editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod code_context_menus;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51use ::git::diff::DiffHunkStatus;
   52pub(crate) use actions::*;
   53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{anyhow, Context as _, Result};
   56use blink_manager::BlinkManager;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::StringMatchCandidate;
   73
   74use code_context_menus::{
   75    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   76    CompletionEntry, CompletionsMenu, ContextMenuOrigin,
   77};
   78use git::blame::GitBlame;
   79use gpui::{
   80    div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
   81    AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
   82    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
   83    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
   84    MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
   85    Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   87    WeakView, WindowContext,
   88};
   89use highlight_matching_bracket::refresh_matching_bracket_highlights;
   90use hover_popover::{hide_hover, HoverState};
   91pub(crate) use hunk_diff::HoveredHunk;
   92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CursorShape, Diagnostic, DiagnosticEntry, Documentation, IndentKind, IndentSize, Language,
  103    OffsetRangeExt, Point, Selection, SelectionGoal, TransactionId,
  104};
  105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  106use linked_editing_ranges::refresh_linked_ranges;
  107use mouse_context_menu::MouseContextMenu;
  108pub use proposed_changes_editor::{
  109    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  110};
  111use similar::{ChangeTag, TextDiff};
  112use std::iter::Peekable;
  113use task::{ResolvedTask, TaskTemplate, TaskVariables};
  114
  115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  116pub use lsp::CompletionContext;
  117use lsp::{
  118    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  119    LanguageServerId, LanguageServerName,
  120};
  121
  122use movement::TextLayoutDetails;
  123pub use multi_buffer::{
  124    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  125    ToPoint,
  126};
  127use multi_buffer::{
  128    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  129};
  130use project::{
  131    buffer_store::BufferChangeSet,
  132    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  133    project_settings::{GitGutterSetting, ProjectSettings},
  134    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  135    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  136};
  137use rand::prelude::*;
  138use rpc::{proto::*, ErrorExt};
  139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  140use selections_collection::{
  141    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  142};
  143use serde::{Deserialize, Serialize};
  144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  145use smallvec::SmallVec;
  146use snippet::Snippet;
  147use std::{
  148    any::TypeId,
  149    borrow::Cow,
  150    cell::RefCell,
  151    cmp::{self, Ordering, Reverse},
  152    mem,
  153    num::NonZeroU32,
  154    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  155    path::{Path, PathBuf},
  156    rc::Rc,
  157    sync::Arc,
  158    time::{Duration, Instant},
  159};
  160pub use sum_tree::Bias;
  161use sum_tree::TreeMap;
  162use text::{BufferId, OffsetUtf16, Rope};
  163use theme::{
  164    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  165    ThemeColors, ThemeSettings,
  166};
  167use ui::{
  168    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  169    PopoverMenuHandle, Tooltip,
  170};
  171use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  172use workspace::item::{ItemHandle, PreviewTabsSettings};
  173use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  174use workspace::{
  175    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  176};
  177use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  178
  179use crate::hover_links::{find_url, find_url_from_range};
  180use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  181
  182pub const FILE_HEADER_HEIGHT: u32 = 2;
  183pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  184pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  185pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  186const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  187const MAX_LINE_LEN: usize = 1024;
  188const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  189const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  190pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  191#[doc(hidden)]
  192pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  193
  194pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  195pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  196
  197pub fn render_parsed_markdown(
  198    element_id: impl Into<ElementId>,
  199    parsed: &language::ParsedMarkdown,
  200    editor_style: &EditorStyle,
  201    workspace: Option<WeakView<Workspace>>,
  202    cx: &mut WindowContext,
  203) -> InteractiveText {
  204    let code_span_background_color = cx
  205        .theme()
  206        .colors()
  207        .editor_document_highlight_read_background;
  208
  209    let highlights = gpui::combine_highlights(
  210        parsed.highlights.iter().filter_map(|(range, highlight)| {
  211            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  212            Some((range.clone(), highlight))
  213        }),
  214        parsed
  215            .regions
  216            .iter()
  217            .zip(&parsed.region_ranges)
  218            .filter_map(|(region, range)| {
  219                if region.code {
  220                    Some((
  221                        range.clone(),
  222                        HighlightStyle {
  223                            background_color: Some(code_span_background_color),
  224                            ..Default::default()
  225                        },
  226                    ))
  227                } else {
  228                    None
  229                }
  230            }),
  231    );
  232
  233    let mut links = Vec::new();
  234    let mut link_ranges = Vec::new();
  235    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  236        if let Some(link) = region.link.clone() {
  237            links.push(link);
  238            link_ranges.push(range.clone());
  239        }
  240    }
  241
  242    InteractiveText::new(
  243        element_id,
  244        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  245    )
  246    .on_click(link_ranges, move |clicked_range_ix, cx| {
  247        match &links[clicked_range_ix] {
  248            markdown::Link::Web { url } => cx.open_url(url),
  249            markdown::Link::Path { path } => {
  250                if let Some(workspace) = &workspace {
  251                    _ = workspace.update(cx, |workspace, cx| {
  252                        workspace.open_abs_path(path.clone(), false, cx).detach();
  253                    });
  254                }
  255            }
  256        }
  257    })
  258}
  259
  260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  261pub enum InlayId {
  262    InlineCompletion(usize),
  263    Hint(usize),
  264}
  265
  266impl InlayId {
  267    fn id(&self) -> usize {
  268        match self {
  269            Self::InlineCompletion(id) => *id,
  270            Self::Hint(id) => *id,
  271        }
  272    }
  273}
  274
  275enum DiffRowHighlight {}
  276enum DocumentHighlightRead {}
  277enum DocumentHighlightWrite {}
  278enum InputComposition {}
  279
  280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  281pub enum Navigated {
  282    Yes,
  283    No,
  284}
  285
  286impl Navigated {
  287    pub fn from_bool(yes: bool) -> Navigated {
  288        if yes {
  289            Navigated::Yes
  290        } else {
  291            Navigated::No
  292        }
  293    }
  294}
  295
  296pub fn init_settings(cx: &mut AppContext) {
  297    EditorSettings::register(cx);
  298}
  299
  300pub fn init(cx: &mut AppContext) {
  301    init_settings(cx);
  302
  303    workspace::register_project_item::<Editor>(cx);
  304    workspace::FollowableViewRegistry::register::<Editor>(cx);
  305    workspace::register_serializable_item::<Editor>(cx);
  306
  307    cx.observe_new_views(
  308        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  309            workspace.register_action(Editor::new_file);
  310            workspace.register_action(Editor::new_file_vertical);
  311            workspace.register_action(Editor::new_file_horizontal);
  312        },
  313    )
  314    .detach();
  315
  316    cx.on_action(move |_: &workspace::NewFile, cx| {
  317        let app_state = workspace::AppState::global(cx);
  318        if let Some(app_state) = app_state.upgrade() {
  319            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  320                Editor::new_file(workspace, &Default::default(), cx)
  321            })
  322            .detach();
  323        }
  324    });
  325    cx.on_action(move |_: &workspace::NewWindow, cx| {
  326        let app_state = workspace::AppState::global(cx);
  327        if let Some(app_state) = app_state.upgrade() {
  328            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  329                Editor::new_file(workspace, &Default::default(), cx)
  330            })
  331            .detach();
  332        }
  333    });
  334    git::project_diff::init(cx);
  335}
  336
  337pub struct SearchWithinRange;
  338
  339trait InvalidationRegion {
  340    fn ranges(&self) -> &[Range<Anchor>];
  341}
  342
  343#[derive(Clone, Debug, PartialEq)]
  344pub enum SelectPhase {
  345    Begin {
  346        position: DisplayPoint,
  347        add: bool,
  348        click_count: usize,
  349    },
  350    BeginColumnar {
  351        position: DisplayPoint,
  352        reset: bool,
  353        goal_column: u32,
  354    },
  355    Extend {
  356        position: DisplayPoint,
  357        click_count: usize,
  358    },
  359    Update {
  360        position: DisplayPoint,
  361        goal_column: u32,
  362        scroll_delta: gpui::Point<f32>,
  363    },
  364    End,
  365}
  366
  367#[derive(Clone, Debug)]
  368pub enum SelectMode {
  369    Character,
  370    Word(Range<Anchor>),
  371    Line(Range<Anchor>),
  372    All,
  373}
  374
  375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  376pub enum EditorMode {
  377    SingleLine { auto_width: bool },
  378    AutoHeight { max_lines: usize },
  379    Full,
  380}
  381
  382#[derive(Copy, Clone, Debug)]
  383pub enum SoftWrap {
  384    /// Prefer not to wrap at all.
  385    ///
  386    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  387    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  388    GitDiff,
  389    /// Prefer a single line generally, unless an overly long line is encountered.
  390    None,
  391    /// Soft wrap lines that exceed the editor width.
  392    EditorWidth,
  393    /// Soft wrap lines at the preferred line length.
  394    Column(u32),
  395    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  396    Bounded(u32),
  397}
  398
  399#[derive(Clone)]
  400pub struct EditorStyle {
  401    pub background: Hsla,
  402    pub local_player: PlayerColor,
  403    pub text: TextStyle,
  404    pub scrollbar_width: Pixels,
  405    pub syntax: Arc<SyntaxTheme>,
  406    pub status: StatusColors,
  407    pub inlay_hints_style: HighlightStyle,
  408    pub inline_completion_styles: InlineCompletionStyles,
  409    pub unnecessary_code_fade: f32,
  410}
  411
  412impl Default for EditorStyle {
  413    fn default() -> Self {
  414        Self {
  415            background: Hsla::default(),
  416            local_player: PlayerColor::default(),
  417            text: TextStyle::default(),
  418            scrollbar_width: Pixels::default(),
  419            syntax: Default::default(),
  420            // HACK: Status colors don't have a real default.
  421            // We should look into removing the status colors from the editor
  422            // style and retrieve them directly from the theme.
  423            status: StatusColors::dark(),
  424            inlay_hints_style: HighlightStyle::default(),
  425            inline_completion_styles: InlineCompletionStyles {
  426                insertion: HighlightStyle::default(),
  427                whitespace: HighlightStyle::default(),
  428            },
  429            unnecessary_code_fade: Default::default(),
  430        }
  431    }
  432}
  433
  434pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  435    let show_background = language_settings::language_settings(None, None, cx)
  436        .inlay_hints
  437        .show_background;
  438
  439    HighlightStyle {
  440        color: Some(cx.theme().status().hint),
  441        background_color: show_background.then(|| cx.theme().status().hint_background),
  442        ..HighlightStyle::default()
  443    }
  444}
  445
  446pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
  447    InlineCompletionStyles {
  448        insertion: HighlightStyle {
  449            color: Some(cx.theme().status().predictive),
  450            ..HighlightStyle::default()
  451        },
  452        whitespace: HighlightStyle {
  453            background_color: Some(cx.theme().status().created_background),
  454            ..HighlightStyle::default()
  455        },
  456    }
  457}
  458
  459type CompletionId = usize;
  460
  461#[derive(Debug, Clone)]
  462struct InlineCompletionMenuHint {
  463    provider_name: &'static str,
  464    text: InlineCompletionText,
  465}
  466
  467#[derive(Clone, Debug)]
  468enum InlineCompletionText {
  469    Move(SharedString),
  470    Edit {
  471        text: SharedString,
  472        highlights: Vec<(Range<usize>, HighlightStyle)>,
  473    },
  474}
  475
  476enum InlineCompletion {
  477    Edit(Vec<(Range<Anchor>, String)>),
  478    Move(Anchor),
  479}
  480
  481struct InlineCompletionState {
  482    inlay_ids: Vec<InlayId>,
  483    completion: InlineCompletion,
  484    invalidation_range: Range<Anchor>,
  485}
  486
  487enum InlineCompletionHighlight {}
  488
  489#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  490struct EditorActionId(usize);
  491
  492impl EditorActionId {
  493    pub fn post_inc(&mut self) -> Self {
  494        let answer = self.0;
  495
  496        *self = Self(answer + 1);
  497
  498        Self(answer)
  499    }
  500}
  501
  502// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  503// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  504
  505type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  506type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  507
  508#[derive(Default)]
  509struct ScrollbarMarkerState {
  510    scrollbar_size: Size<Pixels>,
  511    dirty: bool,
  512    markers: Arc<[PaintQuad]>,
  513    pending_refresh: Option<Task<Result<()>>>,
  514}
  515
  516impl ScrollbarMarkerState {
  517    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  518        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  519    }
  520}
  521
  522#[derive(Clone, Debug)]
  523struct RunnableTasks {
  524    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  525    offset: MultiBufferOffset,
  526    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  527    column: u32,
  528    // Values of all named captures, including those starting with '_'
  529    extra_variables: HashMap<String, String>,
  530    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  531    context_range: Range<BufferOffset>,
  532}
  533
  534impl RunnableTasks {
  535    fn resolve<'a>(
  536        &'a self,
  537        cx: &'a task::TaskContext,
  538    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  539        self.templates.iter().filter_map(|(kind, template)| {
  540            template
  541                .resolve_task(&kind.to_id_base(), cx)
  542                .map(|task| (kind.clone(), task))
  543        })
  544    }
  545}
  546
  547#[derive(Clone)]
  548struct ResolvedTasks {
  549    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  550    position: Anchor,
  551}
  552#[derive(Copy, Clone, Debug)]
  553struct MultiBufferOffset(usize);
  554#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  555struct BufferOffset(usize);
  556
  557// Addons allow storing per-editor state in other crates (e.g. Vim)
  558pub trait Addon: 'static {
  559    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  560
  561    fn to_any(&self) -> &dyn std::any::Any;
  562}
  563
  564#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  565pub enum IsVimMode {
  566    Yes,
  567    No,
  568}
  569
  570/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  571///
  572/// See the [module level documentation](self) for more information.
  573pub struct Editor {
  574    focus_handle: FocusHandle,
  575    last_focused_descendant: Option<WeakFocusHandle>,
  576    /// The text buffer being edited
  577    buffer: Model<MultiBuffer>,
  578    /// Map of how text in the buffer should be displayed.
  579    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  580    pub display_map: Model<DisplayMap>,
  581    pub selections: SelectionsCollection,
  582    pub scroll_manager: ScrollManager,
  583    /// When inline assist editors are linked, they all render cursors because
  584    /// typing enters text into each of them, even the ones that aren't focused.
  585    pub(crate) show_cursor_when_unfocused: bool,
  586    columnar_selection_tail: Option<Anchor>,
  587    add_selections_state: Option<AddSelectionsState>,
  588    select_next_state: Option<SelectNextState>,
  589    select_prev_state: Option<SelectNextState>,
  590    selection_history: SelectionHistory,
  591    autoclose_regions: Vec<AutocloseRegion>,
  592    snippet_stack: InvalidationStack<SnippetState>,
  593    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  594    ime_transaction: Option<TransactionId>,
  595    active_diagnostics: Option<ActiveDiagnosticGroup>,
  596    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  597
  598    project: Option<Model<Project>>,
  599    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  600    completion_provider: Option<Box<dyn CompletionProvider>>,
  601    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  602    blink_manager: Model<BlinkManager>,
  603    show_cursor_names: bool,
  604    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  605    pub show_local_selections: bool,
  606    mode: EditorMode,
  607    show_breadcrumbs: bool,
  608    show_gutter: bool,
  609    show_scrollbars: bool,
  610    show_line_numbers: Option<bool>,
  611    use_relative_line_numbers: Option<bool>,
  612    show_git_diff_gutter: Option<bool>,
  613    show_code_actions: Option<bool>,
  614    show_runnables: Option<bool>,
  615    show_wrap_guides: Option<bool>,
  616    show_indent_guides: Option<bool>,
  617    placeholder_text: Option<Arc<str>>,
  618    highlight_order: usize,
  619    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  620    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  621    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  622    scrollbar_marker_state: ScrollbarMarkerState,
  623    active_indent_guides_state: ActiveIndentGuidesState,
  624    nav_history: Option<ItemNavHistory>,
  625    context_menu: RefCell<Option<CodeContextMenu>>,
  626    mouse_context_menu: Option<MouseContextMenu>,
  627    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  628    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  629    signature_help_state: SignatureHelpState,
  630    auto_signature_help: Option<bool>,
  631    find_all_references_task_sources: Vec<Anchor>,
  632    next_completion_id: CompletionId,
  633    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  634    code_actions_task: Option<Task<Result<()>>>,
  635    document_highlights_task: Option<Task<()>>,
  636    linked_editing_range_task: Option<Task<Option<()>>>,
  637    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  638    pending_rename: Option<RenameState>,
  639    searchable: bool,
  640    cursor_shape: CursorShape,
  641    current_line_highlight: Option<CurrentLineHighlight>,
  642    collapse_matches: bool,
  643    autoindent_mode: Option<AutoindentMode>,
  644    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  645    input_enabled: bool,
  646    use_modal_editing: bool,
  647    read_only: bool,
  648    leader_peer_id: Option<PeerId>,
  649    remote_id: Option<ViewId>,
  650    hover_state: HoverState,
  651    gutter_hovered: bool,
  652    hovered_link_state: Option<HoveredLinkState>,
  653    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  654    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  655    active_inline_completion: Option<InlineCompletionState>,
  656    // enable_inline_completions is a switch that Vim can use to disable
  657    // inline completions based on its mode.
  658    enable_inline_completions: bool,
  659    show_inline_completions_override: Option<bool>,
  660    inlay_hint_cache: InlayHintCache,
  661    diff_map: DiffMap,
  662    next_inlay_id: usize,
  663    _subscriptions: Vec<Subscription>,
  664    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  665    gutter_dimensions: GutterDimensions,
  666    style: Option<EditorStyle>,
  667    text_style_refinement: Option<TextStyleRefinement>,
  668    next_editor_action_id: EditorActionId,
  669    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  670    use_autoclose: bool,
  671    use_auto_surround: bool,
  672    auto_replace_emoji_shortcode: bool,
  673    show_git_blame_gutter: bool,
  674    show_git_blame_inline: bool,
  675    show_git_blame_inline_delay_task: Option<Task<()>>,
  676    git_blame_inline_enabled: bool,
  677    serialize_dirty_buffers: bool,
  678    show_selection_menu: Option<bool>,
  679    blame: Option<Model<GitBlame>>,
  680    blame_subscription: Option<Subscription>,
  681    custom_context_menu: Option<
  682        Box<
  683            dyn 'static
  684                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  685        >,
  686    >,
  687    last_bounds: Option<Bounds<Pixels>>,
  688    expect_bounds_change: Option<Bounds<Pixels>>,
  689    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  690    tasks_update_task: Option<Task<()>>,
  691    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  692    breadcrumb_header: Option<String>,
  693    focused_block: Option<FocusedBlock>,
  694    next_scroll_position: NextScrollCursorCenterTopBottom,
  695    addons: HashMap<TypeId, Box<dyn Addon>>,
  696    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  697    toggle_fold_multiple_buffers: Task<()>,
  698    _scroll_cursor_center_top_bottom_task: Task<()>,
  699}
  700
  701#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  702enum NextScrollCursorCenterTopBottom {
  703    #[default]
  704    Center,
  705    Top,
  706    Bottom,
  707}
  708
  709impl NextScrollCursorCenterTopBottom {
  710    fn next(&self) -> Self {
  711        match self {
  712            Self::Center => Self::Top,
  713            Self::Top => Self::Bottom,
  714            Self::Bottom => Self::Center,
  715        }
  716    }
  717}
  718
  719#[derive(Clone)]
  720pub struct EditorSnapshot {
  721    pub mode: EditorMode,
  722    show_gutter: bool,
  723    show_line_numbers: Option<bool>,
  724    show_git_diff_gutter: Option<bool>,
  725    show_code_actions: Option<bool>,
  726    show_runnables: Option<bool>,
  727    git_blame_gutter_max_author_length: Option<usize>,
  728    pub display_snapshot: DisplaySnapshot,
  729    pub placeholder_text: Option<Arc<str>>,
  730    diff_map: DiffMapSnapshot,
  731    is_focused: bool,
  732    scroll_anchor: ScrollAnchor,
  733    ongoing_scroll: OngoingScroll,
  734    current_line_highlight: CurrentLineHighlight,
  735    gutter_hovered: bool,
  736}
  737
  738const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  739
  740#[derive(Default, Debug, Clone, Copy)]
  741pub struct GutterDimensions {
  742    pub left_padding: Pixels,
  743    pub right_padding: Pixels,
  744    pub width: Pixels,
  745    pub margin: Pixels,
  746    pub git_blame_entries_width: Option<Pixels>,
  747}
  748
  749impl GutterDimensions {
  750    /// The full width of the space taken up by the gutter.
  751    pub fn full_width(&self) -> Pixels {
  752        self.margin + self.width
  753    }
  754
  755    /// The width of the space reserved for the fold indicators,
  756    /// use alongside 'justify_end' and `gutter_width` to
  757    /// right align content with the line numbers
  758    pub fn fold_area_width(&self) -> Pixels {
  759        self.margin + self.right_padding
  760    }
  761}
  762
  763#[derive(Debug)]
  764pub struct RemoteSelection {
  765    pub replica_id: ReplicaId,
  766    pub selection: Selection<Anchor>,
  767    pub cursor_shape: CursorShape,
  768    pub peer_id: PeerId,
  769    pub line_mode: bool,
  770    pub participant_index: Option<ParticipantIndex>,
  771    pub user_name: Option<SharedString>,
  772}
  773
  774#[derive(Clone, Debug)]
  775struct SelectionHistoryEntry {
  776    selections: Arc<[Selection<Anchor>]>,
  777    select_next_state: Option<SelectNextState>,
  778    select_prev_state: Option<SelectNextState>,
  779    add_selections_state: Option<AddSelectionsState>,
  780}
  781
  782enum SelectionHistoryMode {
  783    Normal,
  784    Undoing,
  785    Redoing,
  786}
  787
  788#[derive(Clone, PartialEq, Eq, Hash)]
  789struct HoveredCursor {
  790    replica_id: u16,
  791    selection_id: usize,
  792}
  793
  794impl Default for SelectionHistoryMode {
  795    fn default() -> Self {
  796        Self::Normal
  797    }
  798}
  799
  800#[derive(Default)]
  801struct SelectionHistory {
  802    #[allow(clippy::type_complexity)]
  803    selections_by_transaction:
  804        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  805    mode: SelectionHistoryMode,
  806    undo_stack: VecDeque<SelectionHistoryEntry>,
  807    redo_stack: VecDeque<SelectionHistoryEntry>,
  808}
  809
  810impl SelectionHistory {
  811    fn insert_transaction(
  812        &mut self,
  813        transaction_id: TransactionId,
  814        selections: Arc<[Selection<Anchor>]>,
  815    ) {
  816        self.selections_by_transaction
  817            .insert(transaction_id, (selections, None));
  818    }
  819
  820    #[allow(clippy::type_complexity)]
  821    fn transaction(
  822        &self,
  823        transaction_id: TransactionId,
  824    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  825        self.selections_by_transaction.get(&transaction_id)
  826    }
  827
  828    #[allow(clippy::type_complexity)]
  829    fn transaction_mut(
  830        &mut self,
  831        transaction_id: TransactionId,
  832    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  833        self.selections_by_transaction.get_mut(&transaction_id)
  834    }
  835
  836    fn push(&mut self, entry: SelectionHistoryEntry) {
  837        if !entry.selections.is_empty() {
  838            match self.mode {
  839                SelectionHistoryMode::Normal => {
  840                    self.push_undo(entry);
  841                    self.redo_stack.clear();
  842                }
  843                SelectionHistoryMode::Undoing => self.push_redo(entry),
  844                SelectionHistoryMode::Redoing => self.push_undo(entry),
  845            }
  846        }
  847    }
  848
  849    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  850        if self
  851            .undo_stack
  852            .back()
  853            .map_or(true, |e| e.selections != entry.selections)
  854        {
  855            self.undo_stack.push_back(entry);
  856            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  857                self.undo_stack.pop_front();
  858            }
  859        }
  860    }
  861
  862    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  863        if self
  864            .redo_stack
  865            .back()
  866            .map_or(true, |e| e.selections != entry.selections)
  867        {
  868            self.redo_stack.push_back(entry);
  869            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  870                self.redo_stack.pop_front();
  871            }
  872        }
  873    }
  874}
  875
  876struct RowHighlight {
  877    index: usize,
  878    range: Range<Anchor>,
  879    color: Hsla,
  880    should_autoscroll: bool,
  881}
  882
  883#[derive(Clone, Debug)]
  884struct AddSelectionsState {
  885    above: bool,
  886    stack: Vec<usize>,
  887}
  888
  889#[derive(Clone)]
  890struct SelectNextState {
  891    query: AhoCorasick,
  892    wordwise: bool,
  893    done: bool,
  894}
  895
  896impl std::fmt::Debug for SelectNextState {
  897    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  898        f.debug_struct(std::any::type_name::<Self>())
  899            .field("wordwise", &self.wordwise)
  900            .field("done", &self.done)
  901            .finish()
  902    }
  903}
  904
  905#[derive(Debug)]
  906struct AutocloseRegion {
  907    selection_id: usize,
  908    range: Range<Anchor>,
  909    pair: BracketPair,
  910}
  911
  912#[derive(Debug)]
  913struct SnippetState {
  914    ranges: Vec<Vec<Range<Anchor>>>,
  915    active_index: usize,
  916    choices: Vec<Option<Vec<String>>>,
  917}
  918
  919#[doc(hidden)]
  920pub struct RenameState {
  921    pub range: Range<Anchor>,
  922    pub old_name: Arc<str>,
  923    pub editor: View<Editor>,
  924    block_id: CustomBlockId,
  925}
  926
  927struct InvalidationStack<T>(Vec<T>);
  928
  929struct RegisteredInlineCompletionProvider {
  930    provider: Arc<dyn InlineCompletionProviderHandle>,
  931    _subscription: Subscription,
  932}
  933
  934#[derive(Debug)]
  935struct ActiveDiagnosticGroup {
  936    primary_range: Range<Anchor>,
  937    primary_message: String,
  938    group_id: usize,
  939    blocks: HashMap<CustomBlockId, Diagnostic>,
  940    is_valid: bool,
  941}
  942
  943#[derive(Serialize, Deserialize, Clone, Debug)]
  944pub struct ClipboardSelection {
  945    pub len: usize,
  946    pub is_entire_line: bool,
  947    pub first_line_indent: u32,
  948}
  949
  950#[derive(Debug)]
  951pub(crate) struct NavigationData {
  952    cursor_anchor: Anchor,
  953    cursor_position: Point,
  954    scroll_anchor: ScrollAnchor,
  955    scroll_top_row: u32,
  956}
  957
  958#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  959pub enum GotoDefinitionKind {
  960    Symbol,
  961    Declaration,
  962    Type,
  963    Implementation,
  964}
  965
  966#[derive(Debug, Clone)]
  967enum InlayHintRefreshReason {
  968    Toggle(bool),
  969    SettingsChange(InlayHintSettings),
  970    NewLinesShown,
  971    BufferEdited(HashSet<Arc<Language>>),
  972    RefreshRequested,
  973    ExcerptsRemoved(Vec<ExcerptId>),
  974}
  975
  976impl InlayHintRefreshReason {
  977    fn description(&self) -> &'static str {
  978        match self {
  979            Self::Toggle(_) => "toggle",
  980            Self::SettingsChange(_) => "settings change",
  981            Self::NewLinesShown => "new lines shown",
  982            Self::BufferEdited(_) => "buffer edited",
  983            Self::RefreshRequested => "refresh requested",
  984            Self::ExcerptsRemoved(_) => "excerpts removed",
  985        }
  986    }
  987}
  988
  989pub enum FormatTarget {
  990    Buffers,
  991    Ranges(Vec<Range<MultiBufferPoint>>),
  992}
  993
  994pub(crate) struct FocusedBlock {
  995    id: BlockId,
  996    focus_handle: WeakFocusHandle,
  997}
  998
  999#[derive(Clone)]
 1000enum JumpData {
 1001    MultiBufferRow {
 1002        row: MultiBufferRow,
 1003        line_offset_from_top: u32,
 1004    },
 1005    MultiBufferPoint {
 1006        excerpt_id: ExcerptId,
 1007        position: Point,
 1008        anchor: text::Anchor,
 1009        line_offset_from_top: u32,
 1010    },
 1011}
 1012
 1013impl Editor {
 1014    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1015        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1016        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1017        Self::new(
 1018            EditorMode::SingleLine { auto_width: false },
 1019            buffer,
 1020            None,
 1021            false,
 1022            cx,
 1023        )
 1024    }
 1025
 1026    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1027        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1028        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1029        Self::new(EditorMode::Full, buffer, None, false, cx)
 1030    }
 1031
 1032    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1033        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1034        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1035        Self::new(
 1036            EditorMode::SingleLine { auto_width: true },
 1037            buffer,
 1038            None,
 1039            false,
 1040            cx,
 1041        )
 1042    }
 1043
 1044    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1045        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1046        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1047        Self::new(
 1048            EditorMode::AutoHeight { max_lines },
 1049            buffer,
 1050            None,
 1051            false,
 1052            cx,
 1053        )
 1054    }
 1055
 1056    pub fn for_buffer(
 1057        buffer: Model<Buffer>,
 1058        project: Option<Model<Project>>,
 1059        cx: &mut ViewContext<Self>,
 1060    ) -> Self {
 1061        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1062        Self::new(EditorMode::Full, buffer, project, false, cx)
 1063    }
 1064
 1065    pub fn for_multibuffer(
 1066        buffer: Model<MultiBuffer>,
 1067        project: Option<Model<Project>>,
 1068        show_excerpt_controls: bool,
 1069        cx: &mut ViewContext<Self>,
 1070    ) -> Self {
 1071        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1072    }
 1073
 1074    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1075        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1076        let mut clone = Self::new(
 1077            self.mode,
 1078            self.buffer.clone(),
 1079            self.project.clone(),
 1080            show_excerpt_controls,
 1081            cx,
 1082        );
 1083        self.display_map.update(cx, |display_map, cx| {
 1084            let snapshot = display_map.snapshot(cx);
 1085            clone.display_map.update(cx, |display_map, cx| {
 1086                display_map.set_state(&snapshot, cx);
 1087            });
 1088        });
 1089        clone.selections.clone_state(&self.selections);
 1090        clone.scroll_manager.clone_state(&self.scroll_manager);
 1091        clone.searchable = self.searchable;
 1092        clone
 1093    }
 1094
 1095    pub fn new(
 1096        mode: EditorMode,
 1097        buffer: Model<MultiBuffer>,
 1098        project: Option<Model<Project>>,
 1099        show_excerpt_controls: bool,
 1100        cx: &mut ViewContext<Self>,
 1101    ) -> Self {
 1102        let style = cx.text_style();
 1103        let font_size = style.font_size.to_pixels(cx.rem_size());
 1104        let editor = cx.view().downgrade();
 1105        let fold_placeholder = FoldPlaceholder {
 1106            constrain_width: true,
 1107            render: Arc::new(move |fold_id, fold_range, cx| {
 1108                let editor = editor.clone();
 1109                div()
 1110                    .id(fold_id)
 1111                    .bg(cx.theme().colors().ghost_element_background)
 1112                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1113                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1114                    .rounded_sm()
 1115                    .size_full()
 1116                    .cursor_pointer()
 1117                    .child("")
 1118                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1119                    .on_click(move |_, cx| {
 1120                        editor
 1121                            .update(cx, |editor, cx| {
 1122                                editor.unfold_ranges(
 1123                                    &[fold_range.start..fold_range.end],
 1124                                    true,
 1125                                    false,
 1126                                    cx,
 1127                                );
 1128                                cx.stop_propagation();
 1129                            })
 1130                            .ok();
 1131                    })
 1132                    .into_any()
 1133            }),
 1134            merge_adjacent: true,
 1135            ..Default::default()
 1136        };
 1137        let display_map = cx.new_model(|cx| {
 1138            DisplayMap::new(
 1139                buffer.clone(),
 1140                style.font(),
 1141                font_size,
 1142                None,
 1143                show_excerpt_controls,
 1144                FILE_HEADER_HEIGHT,
 1145                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1146                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1147                fold_placeholder,
 1148                cx,
 1149            )
 1150        });
 1151
 1152        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1153
 1154        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1155
 1156        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1157            .then(|| language_settings::SoftWrap::None);
 1158
 1159        let mut project_subscriptions = Vec::new();
 1160        if mode == EditorMode::Full {
 1161            if let Some(project) = project.as_ref() {
 1162                if buffer.read(cx).is_singleton() {
 1163                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1164                        cx.emit(EditorEvent::TitleChanged);
 1165                    }));
 1166                }
 1167                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1168                    if let project::Event::RefreshInlayHints = event {
 1169                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1170                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1171                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1172                            let focus_handle = editor.focus_handle(cx);
 1173                            if focus_handle.is_focused(cx) {
 1174                                let snapshot = buffer.read(cx).snapshot();
 1175                                for (range, snippet) in snippet_edits {
 1176                                    let editor_range =
 1177                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1178                                    editor
 1179                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1180                                        .ok();
 1181                                }
 1182                            }
 1183                        }
 1184                    }
 1185                }));
 1186                if let Some(task_inventory) = project
 1187                    .read(cx)
 1188                    .task_store()
 1189                    .read(cx)
 1190                    .task_inventory()
 1191                    .cloned()
 1192                {
 1193                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1194                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1195                    }));
 1196                }
 1197            }
 1198        }
 1199
 1200        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1201
 1202        let inlay_hint_settings =
 1203            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1204        let focus_handle = cx.focus_handle();
 1205        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1206        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1207            .detach();
 1208        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1209            .detach();
 1210        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1211
 1212        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1213            Some(false)
 1214        } else {
 1215            None
 1216        };
 1217
 1218        let mut code_action_providers = Vec::new();
 1219        if let Some(project) = project.clone() {
 1220            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1221            code_action_providers.push(Rc::new(project) as Rc<_>);
 1222        }
 1223
 1224        let mut this = Self {
 1225            focus_handle,
 1226            show_cursor_when_unfocused: false,
 1227            last_focused_descendant: None,
 1228            buffer: buffer.clone(),
 1229            display_map: display_map.clone(),
 1230            selections,
 1231            scroll_manager: ScrollManager::new(cx),
 1232            columnar_selection_tail: None,
 1233            add_selections_state: None,
 1234            select_next_state: None,
 1235            select_prev_state: None,
 1236            selection_history: Default::default(),
 1237            autoclose_regions: Default::default(),
 1238            snippet_stack: Default::default(),
 1239            select_larger_syntax_node_stack: Vec::new(),
 1240            ime_transaction: Default::default(),
 1241            active_diagnostics: None,
 1242            soft_wrap_mode_override,
 1243            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1244            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1245            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1246            project,
 1247            blink_manager: blink_manager.clone(),
 1248            show_local_selections: true,
 1249            show_scrollbars: true,
 1250            mode,
 1251            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1252            show_gutter: mode == EditorMode::Full,
 1253            show_line_numbers: None,
 1254            use_relative_line_numbers: None,
 1255            show_git_diff_gutter: None,
 1256            show_code_actions: None,
 1257            show_runnables: None,
 1258            show_wrap_guides: None,
 1259            show_indent_guides,
 1260            placeholder_text: None,
 1261            highlight_order: 0,
 1262            highlighted_rows: HashMap::default(),
 1263            background_highlights: Default::default(),
 1264            gutter_highlights: TreeMap::default(),
 1265            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1266            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1267            nav_history: None,
 1268            context_menu: RefCell::new(None),
 1269            mouse_context_menu: None,
 1270            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1271            completion_tasks: Default::default(),
 1272            signature_help_state: SignatureHelpState::default(),
 1273            auto_signature_help: None,
 1274            find_all_references_task_sources: Vec::new(),
 1275            next_completion_id: 0,
 1276            next_inlay_id: 0,
 1277            code_action_providers,
 1278            available_code_actions: Default::default(),
 1279            code_actions_task: Default::default(),
 1280            document_highlights_task: Default::default(),
 1281            linked_editing_range_task: Default::default(),
 1282            pending_rename: Default::default(),
 1283            searchable: true,
 1284            cursor_shape: EditorSettings::get_global(cx)
 1285                .cursor_shape
 1286                .unwrap_or_default(),
 1287            current_line_highlight: None,
 1288            autoindent_mode: Some(AutoindentMode::EachLine),
 1289            collapse_matches: false,
 1290            workspace: None,
 1291            input_enabled: true,
 1292            use_modal_editing: mode == EditorMode::Full,
 1293            read_only: false,
 1294            use_autoclose: true,
 1295            use_auto_surround: true,
 1296            auto_replace_emoji_shortcode: false,
 1297            leader_peer_id: None,
 1298            remote_id: None,
 1299            hover_state: Default::default(),
 1300            hovered_link_state: Default::default(),
 1301            inline_completion_provider: None,
 1302            active_inline_completion: None,
 1303            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1304            diff_map: DiffMap::default(),
 1305            gutter_hovered: false,
 1306            pixel_position_of_newest_cursor: None,
 1307            last_bounds: None,
 1308            expect_bounds_change: None,
 1309            gutter_dimensions: GutterDimensions::default(),
 1310            style: None,
 1311            show_cursor_names: false,
 1312            hovered_cursors: Default::default(),
 1313            next_editor_action_id: EditorActionId::default(),
 1314            editor_actions: Rc::default(),
 1315            show_inline_completions_override: None,
 1316            enable_inline_completions: true,
 1317            custom_context_menu: None,
 1318            show_git_blame_gutter: false,
 1319            show_git_blame_inline: false,
 1320            show_selection_menu: None,
 1321            show_git_blame_inline_delay_task: None,
 1322            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1323            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1324                .session
 1325                .restore_unsaved_buffers,
 1326            blame: None,
 1327            blame_subscription: None,
 1328            tasks: Default::default(),
 1329            _subscriptions: vec![
 1330                cx.observe(&buffer, Self::on_buffer_changed),
 1331                cx.subscribe(&buffer, Self::on_buffer_event),
 1332                cx.observe(&display_map, Self::on_display_map_changed),
 1333                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1334                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1335                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1336                cx.observe_window_activation(|editor, cx| {
 1337                    let active = cx.is_window_active();
 1338                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1339                        if active {
 1340                            blink_manager.enable(cx);
 1341                        } else {
 1342                            blink_manager.disable(cx);
 1343                        }
 1344                    });
 1345                }),
 1346            ],
 1347            tasks_update_task: None,
 1348            linked_edit_ranges: Default::default(),
 1349            previous_search_ranges: None,
 1350            breadcrumb_header: None,
 1351            focused_block: None,
 1352            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1353            addons: HashMap::default(),
 1354            registered_buffers: HashMap::default(),
 1355            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1356            toggle_fold_multiple_buffers: Task::ready(()),
 1357            text_style_refinement: None,
 1358        };
 1359        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1360        this._subscriptions.extend(project_subscriptions);
 1361
 1362        this.end_selection(cx);
 1363        this.scroll_manager.show_scrollbar(cx);
 1364
 1365        if mode == EditorMode::Full {
 1366            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1367            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1368
 1369            if this.git_blame_inline_enabled {
 1370                this.git_blame_inline_enabled = true;
 1371                this.start_git_blame_inline(false, cx);
 1372            }
 1373
 1374            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1375                if let Some(project) = this.project.as_ref() {
 1376                    let lsp_store = project.read(cx).lsp_store();
 1377                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1378                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1379                    });
 1380                    this.registered_buffers
 1381                        .insert(buffer.read(cx).remote_id(), handle);
 1382                }
 1383            }
 1384        }
 1385
 1386        this.report_editor_event("Editor Opened", None, cx);
 1387        this
 1388    }
 1389
 1390    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1391        self.mouse_context_menu
 1392            .as_ref()
 1393            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1394    }
 1395
 1396    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1397        let mut key_context = KeyContext::new_with_defaults();
 1398        key_context.add("Editor");
 1399        let mode = match self.mode {
 1400            EditorMode::SingleLine { .. } => "single_line",
 1401            EditorMode::AutoHeight { .. } => "auto_height",
 1402            EditorMode::Full => "full",
 1403        };
 1404
 1405        if EditorSettings::jupyter_enabled(cx) {
 1406            key_context.add("jupyter");
 1407        }
 1408
 1409        key_context.set("mode", mode);
 1410        if self.pending_rename.is_some() {
 1411            key_context.add("renaming");
 1412        }
 1413        match self.context_menu.borrow().as_ref() {
 1414            Some(CodeContextMenu::Completions(_)) => {
 1415                key_context.add("menu");
 1416                key_context.add("showing_completions")
 1417            }
 1418            Some(CodeContextMenu::CodeActions(_)) => {
 1419                key_context.add("menu");
 1420                key_context.add("showing_code_actions")
 1421            }
 1422            None => {}
 1423        }
 1424
 1425        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1426        if !self.focus_handle(cx).contains_focused(cx)
 1427            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1428        {
 1429            for addon in self.addons.values() {
 1430                addon.extend_key_context(&mut key_context, cx)
 1431            }
 1432        }
 1433
 1434        if let Some(extension) = self
 1435            .buffer
 1436            .read(cx)
 1437            .as_singleton()
 1438            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1439        {
 1440            key_context.set("extension", extension.to_string());
 1441        }
 1442
 1443        if self.has_active_inline_completion() {
 1444            key_context.add("copilot_suggestion");
 1445            key_context.add("inline_completion");
 1446        }
 1447
 1448        if !self
 1449            .selections
 1450            .disjoint
 1451            .iter()
 1452            .all(|selection| selection.start == selection.end)
 1453        {
 1454            key_context.add("selection");
 1455        }
 1456
 1457        key_context
 1458    }
 1459
 1460    pub fn new_file(
 1461        workspace: &mut Workspace,
 1462        _: &workspace::NewFile,
 1463        cx: &mut ViewContext<Workspace>,
 1464    ) {
 1465        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1466            "Failed to create buffer",
 1467            cx,
 1468            |e, _| match e.error_code() {
 1469                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1470                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1471                e.error_tag("required").unwrap_or("the latest version")
 1472            )),
 1473                _ => None,
 1474            },
 1475        );
 1476    }
 1477
 1478    pub fn new_in_workspace(
 1479        workspace: &mut Workspace,
 1480        cx: &mut ViewContext<Workspace>,
 1481    ) -> Task<Result<View<Editor>>> {
 1482        let project = workspace.project().clone();
 1483        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1484
 1485        cx.spawn(|workspace, mut cx| async move {
 1486            let buffer = create.await?;
 1487            workspace.update(&mut cx, |workspace, cx| {
 1488                let editor =
 1489                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1490                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1491                editor
 1492            })
 1493        })
 1494    }
 1495
 1496    fn new_file_vertical(
 1497        workspace: &mut Workspace,
 1498        _: &workspace::NewFileSplitVertical,
 1499        cx: &mut ViewContext<Workspace>,
 1500    ) {
 1501        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1502    }
 1503
 1504    fn new_file_horizontal(
 1505        workspace: &mut Workspace,
 1506        _: &workspace::NewFileSplitHorizontal,
 1507        cx: &mut ViewContext<Workspace>,
 1508    ) {
 1509        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1510    }
 1511
 1512    fn new_file_in_direction(
 1513        workspace: &mut Workspace,
 1514        direction: SplitDirection,
 1515        cx: &mut ViewContext<Workspace>,
 1516    ) {
 1517        let project = workspace.project().clone();
 1518        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1519
 1520        cx.spawn(|workspace, mut cx| async move {
 1521            let buffer = create.await?;
 1522            workspace.update(&mut cx, move |workspace, cx| {
 1523                workspace.split_item(
 1524                    direction,
 1525                    Box::new(
 1526                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1527                    ),
 1528                    cx,
 1529                )
 1530            })?;
 1531            anyhow::Ok(())
 1532        })
 1533        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1534            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1535                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1536                e.error_tag("required").unwrap_or("the latest version")
 1537            )),
 1538            _ => None,
 1539        });
 1540    }
 1541
 1542    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1543        self.leader_peer_id
 1544    }
 1545
 1546    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1547        &self.buffer
 1548    }
 1549
 1550    pub fn workspace(&self) -> Option<View<Workspace>> {
 1551        self.workspace.as_ref()?.0.upgrade()
 1552    }
 1553
 1554    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1555        self.buffer().read(cx).title(cx)
 1556    }
 1557
 1558    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1559        let git_blame_gutter_max_author_length = self
 1560            .render_git_blame_gutter(cx)
 1561            .then(|| {
 1562                if let Some(blame) = self.blame.as_ref() {
 1563                    let max_author_length =
 1564                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1565                    Some(max_author_length)
 1566                } else {
 1567                    None
 1568                }
 1569            })
 1570            .flatten();
 1571
 1572        EditorSnapshot {
 1573            mode: self.mode,
 1574            show_gutter: self.show_gutter,
 1575            show_line_numbers: self.show_line_numbers,
 1576            show_git_diff_gutter: self.show_git_diff_gutter,
 1577            show_code_actions: self.show_code_actions,
 1578            show_runnables: self.show_runnables,
 1579            git_blame_gutter_max_author_length,
 1580            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1581            scroll_anchor: self.scroll_manager.anchor(),
 1582            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1583            placeholder_text: self.placeholder_text.clone(),
 1584            diff_map: self.diff_map.snapshot(),
 1585            is_focused: self.focus_handle.is_focused(cx),
 1586            current_line_highlight: self
 1587                .current_line_highlight
 1588                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1589            gutter_hovered: self.gutter_hovered,
 1590        }
 1591    }
 1592
 1593    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1594        self.buffer.read(cx).language_at(point, cx)
 1595    }
 1596
 1597    pub fn file_at<T: ToOffset>(
 1598        &self,
 1599        point: T,
 1600        cx: &AppContext,
 1601    ) -> Option<Arc<dyn language::File>> {
 1602        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1603    }
 1604
 1605    pub fn active_excerpt(
 1606        &self,
 1607        cx: &AppContext,
 1608    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1609        self.buffer
 1610            .read(cx)
 1611            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1612    }
 1613
 1614    pub fn mode(&self) -> EditorMode {
 1615        self.mode
 1616    }
 1617
 1618    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1619        self.collaboration_hub.as_deref()
 1620    }
 1621
 1622    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1623        self.collaboration_hub = Some(hub);
 1624    }
 1625
 1626    pub fn set_custom_context_menu(
 1627        &mut self,
 1628        f: impl 'static
 1629            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1630    ) {
 1631        self.custom_context_menu = Some(Box::new(f))
 1632    }
 1633
 1634    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1635        self.completion_provider = provider;
 1636    }
 1637
 1638    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1639        self.semantics_provider.clone()
 1640    }
 1641
 1642    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1643        self.semantics_provider = provider;
 1644    }
 1645
 1646    pub fn set_inline_completion_provider<T>(
 1647        &mut self,
 1648        provider: Option<Model<T>>,
 1649        cx: &mut ViewContext<Self>,
 1650    ) where
 1651        T: InlineCompletionProvider,
 1652    {
 1653        self.inline_completion_provider =
 1654            provider.map(|provider| RegisteredInlineCompletionProvider {
 1655                _subscription: cx.observe(&provider, |this, _, cx| {
 1656                    if this.focus_handle.is_focused(cx) {
 1657                        this.update_visible_inline_completion(cx);
 1658                    }
 1659                }),
 1660                provider: Arc::new(provider),
 1661            });
 1662        self.refresh_inline_completion(false, false, cx);
 1663    }
 1664
 1665    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1666        self.placeholder_text.as_deref()
 1667    }
 1668
 1669    pub fn set_placeholder_text(
 1670        &mut self,
 1671        placeholder_text: impl Into<Arc<str>>,
 1672        cx: &mut ViewContext<Self>,
 1673    ) {
 1674        let placeholder_text = Some(placeholder_text.into());
 1675        if self.placeholder_text != placeholder_text {
 1676            self.placeholder_text = placeholder_text;
 1677            cx.notify();
 1678        }
 1679    }
 1680
 1681    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1682        self.cursor_shape = cursor_shape;
 1683
 1684        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1685        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1686
 1687        cx.notify();
 1688    }
 1689
 1690    pub fn set_current_line_highlight(
 1691        &mut self,
 1692        current_line_highlight: Option<CurrentLineHighlight>,
 1693    ) {
 1694        self.current_line_highlight = current_line_highlight;
 1695    }
 1696
 1697    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1698        self.collapse_matches = collapse_matches;
 1699    }
 1700
 1701    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1702        let buffers = self.buffer.read(cx).all_buffers();
 1703        let Some(lsp_store) = self.lsp_store(cx) else {
 1704            return;
 1705        };
 1706        lsp_store.update(cx, |lsp_store, cx| {
 1707            for buffer in buffers {
 1708                self.registered_buffers
 1709                    .entry(buffer.read(cx).remote_id())
 1710                    .or_insert_with(|| {
 1711                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1712                    });
 1713            }
 1714        })
 1715    }
 1716
 1717    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1718        if self.collapse_matches {
 1719            return range.start..range.start;
 1720        }
 1721        range.clone()
 1722    }
 1723
 1724    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1725        if self.display_map.read(cx).clip_at_line_ends != clip {
 1726            self.display_map
 1727                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1728        }
 1729    }
 1730
 1731    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1732        self.input_enabled = input_enabled;
 1733    }
 1734
 1735    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 1736        self.enable_inline_completions = enabled;
 1737    }
 1738
 1739    pub fn set_autoindent(&mut self, autoindent: bool) {
 1740        if autoindent {
 1741            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1742        } else {
 1743            self.autoindent_mode = None;
 1744        }
 1745    }
 1746
 1747    pub fn read_only(&self, cx: &AppContext) -> bool {
 1748        self.read_only || self.buffer.read(cx).read_only()
 1749    }
 1750
 1751    pub fn set_read_only(&mut self, read_only: bool) {
 1752        self.read_only = read_only;
 1753    }
 1754
 1755    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1756        self.use_autoclose = autoclose;
 1757    }
 1758
 1759    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1760        self.use_auto_surround = auto_surround;
 1761    }
 1762
 1763    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1764        self.auto_replace_emoji_shortcode = auto_replace;
 1765    }
 1766
 1767    pub fn toggle_inline_completions(
 1768        &mut self,
 1769        _: &ToggleInlineCompletions,
 1770        cx: &mut ViewContext<Self>,
 1771    ) {
 1772        if self.show_inline_completions_override.is_some() {
 1773            self.set_show_inline_completions(None, cx);
 1774        } else {
 1775            let cursor = self.selections.newest_anchor().head();
 1776            if let Some((buffer, cursor_buffer_position)) =
 1777                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1778            {
 1779                let show_inline_completions =
 1780                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1781                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1782            }
 1783        }
 1784    }
 1785
 1786    pub fn set_show_inline_completions(
 1787        &mut self,
 1788        show_inline_completions: Option<bool>,
 1789        cx: &mut ViewContext<Self>,
 1790    ) {
 1791        self.show_inline_completions_override = show_inline_completions;
 1792        self.refresh_inline_completion(false, true, cx);
 1793    }
 1794
 1795    pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
 1796        let cursor = self.selections.newest_anchor().head();
 1797        if let Some((buffer, buffer_position)) =
 1798            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1799        {
 1800            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1801        } else {
 1802            false
 1803        }
 1804    }
 1805
 1806    fn should_show_inline_completions(
 1807        &self,
 1808        buffer: &Model<Buffer>,
 1809        buffer_position: language::Anchor,
 1810        cx: &AppContext,
 1811    ) -> bool {
 1812        if !self.snippet_stack.is_empty() {
 1813            return false;
 1814        }
 1815
 1816        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1817            return false;
 1818        }
 1819
 1820        if let Some(provider) = self.inline_completion_provider() {
 1821            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1822                show_inline_completions
 1823            } else {
 1824                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1825            }
 1826        } else {
 1827            false
 1828        }
 1829    }
 1830
 1831    fn inline_completions_disabled_in_scope(
 1832        &self,
 1833        buffer: &Model<Buffer>,
 1834        buffer_position: language::Anchor,
 1835        cx: &AppContext,
 1836    ) -> bool {
 1837        let snapshot = buffer.read(cx).snapshot();
 1838        let settings = snapshot.settings_at(buffer_position, cx);
 1839
 1840        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1841            return false;
 1842        };
 1843
 1844        scope.override_name().map_or(false, |scope_name| {
 1845            settings
 1846                .inline_completions_disabled_in
 1847                .iter()
 1848                .any(|s| s == scope_name)
 1849        })
 1850    }
 1851
 1852    pub fn set_use_modal_editing(&mut self, to: bool) {
 1853        self.use_modal_editing = to;
 1854    }
 1855
 1856    pub fn use_modal_editing(&self) -> bool {
 1857        self.use_modal_editing
 1858    }
 1859
 1860    fn selections_did_change(
 1861        &mut self,
 1862        local: bool,
 1863        old_cursor_position: &Anchor,
 1864        show_completions: bool,
 1865        cx: &mut ViewContext<Self>,
 1866    ) {
 1867        cx.invalidate_character_coordinates();
 1868
 1869        // Copy selections to primary selection buffer
 1870        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1871        if local {
 1872            let selections = self.selections.all::<usize>(cx);
 1873            let buffer_handle = self.buffer.read(cx).read(cx);
 1874
 1875            let mut text = String::new();
 1876            for (index, selection) in selections.iter().enumerate() {
 1877                let text_for_selection = buffer_handle
 1878                    .text_for_range(selection.start..selection.end)
 1879                    .collect::<String>();
 1880
 1881                text.push_str(&text_for_selection);
 1882                if index != selections.len() - 1 {
 1883                    text.push('\n');
 1884                }
 1885            }
 1886
 1887            if !text.is_empty() {
 1888                cx.write_to_primary(ClipboardItem::new_string(text));
 1889            }
 1890        }
 1891
 1892        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1893            self.buffer.update(cx, |buffer, cx| {
 1894                buffer.set_active_selections(
 1895                    &self.selections.disjoint_anchors(),
 1896                    self.selections.line_mode,
 1897                    self.cursor_shape,
 1898                    cx,
 1899                )
 1900            });
 1901        }
 1902        let display_map = self
 1903            .display_map
 1904            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1905        let buffer = &display_map.buffer_snapshot;
 1906        self.add_selections_state = None;
 1907        self.select_next_state = None;
 1908        self.select_prev_state = None;
 1909        self.select_larger_syntax_node_stack.clear();
 1910        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1911        self.snippet_stack
 1912            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1913        self.take_rename(false, cx);
 1914
 1915        let new_cursor_position = self.selections.newest_anchor().head();
 1916
 1917        self.push_to_nav_history(
 1918            *old_cursor_position,
 1919            Some(new_cursor_position.to_point(buffer)),
 1920            cx,
 1921        );
 1922
 1923        if local {
 1924            let new_cursor_position = self.selections.newest_anchor().head();
 1925            let mut context_menu = self.context_menu.borrow_mut();
 1926            let completion_menu = match context_menu.as_ref() {
 1927                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1928                _ => {
 1929                    *context_menu = None;
 1930                    None
 1931                }
 1932            };
 1933
 1934            if let Some(completion_menu) = completion_menu {
 1935                let cursor_position = new_cursor_position.to_offset(buffer);
 1936                let (word_range, kind) =
 1937                    buffer.surrounding_word(completion_menu.initial_position, true);
 1938                if kind == Some(CharKind::Word)
 1939                    && word_range.to_inclusive().contains(&cursor_position)
 1940                {
 1941                    let mut completion_menu = completion_menu.clone();
 1942                    drop(context_menu);
 1943
 1944                    let query = Self::completion_query(buffer, cursor_position);
 1945                    cx.spawn(move |this, mut cx| async move {
 1946                        completion_menu
 1947                            .filter(query.as_deref(), cx.background_executor().clone())
 1948                            .await;
 1949
 1950                        this.update(&mut cx, |this, cx| {
 1951                            let mut context_menu = this.context_menu.borrow_mut();
 1952                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1953                            else {
 1954                                return;
 1955                            };
 1956
 1957                            if menu.id > completion_menu.id {
 1958                                return;
 1959                            }
 1960
 1961                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1962                            drop(context_menu);
 1963                            cx.notify();
 1964                        })
 1965                    })
 1966                    .detach();
 1967
 1968                    if show_completions {
 1969                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1970                    }
 1971                } else {
 1972                    drop(context_menu);
 1973                    self.hide_context_menu(cx);
 1974                }
 1975            } else {
 1976                drop(context_menu);
 1977            }
 1978
 1979            hide_hover(self, cx);
 1980
 1981            if old_cursor_position.to_display_point(&display_map).row()
 1982                != new_cursor_position.to_display_point(&display_map).row()
 1983            {
 1984                self.available_code_actions.take();
 1985            }
 1986            self.refresh_code_actions(cx);
 1987            self.refresh_document_highlights(cx);
 1988            refresh_matching_bracket_highlights(self, cx);
 1989            self.update_visible_inline_completion(cx);
 1990            linked_editing_ranges::refresh_linked_ranges(self, cx);
 1991            if self.git_blame_inline_enabled {
 1992                self.start_inline_blame_timer(cx);
 1993            }
 1994        }
 1995
 1996        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 1997        cx.emit(EditorEvent::SelectionsChanged { local });
 1998
 1999        if self.selections.disjoint_anchors().len() == 1 {
 2000            cx.emit(SearchEvent::ActiveMatchChanged)
 2001        }
 2002        cx.notify();
 2003    }
 2004
 2005    pub fn change_selections<R>(
 2006        &mut self,
 2007        autoscroll: Option<Autoscroll>,
 2008        cx: &mut ViewContext<Self>,
 2009        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2010    ) -> R {
 2011        self.change_selections_inner(autoscroll, true, cx, change)
 2012    }
 2013
 2014    pub fn change_selections_inner<R>(
 2015        &mut self,
 2016        autoscroll: Option<Autoscroll>,
 2017        request_completions: bool,
 2018        cx: &mut ViewContext<Self>,
 2019        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2020    ) -> R {
 2021        let old_cursor_position = self.selections.newest_anchor().head();
 2022        self.push_to_selection_history();
 2023
 2024        let (changed, result) = self.selections.change_with(cx, change);
 2025
 2026        if changed {
 2027            if let Some(autoscroll) = autoscroll {
 2028                self.request_autoscroll(autoscroll, cx);
 2029            }
 2030            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2031
 2032            if self.should_open_signature_help_automatically(
 2033                &old_cursor_position,
 2034                self.signature_help_state.backspace_pressed(),
 2035                cx,
 2036            ) {
 2037                self.show_signature_help(&ShowSignatureHelp, cx);
 2038            }
 2039            self.signature_help_state.set_backspace_pressed(false);
 2040        }
 2041
 2042        result
 2043    }
 2044
 2045    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2046    where
 2047        I: IntoIterator<Item = (Range<S>, T)>,
 2048        S: ToOffset,
 2049        T: Into<Arc<str>>,
 2050    {
 2051        if self.read_only(cx) {
 2052            return;
 2053        }
 2054
 2055        self.buffer
 2056            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2057    }
 2058
 2059    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2060    where
 2061        I: IntoIterator<Item = (Range<S>, T)>,
 2062        S: ToOffset,
 2063        T: Into<Arc<str>>,
 2064    {
 2065        if self.read_only(cx) {
 2066            return;
 2067        }
 2068
 2069        self.buffer.update(cx, |buffer, cx| {
 2070            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2071        });
 2072    }
 2073
 2074    pub fn edit_with_block_indent<I, S, T>(
 2075        &mut self,
 2076        edits: I,
 2077        original_indent_columns: Vec<u32>,
 2078        cx: &mut ViewContext<Self>,
 2079    ) where
 2080        I: IntoIterator<Item = (Range<S>, T)>,
 2081        S: ToOffset,
 2082        T: Into<Arc<str>>,
 2083    {
 2084        if self.read_only(cx) {
 2085            return;
 2086        }
 2087
 2088        self.buffer.update(cx, |buffer, cx| {
 2089            buffer.edit(
 2090                edits,
 2091                Some(AutoindentMode::Block {
 2092                    original_indent_columns,
 2093                }),
 2094                cx,
 2095            )
 2096        });
 2097    }
 2098
 2099    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2100        self.hide_context_menu(cx);
 2101
 2102        match phase {
 2103            SelectPhase::Begin {
 2104                position,
 2105                add,
 2106                click_count,
 2107            } => self.begin_selection(position, add, click_count, cx),
 2108            SelectPhase::BeginColumnar {
 2109                position,
 2110                goal_column,
 2111                reset,
 2112            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2113            SelectPhase::Extend {
 2114                position,
 2115                click_count,
 2116            } => self.extend_selection(position, click_count, cx),
 2117            SelectPhase::Update {
 2118                position,
 2119                goal_column,
 2120                scroll_delta,
 2121            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2122            SelectPhase::End => self.end_selection(cx),
 2123        }
 2124    }
 2125
 2126    fn extend_selection(
 2127        &mut self,
 2128        position: DisplayPoint,
 2129        click_count: usize,
 2130        cx: &mut ViewContext<Self>,
 2131    ) {
 2132        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2133        let tail = self.selections.newest::<usize>(cx).tail();
 2134        self.begin_selection(position, false, click_count, cx);
 2135
 2136        let position = position.to_offset(&display_map, Bias::Left);
 2137        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2138
 2139        let mut pending_selection = self
 2140            .selections
 2141            .pending_anchor()
 2142            .expect("extend_selection not called with pending selection");
 2143        if position >= tail {
 2144            pending_selection.start = tail_anchor;
 2145        } else {
 2146            pending_selection.end = tail_anchor;
 2147            pending_selection.reversed = true;
 2148        }
 2149
 2150        let mut pending_mode = self.selections.pending_mode().unwrap();
 2151        match &mut pending_mode {
 2152            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2153            _ => {}
 2154        }
 2155
 2156        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2157            s.set_pending(pending_selection, pending_mode)
 2158        });
 2159    }
 2160
 2161    fn begin_selection(
 2162        &mut self,
 2163        position: DisplayPoint,
 2164        add: bool,
 2165        click_count: usize,
 2166        cx: &mut ViewContext<Self>,
 2167    ) {
 2168        if !self.focus_handle.is_focused(cx) {
 2169            self.last_focused_descendant = None;
 2170            cx.focus(&self.focus_handle);
 2171        }
 2172
 2173        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2174        let buffer = &display_map.buffer_snapshot;
 2175        let newest_selection = self.selections.newest_anchor().clone();
 2176        let position = display_map.clip_point(position, Bias::Left);
 2177
 2178        let start;
 2179        let end;
 2180        let mode;
 2181        let mut auto_scroll;
 2182        match click_count {
 2183            1 => {
 2184                start = buffer.anchor_before(position.to_point(&display_map));
 2185                end = start;
 2186                mode = SelectMode::Character;
 2187                auto_scroll = true;
 2188            }
 2189            2 => {
 2190                let range = movement::surrounding_word(&display_map, position);
 2191                start = buffer.anchor_before(range.start.to_point(&display_map));
 2192                end = buffer.anchor_before(range.end.to_point(&display_map));
 2193                mode = SelectMode::Word(start..end);
 2194                auto_scroll = true;
 2195            }
 2196            3 => {
 2197                let position = display_map
 2198                    .clip_point(position, Bias::Left)
 2199                    .to_point(&display_map);
 2200                let line_start = display_map.prev_line_boundary(position).0;
 2201                let next_line_start = buffer.clip_point(
 2202                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2203                    Bias::Left,
 2204                );
 2205                start = buffer.anchor_before(line_start);
 2206                end = buffer.anchor_before(next_line_start);
 2207                mode = SelectMode::Line(start..end);
 2208                auto_scroll = true;
 2209            }
 2210            _ => {
 2211                start = buffer.anchor_before(0);
 2212                end = buffer.anchor_before(buffer.len());
 2213                mode = SelectMode::All;
 2214                auto_scroll = false;
 2215            }
 2216        }
 2217        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2218
 2219        let point_to_delete: Option<usize> = {
 2220            let selected_points: Vec<Selection<Point>> =
 2221                self.selections.disjoint_in_range(start..end, cx);
 2222
 2223            if !add || click_count > 1 {
 2224                None
 2225            } else if !selected_points.is_empty() {
 2226                Some(selected_points[0].id)
 2227            } else {
 2228                let clicked_point_already_selected =
 2229                    self.selections.disjoint.iter().find(|selection| {
 2230                        selection.start.to_point(buffer) == start.to_point(buffer)
 2231                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2232                    });
 2233
 2234                clicked_point_already_selected.map(|selection| selection.id)
 2235            }
 2236        };
 2237
 2238        let selections_count = self.selections.count();
 2239
 2240        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2241            if let Some(point_to_delete) = point_to_delete {
 2242                s.delete(point_to_delete);
 2243
 2244                if selections_count == 1 {
 2245                    s.set_pending_anchor_range(start..end, mode);
 2246                }
 2247            } else {
 2248                if !add {
 2249                    s.clear_disjoint();
 2250                } else if click_count > 1 {
 2251                    s.delete(newest_selection.id)
 2252                }
 2253
 2254                s.set_pending_anchor_range(start..end, mode);
 2255            }
 2256        });
 2257    }
 2258
 2259    fn begin_columnar_selection(
 2260        &mut self,
 2261        position: DisplayPoint,
 2262        goal_column: u32,
 2263        reset: bool,
 2264        cx: &mut ViewContext<Self>,
 2265    ) {
 2266        if !self.focus_handle.is_focused(cx) {
 2267            self.last_focused_descendant = None;
 2268            cx.focus(&self.focus_handle);
 2269        }
 2270
 2271        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2272
 2273        if reset {
 2274            let pointer_position = display_map
 2275                .buffer_snapshot
 2276                .anchor_before(position.to_point(&display_map));
 2277
 2278            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2279                s.clear_disjoint();
 2280                s.set_pending_anchor_range(
 2281                    pointer_position..pointer_position,
 2282                    SelectMode::Character,
 2283                );
 2284            });
 2285        }
 2286
 2287        let tail = self.selections.newest::<Point>(cx).tail();
 2288        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2289
 2290        if !reset {
 2291            self.select_columns(
 2292                tail.to_display_point(&display_map),
 2293                position,
 2294                goal_column,
 2295                &display_map,
 2296                cx,
 2297            );
 2298        }
 2299    }
 2300
 2301    fn update_selection(
 2302        &mut self,
 2303        position: DisplayPoint,
 2304        goal_column: u32,
 2305        scroll_delta: gpui::Point<f32>,
 2306        cx: &mut ViewContext<Self>,
 2307    ) {
 2308        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2309
 2310        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2311            let tail = tail.to_display_point(&display_map);
 2312            self.select_columns(tail, position, goal_column, &display_map, cx);
 2313        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2314            let buffer = self.buffer.read(cx).snapshot(cx);
 2315            let head;
 2316            let tail;
 2317            let mode = self.selections.pending_mode().unwrap();
 2318            match &mode {
 2319                SelectMode::Character => {
 2320                    head = position.to_point(&display_map);
 2321                    tail = pending.tail().to_point(&buffer);
 2322                }
 2323                SelectMode::Word(original_range) => {
 2324                    let original_display_range = original_range.start.to_display_point(&display_map)
 2325                        ..original_range.end.to_display_point(&display_map);
 2326                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2327                        ..original_display_range.end.to_point(&display_map);
 2328                    if movement::is_inside_word(&display_map, position)
 2329                        || original_display_range.contains(&position)
 2330                    {
 2331                        let word_range = movement::surrounding_word(&display_map, position);
 2332                        if word_range.start < original_display_range.start {
 2333                            head = word_range.start.to_point(&display_map);
 2334                        } else {
 2335                            head = word_range.end.to_point(&display_map);
 2336                        }
 2337                    } else {
 2338                        head = position.to_point(&display_map);
 2339                    }
 2340
 2341                    if head <= original_buffer_range.start {
 2342                        tail = original_buffer_range.end;
 2343                    } else {
 2344                        tail = original_buffer_range.start;
 2345                    }
 2346                }
 2347                SelectMode::Line(original_range) => {
 2348                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2349
 2350                    let position = display_map
 2351                        .clip_point(position, Bias::Left)
 2352                        .to_point(&display_map);
 2353                    let line_start = display_map.prev_line_boundary(position).0;
 2354                    let next_line_start = buffer.clip_point(
 2355                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2356                        Bias::Left,
 2357                    );
 2358
 2359                    if line_start < original_range.start {
 2360                        head = line_start
 2361                    } else {
 2362                        head = next_line_start
 2363                    }
 2364
 2365                    if head <= original_range.start {
 2366                        tail = original_range.end;
 2367                    } else {
 2368                        tail = original_range.start;
 2369                    }
 2370                }
 2371                SelectMode::All => {
 2372                    return;
 2373                }
 2374            };
 2375
 2376            if head < tail {
 2377                pending.start = buffer.anchor_before(head);
 2378                pending.end = buffer.anchor_before(tail);
 2379                pending.reversed = true;
 2380            } else {
 2381                pending.start = buffer.anchor_before(tail);
 2382                pending.end = buffer.anchor_before(head);
 2383                pending.reversed = false;
 2384            }
 2385
 2386            self.change_selections(None, cx, |s| {
 2387                s.set_pending(pending, mode);
 2388            });
 2389        } else {
 2390            log::error!("update_selection dispatched with no pending selection");
 2391            return;
 2392        }
 2393
 2394        self.apply_scroll_delta(scroll_delta, cx);
 2395        cx.notify();
 2396    }
 2397
 2398    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2399        self.columnar_selection_tail.take();
 2400        if self.selections.pending_anchor().is_some() {
 2401            let selections = self.selections.all::<usize>(cx);
 2402            self.change_selections(None, cx, |s| {
 2403                s.select(selections);
 2404                s.clear_pending();
 2405            });
 2406        }
 2407    }
 2408
 2409    fn select_columns(
 2410        &mut self,
 2411        tail: DisplayPoint,
 2412        head: DisplayPoint,
 2413        goal_column: u32,
 2414        display_map: &DisplaySnapshot,
 2415        cx: &mut ViewContext<Self>,
 2416    ) {
 2417        let start_row = cmp::min(tail.row(), head.row());
 2418        let end_row = cmp::max(tail.row(), head.row());
 2419        let start_column = cmp::min(tail.column(), goal_column);
 2420        let end_column = cmp::max(tail.column(), goal_column);
 2421        let reversed = start_column < tail.column();
 2422
 2423        let selection_ranges = (start_row.0..=end_row.0)
 2424            .map(DisplayRow)
 2425            .filter_map(|row| {
 2426                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2427                    let start = display_map
 2428                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2429                        .to_point(display_map);
 2430                    let end = display_map
 2431                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2432                        .to_point(display_map);
 2433                    if reversed {
 2434                        Some(end..start)
 2435                    } else {
 2436                        Some(start..end)
 2437                    }
 2438                } else {
 2439                    None
 2440                }
 2441            })
 2442            .collect::<Vec<_>>();
 2443
 2444        self.change_selections(None, cx, |s| {
 2445            s.select_ranges(selection_ranges);
 2446        });
 2447        cx.notify();
 2448    }
 2449
 2450    pub fn has_pending_nonempty_selection(&self) -> bool {
 2451        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2452            Some(Selection { start, end, .. }) => start != end,
 2453            None => false,
 2454        };
 2455
 2456        pending_nonempty_selection
 2457            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2458    }
 2459
 2460    pub fn has_pending_selection(&self) -> bool {
 2461        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2462    }
 2463
 2464    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2465        if self.clear_expanded_diff_hunks(cx) {
 2466            cx.notify();
 2467            return;
 2468        }
 2469        if self.dismiss_menus_and_popups(true, cx) {
 2470            return;
 2471        }
 2472
 2473        if self.mode == EditorMode::Full
 2474            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2475        {
 2476            return;
 2477        }
 2478
 2479        cx.propagate();
 2480    }
 2481
 2482    pub fn dismiss_menus_and_popups(
 2483        &mut self,
 2484        should_report_inline_completion_event: bool,
 2485        cx: &mut ViewContext<Self>,
 2486    ) -> bool {
 2487        if self.take_rename(false, cx).is_some() {
 2488            return true;
 2489        }
 2490
 2491        if hide_hover(self, cx) {
 2492            return true;
 2493        }
 2494
 2495        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2496            return true;
 2497        }
 2498
 2499        if self.hide_context_menu(cx).is_some() {
 2500            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2501                self.update_visible_inline_completion(cx);
 2502            }
 2503            return true;
 2504        }
 2505
 2506        if self.mouse_context_menu.take().is_some() {
 2507            return true;
 2508        }
 2509
 2510        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2511            return true;
 2512        }
 2513
 2514        if self.snippet_stack.pop().is_some() {
 2515            return true;
 2516        }
 2517
 2518        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2519            self.dismiss_diagnostics(cx);
 2520            return true;
 2521        }
 2522
 2523        false
 2524    }
 2525
 2526    fn linked_editing_ranges_for(
 2527        &self,
 2528        selection: Range<text::Anchor>,
 2529        cx: &AppContext,
 2530    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2531        if self.linked_edit_ranges.is_empty() {
 2532            return None;
 2533        }
 2534        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2535            selection.end.buffer_id.and_then(|end_buffer_id| {
 2536                if selection.start.buffer_id != Some(end_buffer_id) {
 2537                    return None;
 2538                }
 2539                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2540                let snapshot = buffer.read(cx).snapshot();
 2541                self.linked_edit_ranges
 2542                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2543                    .map(|ranges| (ranges, snapshot, buffer))
 2544            })?;
 2545        use text::ToOffset as TO;
 2546        // find offset from the start of current range to current cursor position
 2547        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2548
 2549        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2550        let start_difference = start_offset - start_byte_offset;
 2551        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2552        let end_difference = end_offset - start_byte_offset;
 2553        // Current range has associated linked ranges.
 2554        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2555        for range in linked_ranges.iter() {
 2556            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2557            let end_offset = start_offset + end_difference;
 2558            let start_offset = start_offset + start_difference;
 2559            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2560                continue;
 2561            }
 2562            if self.selections.disjoint_anchor_ranges().any(|s| {
 2563                if s.start.buffer_id != selection.start.buffer_id
 2564                    || s.end.buffer_id != selection.end.buffer_id
 2565                {
 2566                    return false;
 2567                }
 2568                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2569                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2570            }) {
 2571                continue;
 2572            }
 2573            let start = buffer_snapshot.anchor_after(start_offset);
 2574            let end = buffer_snapshot.anchor_after(end_offset);
 2575            linked_edits
 2576                .entry(buffer.clone())
 2577                .or_default()
 2578                .push(start..end);
 2579        }
 2580        Some(linked_edits)
 2581    }
 2582
 2583    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2584        let text: Arc<str> = text.into();
 2585
 2586        if self.read_only(cx) {
 2587            return;
 2588        }
 2589
 2590        let selections = self.selections.all_adjusted(cx);
 2591        let mut bracket_inserted = false;
 2592        let mut edits = Vec::new();
 2593        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2594        let mut new_selections = Vec::with_capacity(selections.len());
 2595        let mut new_autoclose_regions = Vec::new();
 2596        let snapshot = self.buffer.read(cx).read(cx);
 2597
 2598        for (selection, autoclose_region) in
 2599            self.selections_with_autoclose_regions(selections, &snapshot)
 2600        {
 2601            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2602                // Determine if the inserted text matches the opening or closing
 2603                // bracket of any of this language's bracket pairs.
 2604                let mut bracket_pair = None;
 2605                let mut is_bracket_pair_start = false;
 2606                let mut is_bracket_pair_end = false;
 2607                if !text.is_empty() {
 2608                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2609                    //  and they are removing the character that triggered IME popup.
 2610                    for (pair, enabled) in scope.brackets() {
 2611                        if !pair.close && !pair.surround {
 2612                            continue;
 2613                        }
 2614
 2615                        if enabled && pair.start.ends_with(text.as_ref()) {
 2616                            let prefix_len = pair.start.len() - text.len();
 2617                            let preceding_text_matches_prefix = prefix_len == 0
 2618                                || (selection.start.column >= (prefix_len as u32)
 2619                                    && snapshot.contains_str_at(
 2620                                        Point::new(
 2621                                            selection.start.row,
 2622                                            selection.start.column - (prefix_len as u32),
 2623                                        ),
 2624                                        &pair.start[..prefix_len],
 2625                                    ));
 2626                            if preceding_text_matches_prefix {
 2627                                bracket_pair = Some(pair.clone());
 2628                                is_bracket_pair_start = true;
 2629                                break;
 2630                            }
 2631                        }
 2632                        if pair.end.as_str() == text.as_ref() {
 2633                            bracket_pair = Some(pair.clone());
 2634                            is_bracket_pair_end = true;
 2635                            break;
 2636                        }
 2637                    }
 2638                }
 2639
 2640                if let Some(bracket_pair) = bracket_pair {
 2641                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2642                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2643                    let auto_surround =
 2644                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2645                    if selection.is_empty() {
 2646                        if is_bracket_pair_start {
 2647                            // If the inserted text is a suffix of an opening bracket and the
 2648                            // selection is preceded by the rest of the opening bracket, then
 2649                            // insert the closing bracket.
 2650                            let following_text_allows_autoclose = snapshot
 2651                                .chars_at(selection.start)
 2652                                .next()
 2653                                .map_or(true, |c| scope.should_autoclose_before(c));
 2654
 2655                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2656                                && bracket_pair.start.len() == 1
 2657                            {
 2658                                let target = bracket_pair.start.chars().next().unwrap();
 2659                                let current_line_count = snapshot
 2660                                    .reversed_chars_at(selection.start)
 2661                                    .take_while(|&c| c != '\n')
 2662                                    .filter(|&c| c == target)
 2663                                    .count();
 2664                                current_line_count % 2 == 1
 2665                            } else {
 2666                                false
 2667                            };
 2668
 2669                            if autoclose
 2670                                && bracket_pair.close
 2671                                && following_text_allows_autoclose
 2672                                && !is_closing_quote
 2673                            {
 2674                                let anchor = snapshot.anchor_before(selection.end);
 2675                                new_selections.push((selection.map(|_| anchor), text.len()));
 2676                                new_autoclose_regions.push((
 2677                                    anchor,
 2678                                    text.len(),
 2679                                    selection.id,
 2680                                    bracket_pair.clone(),
 2681                                ));
 2682                                edits.push((
 2683                                    selection.range(),
 2684                                    format!("{}{}", text, bracket_pair.end).into(),
 2685                                ));
 2686                                bracket_inserted = true;
 2687                                continue;
 2688                            }
 2689                        }
 2690
 2691                        if let Some(region) = autoclose_region {
 2692                            // If the selection is followed by an auto-inserted closing bracket,
 2693                            // then don't insert that closing bracket again; just move the selection
 2694                            // past the closing bracket.
 2695                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2696                                && text.as_ref() == region.pair.end.as_str();
 2697                            if should_skip {
 2698                                let anchor = snapshot.anchor_after(selection.end);
 2699                                new_selections
 2700                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2701                                continue;
 2702                            }
 2703                        }
 2704
 2705                        let always_treat_brackets_as_autoclosed = snapshot
 2706                            .settings_at(selection.start, cx)
 2707                            .always_treat_brackets_as_autoclosed;
 2708                        if always_treat_brackets_as_autoclosed
 2709                            && is_bracket_pair_end
 2710                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2711                        {
 2712                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2713                            // and the inserted text is a closing bracket and the selection is followed
 2714                            // by the closing bracket then move the selection past the closing bracket.
 2715                            let anchor = snapshot.anchor_after(selection.end);
 2716                            new_selections.push((selection.map(|_| anchor), text.len()));
 2717                            continue;
 2718                        }
 2719                    }
 2720                    // If an opening bracket is 1 character long and is typed while
 2721                    // text is selected, then surround that text with the bracket pair.
 2722                    else if auto_surround
 2723                        && bracket_pair.surround
 2724                        && is_bracket_pair_start
 2725                        && bracket_pair.start.chars().count() == 1
 2726                    {
 2727                        edits.push((selection.start..selection.start, text.clone()));
 2728                        edits.push((
 2729                            selection.end..selection.end,
 2730                            bracket_pair.end.as_str().into(),
 2731                        ));
 2732                        bracket_inserted = true;
 2733                        new_selections.push((
 2734                            Selection {
 2735                                id: selection.id,
 2736                                start: snapshot.anchor_after(selection.start),
 2737                                end: snapshot.anchor_before(selection.end),
 2738                                reversed: selection.reversed,
 2739                                goal: selection.goal,
 2740                            },
 2741                            0,
 2742                        ));
 2743                        continue;
 2744                    }
 2745                }
 2746            }
 2747
 2748            if self.auto_replace_emoji_shortcode
 2749                && selection.is_empty()
 2750                && text.as_ref().ends_with(':')
 2751            {
 2752                if let Some(possible_emoji_short_code) =
 2753                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2754                {
 2755                    if !possible_emoji_short_code.is_empty() {
 2756                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2757                            let emoji_shortcode_start = Point::new(
 2758                                selection.start.row,
 2759                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2760                            );
 2761
 2762                            // Remove shortcode from buffer
 2763                            edits.push((
 2764                                emoji_shortcode_start..selection.start,
 2765                                "".to_string().into(),
 2766                            ));
 2767                            new_selections.push((
 2768                                Selection {
 2769                                    id: selection.id,
 2770                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2771                                    end: snapshot.anchor_before(selection.start),
 2772                                    reversed: selection.reversed,
 2773                                    goal: selection.goal,
 2774                                },
 2775                                0,
 2776                            ));
 2777
 2778                            // Insert emoji
 2779                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2780                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2781                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2782
 2783                            continue;
 2784                        }
 2785                    }
 2786                }
 2787            }
 2788
 2789            // If not handling any auto-close operation, then just replace the selected
 2790            // text with the given input and move the selection to the end of the
 2791            // newly inserted text.
 2792            let anchor = snapshot.anchor_after(selection.end);
 2793            if !self.linked_edit_ranges.is_empty() {
 2794                let start_anchor = snapshot.anchor_before(selection.start);
 2795
 2796                let is_word_char = text.chars().next().map_or(true, |char| {
 2797                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2798                    classifier.is_word(char)
 2799                });
 2800
 2801                if is_word_char {
 2802                    if let Some(ranges) = self
 2803                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2804                    {
 2805                        for (buffer, edits) in ranges {
 2806                            linked_edits
 2807                                .entry(buffer.clone())
 2808                                .or_default()
 2809                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2810                        }
 2811                    }
 2812                }
 2813            }
 2814
 2815            new_selections.push((selection.map(|_| anchor), 0));
 2816            edits.push((selection.start..selection.end, text.clone()));
 2817        }
 2818
 2819        drop(snapshot);
 2820
 2821        self.transact(cx, |this, cx| {
 2822            this.buffer.update(cx, |buffer, cx| {
 2823                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2824            });
 2825            for (buffer, edits) in linked_edits {
 2826                buffer.update(cx, |buffer, cx| {
 2827                    let snapshot = buffer.snapshot();
 2828                    let edits = edits
 2829                        .into_iter()
 2830                        .map(|(range, text)| {
 2831                            use text::ToPoint as TP;
 2832                            let end_point = TP::to_point(&range.end, &snapshot);
 2833                            let start_point = TP::to_point(&range.start, &snapshot);
 2834                            (start_point..end_point, text)
 2835                        })
 2836                        .sorted_by_key(|(range, _)| range.start)
 2837                        .collect::<Vec<_>>();
 2838                    buffer.edit(edits, None, cx);
 2839                })
 2840            }
 2841            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2842            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2843            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2844            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2845                .zip(new_selection_deltas)
 2846                .map(|(selection, delta)| Selection {
 2847                    id: selection.id,
 2848                    start: selection.start + delta,
 2849                    end: selection.end + delta,
 2850                    reversed: selection.reversed,
 2851                    goal: SelectionGoal::None,
 2852                })
 2853                .collect::<Vec<_>>();
 2854
 2855            let mut i = 0;
 2856            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2857                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2858                let start = map.buffer_snapshot.anchor_before(position);
 2859                let end = map.buffer_snapshot.anchor_after(position);
 2860                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2861                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2862                        Ordering::Less => i += 1,
 2863                        Ordering::Greater => break,
 2864                        Ordering::Equal => {
 2865                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2866                                Ordering::Less => i += 1,
 2867                                Ordering::Equal => break,
 2868                                Ordering::Greater => break,
 2869                            }
 2870                        }
 2871                    }
 2872                }
 2873                this.autoclose_regions.insert(
 2874                    i,
 2875                    AutocloseRegion {
 2876                        selection_id,
 2877                        range: start..end,
 2878                        pair,
 2879                    },
 2880                );
 2881            }
 2882
 2883            let had_active_inline_completion = this.has_active_inline_completion();
 2884            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2885                s.select(new_selections)
 2886            });
 2887
 2888            if !bracket_inserted {
 2889                if let Some(on_type_format_task) =
 2890                    this.trigger_on_type_formatting(text.to_string(), cx)
 2891                {
 2892                    on_type_format_task.detach_and_log_err(cx);
 2893                }
 2894            }
 2895
 2896            let editor_settings = EditorSettings::get_global(cx);
 2897            if bracket_inserted
 2898                && (editor_settings.auto_signature_help
 2899                    || editor_settings.show_signature_help_after_edits)
 2900            {
 2901                this.show_signature_help(&ShowSignatureHelp, cx);
 2902            }
 2903
 2904            let trigger_in_words =
 2905                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2906            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2907            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2908            this.refresh_inline_completion(true, false, cx);
 2909        });
 2910    }
 2911
 2912    fn find_possible_emoji_shortcode_at_position(
 2913        snapshot: &MultiBufferSnapshot,
 2914        position: Point,
 2915    ) -> Option<String> {
 2916        let mut chars = Vec::new();
 2917        let mut found_colon = false;
 2918        for char in snapshot.reversed_chars_at(position).take(100) {
 2919            // Found a possible emoji shortcode in the middle of the buffer
 2920            if found_colon {
 2921                if char.is_whitespace() {
 2922                    chars.reverse();
 2923                    return Some(chars.iter().collect());
 2924                }
 2925                // If the previous character is not a whitespace, we are in the middle of a word
 2926                // and we only want to complete the shortcode if the word is made up of other emojis
 2927                let mut containing_word = String::new();
 2928                for ch in snapshot
 2929                    .reversed_chars_at(position)
 2930                    .skip(chars.len() + 1)
 2931                    .take(100)
 2932                {
 2933                    if ch.is_whitespace() {
 2934                        break;
 2935                    }
 2936                    containing_word.push(ch);
 2937                }
 2938                let containing_word = containing_word.chars().rev().collect::<String>();
 2939                if util::word_consists_of_emojis(containing_word.as_str()) {
 2940                    chars.reverse();
 2941                    return Some(chars.iter().collect());
 2942                }
 2943            }
 2944
 2945            if char.is_whitespace() || !char.is_ascii() {
 2946                return None;
 2947            }
 2948            if char == ':' {
 2949                found_colon = true;
 2950            } else {
 2951                chars.push(char);
 2952            }
 2953        }
 2954        // Found a possible emoji shortcode at the beginning of the buffer
 2955        chars.reverse();
 2956        Some(chars.iter().collect())
 2957    }
 2958
 2959    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2960        self.transact(cx, |this, cx| {
 2961            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2962                let selections = this.selections.all::<usize>(cx);
 2963                let multi_buffer = this.buffer.read(cx);
 2964                let buffer = multi_buffer.snapshot(cx);
 2965                selections
 2966                    .iter()
 2967                    .map(|selection| {
 2968                        let start_point = selection.start.to_point(&buffer);
 2969                        let mut indent =
 2970                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2971                        indent.len = cmp::min(indent.len, start_point.column);
 2972                        let start = selection.start;
 2973                        let end = selection.end;
 2974                        let selection_is_empty = start == end;
 2975                        let language_scope = buffer.language_scope_at(start);
 2976                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2977                            &language_scope
 2978                        {
 2979                            let leading_whitespace_len = buffer
 2980                                .reversed_chars_at(start)
 2981                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2982                                .map(|c| c.len_utf8())
 2983                                .sum::<usize>();
 2984
 2985                            let trailing_whitespace_len = buffer
 2986                                .chars_at(end)
 2987                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2988                                .map(|c| c.len_utf8())
 2989                                .sum::<usize>();
 2990
 2991                            let insert_extra_newline =
 2992                                language.brackets().any(|(pair, enabled)| {
 2993                                    let pair_start = pair.start.trim_end();
 2994                                    let pair_end = pair.end.trim_start();
 2995
 2996                                    enabled
 2997                                        && pair.newline
 2998                                        && buffer.contains_str_at(
 2999                                            end + trailing_whitespace_len,
 3000                                            pair_end,
 3001                                        )
 3002                                        && buffer.contains_str_at(
 3003                                            (start - leading_whitespace_len)
 3004                                                .saturating_sub(pair_start.len()),
 3005                                            pair_start,
 3006                                        )
 3007                                });
 3008
 3009                            // Comment extension on newline is allowed only for cursor selections
 3010                            let comment_delimiter = maybe!({
 3011                                if !selection_is_empty {
 3012                                    return None;
 3013                                }
 3014
 3015                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3016                                    return None;
 3017                                }
 3018
 3019                                let delimiters = language.line_comment_prefixes();
 3020                                let max_len_of_delimiter =
 3021                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3022                                let (snapshot, range) =
 3023                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3024
 3025                                let mut index_of_first_non_whitespace = 0;
 3026                                let comment_candidate = snapshot
 3027                                    .chars_for_range(range)
 3028                                    .skip_while(|c| {
 3029                                        let should_skip = c.is_whitespace();
 3030                                        if should_skip {
 3031                                            index_of_first_non_whitespace += 1;
 3032                                        }
 3033                                        should_skip
 3034                                    })
 3035                                    .take(max_len_of_delimiter)
 3036                                    .collect::<String>();
 3037                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3038                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3039                                })?;
 3040                                let cursor_is_placed_after_comment_marker =
 3041                                    index_of_first_non_whitespace + comment_prefix.len()
 3042                                        <= start_point.column as usize;
 3043                                if cursor_is_placed_after_comment_marker {
 3044                                    Some(comment_prefix.clone())
 3045                                } else {
 3046                                    None
 3047                                }
 3048                            });
 3049                            (comment_delimiter, insert_extra_newline)
 3050                        } else {
 3051                            (None, false)
 3052                        };
 3053
 3054                        let capacity_for_delimiter = comment_delimiter
 3055                            .as_deref()
 3056                            .map(str::len)
 3057                            .unwrap_or_default();
 3058                        let mut new_text =
 3059                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3060                        new_text.push('\n');
 3061                        new_text.extend(indent.chars());
 3062                        if let Some(delimiter) = &comment_delimiter {
 3063                            new_text.push_str(delimiter);
 3064                        }
 3065                        if insert_extra_newline {
 3066                            new_text = new_text.repeat(2);
 3067                        }
 3068
 3069                        let anchor = buffer.anchor_after(end);
 3070                        let new_selection = selection.map(|_| anchor);
 3071                        (
 3072                            (start..end, new_text),
 3073                            (insert_extra_newline, new_selection),
 3074                        )
 3075                    })
 3076                    .unzip()
 3077            };
 3078
 3079            this.edit_with_autoindent(edits, cx);
 3080            let buffer = this.buffer.read(cx).snapshot(cx);
 3081            let new_selections = selection_fixup_info
 3082                .into_iter()
 3083                .map(|(extra_newline_inserted, new_selection)| {
 3084                    let mut cursor = new_selection.end.to_point(&buffer);
 3085                    if extra_newline_inserted {
 3086                        cursor.row -= 1;
 3087                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3088                    }
 3089                    new_selection.map(|_| cursor)
 3090                })
 3091                .collect();
 3092
 3093            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3094            this.refresh_inline_completion(true, false, cx);
 3095        });
 3096    }
 3097
 3098    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3099        let buffer = self.buffer.read(cx);
 3100        let snapshot = buffer.snapshot(cx);
 3101
 3102        let mut edits = Vec::new();
 3103        let mut rows = Vec::new();
 3104
 3105        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3106            let cursor = selection.head();
 3107            let row = cursor.row;
 3108
 3109            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3110
 3111            let newline = "\n".to_string();
 3112            edits.push((start_of_line..start_of_line, newline));
 3113
 3114            rows.push(row + rows_inserted as u32);
 3115        }
 3116
 3117        self.transact(cx, |editor, cx| {
 3118            editor.edit(edits, cx);
 3119
 3120            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3121                let mut index = 0;
 3122                s.move_cursors_with(|map, _, _| {
 3123                    let row = rows[index];
 3124                    index += 1;
 3125
 3126                    let point = Point::new(row, 0);
 3127                    let boundary = map.next_line_boundary(point).1;
 3128                    let clipped = map.clip_point(boundary, Bias::Left);
 3129
 3130                    (clipped, SelectionGoal::None)
 3131                });
 3132            });
 3133
 3134            let mut indent_edits = Vec::new();
 3135            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3136            for row in rows {
 3137                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3138                for (row, indent) in indents {
 3139                    if indent.len == 0 {
 3140                        continue;
 3141                    }
 3142
 3143                    let text = match indent.kind {
 3144                        IndentKind::Space => " ".repeat(indent.len as usize),
 3145                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3146                    };
 3147                    let point = Point::new(row.0, 0);
 3148                    indent_edits.push((point..point, text));
 3149                }
 3150            }
 3151            editor.edit(indent_edits, cx);
 3152        });
 3153    }
 3154
 3155    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3156        let buffer = self.buffer.read(cx);
 3157        let snapshot = buffer.snapshot(cx);
 3158
 3159        let mut edits = Vec::new();
 3160        let mut rows = Vec::new();
 3161        let mut rows_inserted = 0;
 3162
 3163        for selection in self.selections.all_adjusted(cx) {
 3164            let cursor = selection.head();
 3165            let row = cursor.row;
 3166
 3167            let point = Point::new(row + 1, 0);
 3168            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3169
 3170            let newline = "\n".to_string();
 3171            edits.push((start_of_line..start_of_line, newline));
 3172
 3173            rows_inserted += 1;
 3174            rows.push(row + rows_inserted);
 3175        }
 3176
 3177        self.transact(cx, |editor, cx| {
 3178            editor.edit(edits, cx);
 3179
 3180            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3181                let mut index = 0;
 3182                s.move_cursors_with(|map, _, _| {
 3183                    let row = rows[index];
 3184                    index += 1;
 3185
 3186                    let point = Point::new(row, 0);
 3187                    let boundary = map.next_line_boundary(point).1;
 3188                    let clipped = map.clip_point(boundary, Bias::Left);
 3189
 3190                    (clipped, SelectionGoal::None)
 3191                });
 3192            });
 3193
 3194            let mut indent_edits = Vec::new();
 3195            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3196            for row in rows {
 3197                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3198                for (row, indent) in indents {
 3199                    if indent.len == 0 {
 3200                        continue;
 3201                    }
 3202
 3203                    let text = match indent.kind {
 3204                        IndentKind::Space => " ".repeat(indent.len as usize),
 3205                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3206                    };
 3207                    let point = Point::new(row.0, 0);
 3208                    indent_edits.push((point..point, text));
 3209                }
 3210            }
 3211            editor.edit(indent_edits, cx);
 3212        });
 3213    }
 3214
 3215    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3216        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3217            original_indent_columns: Vec::new(),
 3218        });
 3219        self.insert_with_autoindent_mode(text, autoindent, cx);
 3220    }
 3221
 3222    fn insert_with_autoindent_mode(
 3223        &mut self,
 3224        text: &str,
 3225        autoindent_mode: Option<AutoindentMode>,
 3226        cx: &mut ViewContext<Self>,
 3227    ) {
 3228        if self.read_only(cx) {
 3229            return;
 3230        }
 3231
 3232        let text: Arc<str> = text.into();
 3233        self.transact(cx, |this, cx| {
 3234            let old_selections = this.selections.all_adjusted(cx);
 3235            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3236                let anchors = {
 3237                    let snapshot = buffer.read(cx);
 3238                    old_selections
 3239                        .iter()
 3240                        .map(|s| {
 3241                            let anchor = snapshot.anchor_after(s.head());
 3242                            s.map(|_| anchor)
 3243                        })
 3244                        .collect::<Vec<_>>()
 3245                };
 3246                buffer.edit(
 3247                    old_selections
 3248                        .iter()
 3249                        .map(|s| (s.start..s.end, text.clone())),
 3250                    autoindent_mode,
 3251                    cx,
 3252                );
 3253                anchors
 3254            });
 3255
 3256            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3257                s.select_anchors(selection_anchors);
 3258            })
 3259        });
 3260    }
 3261
 3262    fn trigger_completion_on_input(
 3263        &mut self,
 3264        text: &str,
 3265        trigger_in_words: bool,
 3266        cx: &mut ViewContext<Self>,
 3267    ) {
 3268        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3269            self.show_completions(
 3270                &ShowCompletions {
 3271                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3272                },
 3273                cx,
 3274            );
 3275        } else {
 3276            self.hide_context_menu(cx);
 3277        }
 3278    }
 3279
 3280    fn is_completion_trigger(
 3281        &self,
 3282        text: &str,
 3283        trigger_in_words: bool,
 3284        cx: &mut ViewContext<Self>,
 3285    ) -> bool {
 3286        let position = self.selections.newest_anchor().head();
 3287        let multibuffer = self.buffer.read(cx);
 3288        let Some(buffer) = position
 3289            .buffer_id
 3290            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3291        else {
 3292            return false;
 3293        };
 3294
 3295        if let Some(completion_provider) = &self.completion_provider {
 3296            completion_provider.is_completion_trigger(
 3297                &buffer,
 3298                position.text_anchor,
 3299                text,
 3300                trigger_in_words,
 3301                cx,
 3302            )
 3303        } else {
 3304            false
 3305        }
 3306    }
 3307
 3308    /// If any empty selections is touching the start of its innermost containing autoclose
 3309    /// region, expand it to select the brackets.
 3310    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3311        let selections = self.selections.all::<usize>(cx);
 3312        let buffer = self.buffer.read(cx).read(cx);
 3313        let new_selections = self
 3314            .selections_with_autoclose_regions(selections, &buffer)
 3315            .map(|(mut selection, region)| {
 3316                if !selection.is_empty() {
 3317                    return selection;
 3318                }
 3319
 3320                if let Some(region) = region {
 3321                    let mut range = region.range.to_offset(&buffer);
 3322                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3323                        range.start -= region.pair.start.len();
 3324                        if buffer.contains_str_at(range.start, &region.pair.start)
 3325                            && buffer.contains_str_at(range.end, &region.pair.end)
 3326                        {
 3327                            range.end += region.pair.end.len();
 3328                            selection.start = range.start;
 3329                            selection.end = range.end;
 3330
 3331                            return selection;
 3332                        }
 3333                    }
 3334                }
 3335
 3336                let always_treat_brackets_as_autoclosed = buffer
 3337                    .settings_at(selection.start, cx)
 3338                    .always_treat_brackets_as_autoclosed;
 3339
 3340                if !always_treat_brackets_as_autoclosed {
 3341                    return selection;
 3342                }
 3343
 3344                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3345                    for (pair, enabled) in scope.brackets() {
 3346                        if !enabled || !pair.close {
 3347                            continue;
 3348                        }
 3349
 3350                        if buffer.contains_str_at(selection.start, &pair.end) {
 3351                            let pair_start_len = pair.start.len();
 3352                            if buffer.contains_str_at(
 3353                                selection.start.saturating_sub(pair_start_len),
 3354                                &pair.start,
 3355                            ) {
 3356                                selection.start -= pair_start_len;
 3357                                selection.end += pair.end.len();
 3358
 3359                                return selection;
 3360                            }
 3361                        }
 3362                    }
 3363                }
 3364
 3365                selection
 3366            })
 3367            .collect();
 3368
 3369        drop(buffer);
 3370        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3371    }
 3372
 3373    /// Iterate the given selections, and for each one, find the smallest surrounding
 3374    /// autoclose region. This uses the ordering of the selections and the autoclose
 3375    /// regions to avoid repeated comparisons.
 3376    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3377        &'a self,
 3378        selections: impl IntoIterator<Item = Selection<D>>,
 3379        buffer: &'a MultiBufferSnapshot,
 3380    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3381        let mut i = 0;
 3382        let mut regions = self.autoclose_regions.as_slice();
 3383        selections.into_iter().map(move |selection| {
 3384            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3385
 3386            let mut enclosing = None;
 3387            while let Some(pair_state) = regions.get(i) {
 3388                if pair_state.range.end.to_offset(buffer) < range.start {
 3389                    regions = &regions[i + 1..];
 3390                    i = 0;
 3391                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3392                    break;
 3393                } else {
 3394                    if pair_state.selection_id == selection.id {
 3395                        enclosing = Some(pair_state);
 3396                    }
 3397                    i += 1;
 3398                }
 3399            }
 3400
 3401            (selection, enclosing)
 3402        })
 3403    }
 3404
 3405    /// Remove any autoclose regions that no longer contain their selection.
 3406    fn invalidate_autoclose_regions(
 3407        &mut self,
 3408        mut selections: &[Selection<Anchor>],
 3409        buffer: &MultiBufferSnapshot,
 3410    ) {
 3411        self.autoclose_regions.retain(|state| {
 3412            let mut i = 0;
 3413            while let Some(selection) = selections.get(i) {
 3414                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3415                    selections = &selections[1..];
 3416                    continue;
 3417                }
 3418                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3419                    break;
 3420                }
 3421                if selection.id == state.selection_id {
 3422                    return true;
 3423                } else {
 3424                    i += 1;
 3425                }
 3426            }
 3427            false
 3428        });
 3429    }
 3430
 3431    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3432        let offset = position.to_offset(buffer);
 3433        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3434        if offset > word_range.start && kind == Some(CharKind::Word) {
 3435            Some(
 3436                buffer
 3437                    .text_for_range(word_range.start..offset)
 3438                    .collect::<String>(),
 3439            )
 3440        } else {
 3441            None
 3442        }
 3443    }
 3444
 3445    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3446        self.refresh_inlay_hints(
 3447            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3448            cx,
 3449        );
 3450    }
 3451
 3452    pub fn inlay_hints_enabled(&self) -> bool {
 3453        self.inlay_hint_cache.enabled
 3454    }
 3455
 3456    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3457        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3458            return;
 3459        }
 3460
 3461        let reason_description = reason.description();
 3462        let ignore_debounce = matches!(
 3463            reason,
 3464            InlayHintRefreshReason::SettingsChange(_)
 3465                | InlayHintRefreshReason::Toggle(_)
 3466                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3467        );
 3468        let (invalidate_cache, required_languages) = match reason {
 3469            InlayHintRefreshReason::Toggle(enabled) => {
 3470                self.inlay_hint_cache.enabled = enabled;
 3471                if enabled {
 3472                    (InvalidationStrategy::RefreshRequested, None)
 3473                } else {
 3474                    self.inlay_hint_cache.clear();
 3475                    self.splice_inlays(
 3476                        self.visible_inlay_hints(cx)
 3477                            .iter()
 3478                            .map(|inlay| inlay.id)
 3479                            .collect(),
 3480                        Vec::new(),
 3481                        cx,
 3482                    );
 3483                    return;
 3484                }
 3485            }
 3486            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3487                match self.inlay_hint_cache.update_settings(
 3488                    &self.buffer,
 3489                    new_settings,
 3490                    self.visible_inlay_hints(cx),
 3491                    cx,
 3492                ) {
 3493                    ControlFlow::Break(Some(InlaySplice {
 3494                        to_remove,
 3495                        to_insert,
 3496                    })) => {
 3497                        self.splice_inlays(to_remove, to_insert, cx);
 3498                        return;
 3499                    }
 3500                    ControlFlow::Break(None) => return,
 3501                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3502                }
 3503            }
 3504            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3505                if let Some(InlaySplice {
 3506                    to_remove,
 3507                    to_insert,
 3508                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3509                {
 3510                    self.splice_inlays(to_remove, to_insert, cx);
 3511                }
 3512                return;
 3513            }
 3514            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3515            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3516                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3517            }
 3518            InlayHintRefreshReason::RefreshRequested => {
 3519                (InvalidationStrategy::RefreshRequested, None)
 3520            }
 3521        };
 3522
 3523        if let Some(InlaySplice {
 3524            to_remove,
 3525            to_insert,
 3526        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3527            reason_description,
 3528            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3529            invalidate_cache,
 3530            ignore_debounce,
 3531            cx,
 3532        ) {
 3533            self.splice_inlays(to_remove, to_insert, cx);
 3534        }
 3535    }
 3536
 3537    fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
 3538        self.display_map
 3539            .read(cx)
 3540            .current_inlays()
 3541            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3542            .cloned()
 3543            .collect()
 3544    }
 3545
 3546    pub fn excerpts_for_inlay_hints_query(
 3547        &self,
 3548        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3549        cx: &mut ViewContext<Editor>,
 3550    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3551        let Some(project) = self.project.as_ref() else {
 3552            return HashMap::default();
 3553        };
 3554        let project = project.read(cx);
 3555        let multi_buffer = self.buffer().read(cx);
 3556        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3557        let multi_buffer_visible_start = self
 3558            .scroll_manager
 3559            .anchor()
 3560            .anchor
 3561            .to_point(&multi_buffer_snapshot);
 3562        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3563            multi_buffer_visible_start
 3564                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3565            Bias::Left,
 3566        );
 3567        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3568        multi_buffer_snapshot
 3569            .range_to_buffer_ranges(multi_buffer_visible_range)
 3570            .into_iter()
 3571            .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
 3572            .filter_map(|(excerpt, excerpt_visible_range)| {
 3573                let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
 3574                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3575                let worktree_entry = buffer_worktree
 3576                    .read(cx)
 3577                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3578                if worktree_entry.is_ignored {
 3579                    return None;
 3580                }
 3581
 3582                let language = excerpt.buffer().language()?;
 3583                if let Some(restrict_to_languages) = restrict_to_languages {
 3584                    if !restrict_to_languages.contains(language) {
 3585                        return None;
 3586                    }
 3587                }
 3588                Some((
 3589                    excerpt.id(),
 3590                    (
 3591                        multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
 3592                        excerpt.buffer().version().clone(),
 3593                        excerpt_visible_range,
 3594                    ),
 3595                ))
 3596            })
 3597            .collect()
 3598    }
 3599
 3600    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3601        TextLayoutDetails {
 3602            text_system: cx.text_system().clone(),
 3603            editor_style: self.style.clone().unwrap(),
 3604            rem_size: cx.rem_size(),
 3605            scroll_anchor: self.scroll_manager.anchor(),
 3606            visible_rows: self.visible_line_count(),
 3607            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3608        }
 3609    }
 3610
 3611    pub fn splice_inlays(
 3612        &self,
 3613        to_remove: Vec<InlayId>,
 3614        to_insert: Vec<Inlay>,
 3615        cx: &mut ViewContext<Self>,
 3616    ) {
 3617        self.display_map.update(cx, |display_map, cx| {
 3618            display_map.splice_inlays(to_remove, to_insert, cx)
 3619        });
 3620        cx.notify();
 3621    }
 3622
 3623    fn trigger_on_type_formatting(
 3624        &self,
 3625        input: String,
 3626        cx: &mut ViewContext<Self>,
 3627    ) -> Option<Task<Result<()>>> {
 3628        if input.len() != 1 {
 3629            return None;
 3630        }
 3631
 3632        let project = self.project.as_ref()?;
 3633        let position = self.selections.newest_anchor().head();
 3634        let (buffer, buffer_position) = self
 3635            .buffer
 3636            .read(cx)
 3637            .text_anchor_for_position(position, cx)?;
 3638
 3639        let settings = language_settings::language_settings(
 3640            buffer
 3641                .read(cx)
 3642                .language_at(buffer_position)
 3643                .map(|l| l.name()),
 3644            buffer.read(cx).file(),
 3645            cx,
 3646        );
 3647        if !settings.use_on_type_format {
 3648            return None;
 3649        }
 3650
 3651        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3652        // hence we do LSP request & edit on host side only — add formats to host's history.
 3653        let push_to_lsp_host_history = true;
 3654        // If this is not the host, append its history with new edits.
 3655        let push_to_client_history = project.read(cx).is_via_collab();
 3656
 3657        let on_type_formatting = project.update(cx, |project, cx| {
 3658            project.on_type_format(
 3659                buffer.clone(),
 3660                buffer_position,
 3661                input,
 3662                push_to_lsp_host_history,
 3663                cx,
 3664            )
 3665        });
 3666        Some(cx.spawn(|editor, mut cx| async move {
 3667            if let Some(transaction) = on_type_formatting.await? {
 3668                if push_to_client_history {
 3669                    buffer
 3670                        .update(&mut cx, |buffer, _| {
 3671                            buffer.push_transaction(transaction, Instant::now());
 3672                        })
 3673                        .ok();
 3674                }
 3675                editor.update(&mut cx, |editor, cx| {
 3676                    editor.refresh_document_highlights(cx);
 3677                })?;
 3678            }
 3679            Ok(())
 3680        }))
 3681    }
 3682
 3683    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3684        if self.pending_rename.is_some() {
 3685            return;
 3686        }
 3687
 3688        let Some(provider) = self.completion_provider.as_ref() else {
 3689            return;
 3690        };
 3691
 3692        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3693            return;
 3694        }
 3695
 3696        let position = self.selections.newest_anchor().head();
 3697        let (buffer, buffer_position) =
 3698            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3699                output
 3700            } else {
 3701                return;
 3702            };
 3703        let show_completion_documentation = buffer
 3704            .read(cx)
 3705            .snapshot()
 3706            .settings_at(buffer_position, cx)
 3707            .show_completion_documentation;
 3708
 3709        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3710
 3711        let trigger_kind = match &options.trigger {
 3712            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3713                CompletionTriggerKind::TRIGGER_CHARACTER
 3714            }
 3715            _ => CompletionTriggerKind::INVOKED,
 3716        };
 3717        let completion_context = CompletionContext {
 3718            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3719                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3720                    Some(String::from(trigger))
 3721                } else {
 3722                    None
 3723                }
 3724            }),
 3725            trigger_kind,
 3726        };
 3727        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3728        let sort_completions = provider.sort_completions();
 3729
 3730        let id = post_inc(&mut self.next_completion_id);
 3731        let task = cx.spawn(|editor, mut cx| {
 3732            async move {
 3733                editor.update(&mut cx, |this, _| {
 3734                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3735                })?;
 3736                let completions = completions.await.log_err();
 3737                let menu = if let Some(completions) = completions {
 3738                    let mut menu = CompletionsMenu::new(
 3739                        id,
 3740                        sort_completions,
 3741                        show_completion_documentation,
 3742                        position,
 3743                        buffer.clone(),
 3744                        completions.into(),
 3745                    );
 3746
 3747                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3748                        .await;
 3749
 3750                    menu.visible().then_some(menu)
 3751                } else {
 3752                    None
 3753                };
 3754
 3755                editor.update(&mut cx, |editor, cx| {
 3756                    match editor.context_menu.borrow().as_ref() {
 3757                        None => {}
 3758                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3759                            if prev_menu.id > id {
 3760                                return;
 3761                            }
 3762                        }
 3763                        _ => return,
 3764                    }
 3765
 3766                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3767                        let mut menu = menu.unwrap();
 3768                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3769
 3770                        if editor.show_inline_completions_in_menu(cx) {
 3771                            if let Some(hint) = editor.inline_completion_menu_hint(cx) {
 3772                                menu.show_inline_completion_hint(hint);
 3773                            }
 3774                        } else {
 3775                            editor.discard_inline_completion(false, cx);
 3776                        }
 3777
 3778                        *editor.context_menu.borrow_mut() =
 3779                            Some(CodeContextMenu::Completions(menu));
 3780
 3781                        cx.notify();
 3782                    } else if editor.completion_tasks.len() <= 1 {
 3783                        // If there are no more completion tasks and the last menu was
 3784                        // empty, we should hide it.
 3785                        let was_hidden = editor.hide_context_menu(cx).is_none();
 3786                        // If it was already hidden and we don't show inline
 3787                        // completions in the menu, we should also show the
 3788                        // inline-completion when available.
 3789                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3790                            editor.update_visible_inline_completion(cx);
 3791                        }
 3792                    }
 3793                })?;
 3794
 3795                Ok::<_, anyhow::Error>(())
 3796            }
 3797            .log_err()
 3798        });
 3799
 3800        self.completion_tasks.push((id, task));
 3801    }
 3802
 3803    pub fn confirm_completion(
 3804        &mut self,
 3805        action: &ConfirmCompletion,
 3806        cx: &mut ViewContext<Self>,
 3807    ) -> Option<Task<Result<()>>> {
 3808        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3809    }
 3810
 3811    pub fn compose_completion(
 3812        &mut self,
 3813        action: &ComposeCompletion,
 3814        cx: &mut ViewContext<Self>,
 3815    ) -> Option<Task<Result<()>>> {
 3816        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3817    }
 3818
 3819    fn do_completion(
 3820        &mut self,
 3821        item_ix: Option<usize>,
 3822        intent: CompletionIntent,
 3823        cx: &mut ViewContext<Editor>,
 3824    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3825        use language::ToOffset as _;
 3826
 3827        let completions_menu =
 3828            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3829                menu
 3830            } else {
 3831                return None;
 3832            };
 3833
 3834        let entries = completions_menu.entries.borrow();
 3835        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3836        let mat = match mat {
 3837            CompletionEntry::InlineCompletionHint { .. } => {
 3838                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3839                cx.stop_propagation();
 3840                return Some(Task::ready(Ok(())));
 3841            }
 3842            CompletionEntry::Match(mat) => {
 3843                if self.show_inline_completions_in_menu(cx) {
 3844                    self.discard_inline_completion(true, cx);
 3845                }
 3846                mat
 3847            }
 3848        };
 3849        let candidate_id = mat.candidate_id;
 3850        drop(entries);
 3851
 3852        let buffer_handle = completions_menu.buffer;
 3853        let completion = completions_menu
 3854            .completions
 3855            .borrow()
 3856            .get(candidate_id)?
 3857            .clone();
 3858        cx.stop_propagation();
 3859
 3860        let snippet;
 3861        let text;
 3862
 3863        if completion.is_snippet() {
 3864            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3865            text = snippet.as_ref().unwrap().text.clone();
 3866        } else {
 3867            snippet = None;
 3868            text = completion.new_text.clone();
 3869        };
 3870        let selections = self.selections.all::<usize>(cx);
 3871        let buffer = buffer_handle.read(cx);
 3872        let old_range = completion.old_range.to_offset(buffer);
 3873        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3874
 3875        let newest_selection = self.selections.newest_anchor();
 3876        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3877            return None;
 3878        }
 3879
 3880        let lookbehind = newest_selection
 3881            .start
 3882            .text_anchor
 3883            .to_offset(buffer)
 3884            .saturating_sub(old_range.start);
 3885        let lookahead = old_range
 3886            .end
 3887            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3888        let mut common_prefix_len = old_text
 3889            .bytes()
 3890            .zip(text.bytes())
 3891            .take_while(|(a, b)| a == b)
 3892            .count();
 3893
 3894        let snapshot = self.buffer.read(cx).snapshot(cx);
 3895        let mut range_to_replace: Option<Range<isize>> = None;
 3896        let mut ranges = Vec::new();
 3897        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3898        for selection in &selections {
 3899            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3900                let start = selection.start.saturating_sub(lookbehind);
 3901                let end = selection.end + lookahead;
 3902                if selection.id == newest_selection.id {
 3903                    range_to_replace = Some(
 3904                        ((start + common_prefix_len) as isize - selection.start as isize)
 3905                            ..(end as isize - selection.start as isize),
 3906                    );
 3907                }
 3908                ranges.push(start + common_prefix_len..end);
 3909            } else {
 3910                common_prefix_len = 0;
 3911                ranges.clear();
 3912                ranges.extend(selections.iter().map(|s| {
 3913                    if s.id == newest_selection.id {
 3914                        range_to_replace = Some(
 3915                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3916                                - selection.start as isize
 3917                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3918                                    - selection.start as isize,
 3919                        );
 3920                        old_range.clone()
 3921                    } else {
 3922                        s.start..s.end
 3923                    }
 3924                }));
 3925                break;
 3926            }
 3927            if !self.linked_edit_ranges.is_empty() {
 3928                let start_anchor = snapshot.anchor_before(selection.head());
 3929                let end_anchor = snapshot.anchor_after(selection.tail());
 3930                if let Some(ranges) = self
 3931                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3932                {
 3933                    for (buffer, edits) in ranges {
 3934                        linked_edits.entry(buffer.clone()).or_default().extend(
 3935                            edits
 3936                                .into_iter()
 3937                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3938                        );
 3939                    }
 3940                }
 3941            }
 3942        }
 3943        let text = &text[common_prefix_len..];
 3944
 3945        cx.emit(EditorEvent::InputHandled {
 3946            utf16_range_to_replace: range_to_replace,
 3947            text: text.into(),
 3948        });
 3949
 3950        self.transact(cx, |this, cx| {
 3951            if let Some(mut snippet) = snippet {
 3952                snippet.text = text.to_string();
 3953                for tabstop in snippet
 3954                    .tabstops
 3955                    .iter_mut()
 3956                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3957                {
 3958                    tabstop.start -= common_prefix_len as isize;
 3959                    tabstop.end -= common_prefix_len as isize;
 3960                }
 3961
 3962                this.insert_snippet(&ranges, snippet, cx).log_err();
 3963            } else {
 3964                this.buffer.update(cx, |buffer, cx| {
 3965                    buffer.edit(
 3966                        ranges.iter().map(|range| (range.clone(), text)),
 3967                        this.autoindent_mode.clone(),
 3968                        cx,
 3969                    );
 3970                });
 3971            }
 3972            for (buffer, edits) in linked_edits {
 3973                buffer.update(cx, |buffer, cx| {
 3974                    let snapshot = buffer.snapshot();
 3975                    let edits = edits
 3976                        .into_iter()
 3977                        .map(|(range, text)| {
 3978                            use text::ToPoint as TP;
 3979                            let end_point = TP::to_point(&range.end, &snapshot);
 3980                            let start_point = TP::to_point(&range.start, &snapshot);
 3981                            (start_point..end_point, text)
 3982                        })
 3983                        .sorted_by_key(|(range, _)| range.start)
 3984                        .collect::<Vec<_>>();
 3985                    buffer.edit(edits, None, cx);
 3986                })
 3987            }
 3988
 3989            this.refresh_inline_completion(true, false, cx);
 3990        });
 3991
 3992        let show_new_completions_on_confirm = completion
 3993            .confirm
 3994            .as_ref()
 3995            .map_or(false, |confirm| confirm(intent, cx));
 3996        if show_new_completions_on_confirm {
 3997            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3998        }
 3999
 4000        let provider = self.completion_provider.as_ref()?;
 4001        drop(completion);
 4002        let apply_edits = provider.apply_additional_edits_for_completion(
 4003            buffer_handle,
 4004            completions_menu.completions.clone(),
 4005            candidate_id,
 4006            true,
 4007            cx,
 4008        );
 4009
 4010        let editor_settings = EditorSettings::get_global(cx);
 4011        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4012            // After the code completion is finished, users often want to know what signatures are needed.
 4013            // so we should automatically call signature_help
 4014            self.show_signature_help(&ShowSignatureHelp, cx);
 4015        }
 4016
 4017        Some(cx.foreground_executor().spawn(async move {
 4018            apply_edits.await?;
 4019            Ok(())
 4020        }))
 4021    }
 4022
 4023    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4024        let mut context_menu = self.context_menu.borrow_mut();
 4025        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4026            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4027                // Toggle if we're selecting the same one
 4028                *context_menu = None;
 4029                cx.notify();
 4030                return;
 4031            } else {
 4032                // Otherwise, clear it and start a new one
 4033                *context_menu = None;
 4034                cx.notify();
 4035            }
 4036        }
 4037        drop(context_menu);
 4038        let snapshot = self.snapshot(cx);
 4039        let deployed_from_indicator = action.deployed_from_indicator;
 4040        let mut task = self.code_actions_task.take();
 4041        let action = action.clone();
 4042        cx.spawn(|editor, mut cx| async move {
 4043            while let Some(prev_task) = task {
 4044                prev_task.await.log_err();
 4045                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4046            }
 4047
 4048            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4049                if editor.focus_handle.is_focused(cx) {
 4050                    let multibuffer_point = action
 4051                        .deployed_from_indicator
 4052                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4053                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4054                    let (buffer, buffer_row) = snapshot
 4055                        .buffer_snapshot
 4056                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4057                        .and_then(|(buffer_snapshot, range)| {
 4058                            editor
 4059                                .buffer
 4060                                .read(cx)
 4061                                .buffer(buffer_snapshot.remote_id())
 4062                                .map(|buffer| (buffer, range.start.row))
 4063                        })?;
 4064                    let (_, code_actions) = editor
 4065                        .available_code_actions
 4066                        .clone()
 4067                        .and_then(|(location, code_actions)| {
 4068                            let snapshot = location.buffer.read(cx).snapshot();
 4069                            let point_range = location.range.to_point(&snapshot);
 4070                            let point_range = point_range.start.row..=point_range.end.row;
 4071                            if point_range.contains(&buffer_row) {
 4072                                Some((location, code_actions))
 4073                            } else {
 4074                                None
 4075                            }
 4076                        })
 4077                        .unzip();
 4078                    let buffer_id = buffer.read(cx).remote_id();
 4079                    let tasks = editor
 4080                        .tasks
 4081                        .get(&(buffer_id, buffer_row))
 4082                        .map(|t| Arc::new(t.to_owned()));
 4083                    if tasks.is_none() && code_actions.is_none() {
 4084                        return None;
 4085                    }
 4086
 4087                    editor.completion_tasks.clear();
 4088                    editor.discard_inline_completion(false, cx);
 4089                    let task_context =
 4090                        tasks
 4091                            .as_ref()
 4092                            .zip(editor.project.clone())
 4093                            .map(|(tasks, project)| {
 4094                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4095                            });
 4096
 4097                    Some(cx.spawn(|editor, mut cx| async move {
 4098                        let task_context = match task_context {
 4099                            Some(task_context) => task_context.await,
 4100                            None => None,
 4101                        };
 4102                        let resolved_tasks =
 4103                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4104                                Rc::new(ResolvedTasks {
 4105                                    templates: tasks.resolve(&task_context).collect(),
 4106                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4107                                        multibuffer_point.row,
 4108                                        tasks.column,
 4109                                    )),
 4110                                })
 4111                            });
 4112                        let spawn_straight_away = resolved_tasks
 4113                            .as_ref()
 4114                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4115                            && code_actions
 4116                                .as_ref()
 4117                                .map_or(true, |actions| actions.is_empty());
 4118                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4119                            *editor.context_menu.borrow_mut() =
 4120                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4121                                    buffer,
 4122                                    actions: CodeActionContents {
 4123                                        tasks: resolved_tasks,
 4124                                        actions: code_actions,
 4125                                    },
 4126                                    selected_item: Default::default(),
 4127                                    scroll_handle: UniformListScrollHandle::default(),
 4128                                    deployed_from_indicator,
 4129                                }));
 4130                            if spawn_straight_away {
 4131                                if let Some(task) = editor.confirm_code_action(
 4132                                    &ConfirmCodeAction { item_ix: Some(0) },
 4133                                    cx,
 4134                                ) {
 4135                                    cx.notify();
 4136                                    return task;
 4137                                }
 4138                            }
 4139                            cx.notify();
 4140                            Task::ready(Ok(()))
 4141                        }) {
 4142                            task.await
 4143                        } else {
 4144                            Ok(())
 4145                        }
 4146                    }))
 4147                } else {
 4148                    Some(Task::ready(Ok(())))
 4149                }
 4150            })?;
 4151            if let Some(task) = spawned_test_task {
 4152                task.await?;
 4153            }
 4154
 4155            Ok::<_, anyhow::Error>(())
 4156        })
 4157        .detach_and_log_err(cx);
 4158    }
 4159
 4160    pub fn confirm_code_action(
 4161        &mut self,
 4162        action: &ConfirmCodeAction,
 4163        cx: &mut ViewContext<Self>,
 4164    ) -> Option<Task<Result<()>>> {
 4165        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4166            menu
 4167        } else {
 4168            return None;
 4169        };
 4170        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4171        let action = actions_menu.actions.get(action_ix)?;
 4172        let title = action.label();
 4173        let buffer = actions_menu.buffer;
 4174        let workspace = self.workspace()?;
 4175
 4176        match action {
 4177            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4178                workspace.update(cx, |workspace, cx| {
 4179                    workspace::tasks::schedule_resolved_task(
 4180                        workspace,
 4181                        task_source_kind,
 4182                        resolved_task,
 4183                        false,
 4184                        cx,
 4185                    );
 4186
 4187                    Some(Task::ready(Ok(())))
 4188                })
 4189            }
 4190            CodeActionsItem::CodeAction {
 4191                excerpt_id,
 4192                action,
 4193                provider,
 4194            } => {
 4195                let apply_code_action =
 4196                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4197                let workspace = workspace.downgrade();
 4198                Some(cx.spawn(|editor, cx| async move {
 4199                    let project_transaction = apply_code_action.await?;
 4200                    Self::open_project_transaction(
 4201                        &editor,
 4202                        workspace,
 4203                        project_transaction,
 4204                        title,
 4205                        cx,
 4206                    )
 4207                    .await
 4208                }))
 4209            }
 4210        }
 4211    }
 4212
 4213    pub async fn open_project_transaction(
 4214        this: &WeakView<Editor>,
 4215        workspace: WeakView<Workspace>,
 4216        transaction: ProjectTransaction,
 4217        title: String,
 4218        mut cx: AsyncWindowContext,
 4219    ) -> Result<()> {
 4220        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4221        cx.update(|cx| {
 4222            entries.sort_unstable_by_key(|(buffer, _)| {
 4223                buffer.read(cx).file().map(|f| f.path().clone())
 4224            });
 4225        })?;
 4226
 4227        // If the project transaction's edits are all contained within this editor, then
 4228        // avoid opening a new editor to display them.
 4229
 4230        if let Some((buffer, transaction)) = entries.first() {
 4231            if entries.len() == 1 {
 4232                let excerpt = this.update(&mut cx, |editor, cx| {
 4233                    editor
 4234                        .buffer()
 4235                        .read(cx)
 4236                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4237                })?;
 4238                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4239                    if excerpted_buffer == *buffer {
 4240                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4241                            let excerpt_range = excerpt_range.to_offset(buffer);
 4242                            buffer
 4243                                .edited_ranges_for_transaction::<usize>(transaction)
 4244                                .all(|range| {
 4245                                    excerpt_range.start <= range.start
 4246                                        && excerpt_range.end >= range.end
 4247                                })
 4248                        })?;
 4249
 4250                        if all_edits_within_excerpt {
 4251                            return Ok(());
 4252                        }
 4253                    }
 4254                }
 4255            }
 4256        } else {
 4257            return Ok(());
 4258        }
 4259
 4260        let mut ranges_to_highlight = Vec::new();
 4261        let excerpt_buffer = cx.new_model(|cx| {
 4262            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4263            for (buffer_handle, transaction) in &entries {
 4264                let buffer = buffer_handle.read(cx);
 4265                ranges_to_highlight.extend(
 4266                    multibuffer.push_excerpts_with_context_lines(
 4267                        buffer_handle.clone(),
 4268                        buffer
 4269                            .edited_ranges_for_transaction::<usize>(transaction)
 4270                            .collect(),
 4271                        DEFAULT_MULTIBUFFER_CONTEXT,
 4272                        cx,
 4273                    ),
 4274                );
 4275            }
 4276            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4277            multibuffer
 4278        })?;
 4279
 4280        workspace.update(&mut cx, |workspace, cx| {
 4281            let project = workspace.project().clone();
 4282            let editor =
 4283                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4284            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4285            editor.update(cx, |editor, cx| {
 4286                editor.highlight_background::<Self>(
 4287                    &ranges_to_highlight,
 4288                    |theme| theme.editor_highlighted_line_background,
 4289                    cx,
 4290                );
 4291            });
 4292        })?;
 4293
 4294        Ok(())
 4295    }
 4296
 4297    pub fn clear_code_action_providers(&mut self) {
 4298        self.code_action_providers.clear();
 4299        self.available_code_actions.take();
 4300    }
 4301
 4302    pub fn add_code_action_provider(
 4303        &mut self,
 4304        provider: Rc<dyn CodeActionProvider>,
 4305        cx: &mut ViewContext<Self>,
 4306    ) {
 4307        if self
 4308            .code_action_providers
 4309            .iter()
 4310            .any(|existing_provider| existing_provider.id() == provider.id())
 4311        {
 4312            return;
 4313        }
 4314
 4315        self.code_action_providers.push(provider);
 4316        self.refresh_code_actions(cx);
 4317    }
 4318
 4319    pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
 4320        self.code_action_providers
 4321            .retain(|provider| provider.id() != id);
 4322        self.refresh_code_actions(cx);
 4323    }
 4324
 4325    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4326        let buffer = self.buffer.read(cx);
 4327        let newest_selection = self.selections.newest_anchor().clone();
 4328        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4329        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4330        if start_buffer != end_buffer {
 4331            return None;
 4332        }
 4333
 4334        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4335            cx.background_executor()
 4336                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4337                .await;
 4338
 4339            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4340                let providers = this.code_action_providers.clone();
 4341                let tasks = this
 4342                    .code_action_providers
 4343                    .iter()
 4344                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4345                    .collect::<Vec<_>>();
 4346                (providers, tasks)
 4347            })?;
 4348
 4349            let mut actions = Vec::new();
 4350            for (provider, provider_actions) in
 4351                providers.into_iter().zip(future::join_all(tasks).await)
 4352            {
 4353                if let Some(provider_actions) = provider_actions.log_err() {
 4354                    actions.extend(provider_actions.into_iter().map(|action| {
 4355                        AvailableCodeAction {
 4356                            excerpt_id: newest_selection.start.excerpt_id,
 4357                            action,
 4358                            provider: provider.clone(),
 4359                        }
 4360                    }));
 4361                }
 4362            }
 4363
 4364            this.update(&mut cx, |this, cx| {
 4365                this.available_code_actions = if actions.is_empty() {
 4366                    None
 4367                } else {
 4368                    Some((
 4369                        Location {
 4370                            buffer: start_buffer,
 4371                            range: start..end,
 4372                        },
 4373                        actions.into(),
 4374                    ))
 4375                };
 4376                cx.notify();
 4377            })
 4378        }));
 4379        None
 4380    }
 4381
 4382    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4383        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4384            self.show_git_blame_inline = false;
 4385
 4386            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4387                cx.background_executor().timer(delay).await;
 4388
 4389                this.update(&mut cx, |this, cx| {
 4390                    this.show_git_blame_inline = true;
 4391                    cx.notify();
 4392                })
 4393                .log_err();
 4394            }));
 4395        }
 4396    }
 4397
 4398    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4399        if self.pending_rename.is_some() {
 4400            return None;
 4401        }
 4402
 4403        let provider = self.semantics_provider.clone()?;
 4404        let buffer = self.buffer.read(cx);
 4405        let newest_selection = self.selections.newest_anchor().clone();
 4406        let cursor_position = newest_selection.head();
 4407        let (cursor_buffer, cursor_buffer_position) =
 4408            buffer.text_anchor_for_position(cursor_position, cx)?;
 4409        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4410        if cursor_buffer != tail_buffer {
 4411            return None;
 4412        }
 4413        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4414        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4415            cx.background_executor()
 4416                .timer(Duration::from_millis(debounce))
 4417                .await;
 4418
 4419            let highlights = if let Some(highlights) = cx
 4420                .update(|cx| {
 4421                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4422                })
 4423                .ok()
 4424                .flatten()
 4425            {
 4426                highlights.await.log_err()
 4427            } else {
 4428                None
 4429            };
 4430
 4431            if let Some(highlights) = highlights {
 4432                this.update(&mut cx, |this, cx| {
 4433                    if this.pending_rename.is_some() {
 4434                        return;
 4435                    }
 4436
 4437                    let buffer_id = cursor_position.buffer_id;
 4438                    let buffer = this.buffer.read(cx);
 4439                    if !buffer
 4440                        .text_anchor_for_position(cursor_position, cx)
 4441                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4442                    {
 4443                        return;
 4444                    }
 4445
 4446                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4447                    let mut write_ranges = Vec::new();
 4448                    let mut read_ranges = Vec::new();
 4449                    for highlight in highlights {
 4450                        for (excerpt_id, excerpt_range) in
 4451                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4452                        {
 4453                            let start = highlight
 4454                                .range
 4455                                .start
 4456                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4457                            let end = highlight
 4458                                .range
 4459                                .end
 4460                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4461                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4462                                continue;
 4463                            }
 4464
 4465                            let range = Anchor {
 4466                                buffer_id,
 4467                                excerpt_id,
 4468                                text_anchor: start,
 4469                            }..Anchor {
 4470                                buffer_id,
 4471                                excerpt_id,
 4472                                text_anchor: end,
 4473                            };
 4474                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4475                                write_ranges.push(range);
 4476                            } else {
 4477                                read_ranges.push(range);
 4478                            }
 4479                        }
 4480                    }
 4481
 4482                    this.highlight_background::<DocumentHighlightRead>(
 4483                        &read_ranges,
 4484                        |theme| theme.editor_document_highlight_read_background,
 4485                        cx,
 4486                    );
 4487                    this.highlight_background::<DocumentHighlightWrite>(
 4488                        &write_ranges,
 4489                        |theme| theme.editor_document_highlight_write_background,
 4490                        cx,
 4491                    );
 4492                    cx.notify();
 4493                })
 4494                .log_err();
 4495            }
 4496        }));
 4497        None
 4498    }
 4499
 4500    pub fn refresh_inline_completion(
 4501        &mut self,
 4502        debounce: bool,
 4503        user_requested: bool,
 4504        cx: &mut ViewContext<Self>,
 4505    ) -> Option<()> {
 4506        let provider = self.inline_completion_provider()?;
 4507        let cursor = self.selections.newest_anchor().head();
 4508        let (buffer, cursor_buffer_position) =
 4509            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4510
 4511        if !user_requested
 4512            && (!self.enable_inline_completions
 4513                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4514                || !self.is_focused(cx))
 4515        {
 4516            self.discard_inline_completion(false, cx);
 4517            return None;
 4518        }
 4519
 4520        self.update_visible_inline_completion(cx);
 4521        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4522        Some(())
 4523    }
 4524
 4525    fn cycle_inline_completion(
 4526        &mut self,
 4527        direction: Direction,
 4528        cx: &mut ViewContext<Self>,
 4529    ) -> Option<()> {
 4530        let provider = self.inline_completion_provider()?;
 4531        let cursor = self.selections.newest_anchor().head();
 4532        let (buffer, cursor_buffer_position) =
 4533            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4534        if !self.enable_inline_completions
 4535            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4536        {
 4537            return None;
 4538        }
 4539
 4540        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4541        self.update_visible_inline_completion(cx);
 4542
 4543        Some(())
 4544    }
 4545
 4546    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4547        if !self.has_active_inline_completion() {
 4548            self.refresh_inline_completion(false, true, cx);
 4549            return;
 4550        }
 4551
 4552        self.update_visible_inline_completion(cx);
 4553    }
 4554
 4555    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4556        self.show_cursor_names(cx);
 4557    }
 4558
 4559    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4560        self.show_cursor_names = true;
 4561        cx.notify();
 4562        cx.spawn(|this, mut cx| async move {
 4563            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4564            this.update(&mut cx, |this, cx| {
 4565                this.show_cursor_names = false;
 4566                cx.notify()
 4567            })
 4568            .ok()
 4569        })
 4570        .detach();
 4571    }
 4572
 4573    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4574        if self.has_active_inline_completion() {
 4575            self.cycle_inline_completion(Direction::Next, cx);
 4576        } else {
 4577            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4578            if is_copilot_disabled {
 4579                cx.propagate();
 4580            }
 4581        }
 4582    }
 4583
 4584    pub fn previous_inline_completion(
 4585        &mut self,
 4586        _: &PreviousInlineCompletion,
 4587        cx: &mut ViewContext<Self>,
 4588    ) {
 4589        if self.has_active_inline_completion() {
 4590            self.cycle_inline_completion(Direction::Prev, cx);
 4591        } else {
 4592            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4593            if is_copilot_disabled {
 4594                cx.propagate();
 4595            }
 4596        }
 4597    }
 4598
 4599    pub fn accept_inline_completion(
 4600        &mut self,
 4601        _: &AcceptInlineCompletion,
 4602        cx: &mut ViewContext<Self>,
 4603    ) {
 4604        let buffer = self.buffer.read(cx);
 4605        let snapshot = buffer.snapshot(cx);
 4606        let selection = self.selections.newest_adjusted(cx);
 4607        let cursor = selection.head();
 4608        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4609        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4610        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4611        {
 4612            if cursor.column < suggested_indent.len
 4613                && cursor.column <= current_indent.len
 4614                && current_indent.len <= suggested_indent.len
 4615            {
 4616                self.tab(&Default::default(), cx);
 4617                return;
 4618            }
 4619        }
 4620
 4621        if self.show_inline_completions_in_menu(cx) {
 4622            self.hide_context_menu(cx);
 4623        }
 4624
 4625        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4626            return;
 4627        };
 4628
 4629        self.report_inline_completion_event(true, cx);
 4630
 4631        match &active_inline_completion.completion {
 4632            InlineCompletion::Move(position) => {
 4633                let position = *position;
 4634                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4635                    selections.select_anchor_ranges([position..position]);
 4636                });
 4637            }
 4638            InlineCompletion::Edit(edits) => {
 4639                if let Some(provider) = self.inline_completion_provider() {
 4640                    provider.accept(cx);
 4641                }
 4642
 4643                let snapshot = self.buffer.read(cx).snapshot(cx);
 4644                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4645
 4646                self.buffer.update(cx, |buffer, cx| {
 4647                    buffer.edit(edits.iter().cloned(), None, cx)
 4648                });
 4649
 4650                self.change_selections(None, cx, |s| {
 4651                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4652                });
 4653
 4654                self.update_visible_inline_completion(cx);
 4655                if self.active_inline_completion.is_none() {
 4656                    self.refresh_inline_completion(true, true, cx);
 4657                }
 4658
 4659                cx.notify();
 4660            }
 4661        }
 4662    }
 4663
 4664    pub fn accept_partial_inline_completion(
 4665        &mut self,
 4666        _: &AcceptPartialInlineCompletion,
 4667        cx: &mut ViewContext<Self>,
 4668    ) {
 4669        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4670            return;
 4671        };
 4672        if self.selections.count() != 1 {
 4673            return;
 4674        }
 4675
 4676        self.report_inline_completion_event(true, cx);
 4677
 4678        match &active_inline_completion.completion {
 4679            InlineCompletion::Move(position) => {
 4680                let position = *position;
 4681                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4682                    selections.select_anchor_ranges([position..position]);
 4683                });
 4684            }
 4685            InlineCompletion::Edit(edits) => {
 4686                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4687                    let text = edits[0].1.as_str();
 4688                    let mut partial_completion = text
 4689                        .chars()
 4690                        .by_ref()
 4691                        .take_while(|c| c.is_alphabetic())
 4692                        .collect::<String>();
 4693                    if partial_completion.is_empty() {
 4694                        partial_completion = text
 4695                            .chars()
 4696                            .by_ref()
 4697                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4698                            .collect::<String>();
 4699                    }
 4700
 4701                    cx.emit(EditorEvent::InputHandled {
 4702                        utf16_range_to_replace: None,
 4703                        text: partial_completion.clone().into(),
 4704                    });
 4705
 4706                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4707
 4708                    self.refresh_inline_completion(true, true, cx);
 4709                    cx.notify();
 4710                }
 4711            }
 4712        }
 4713    }
 4714
 4715    fn discard_inline_completion(
 4716        &mut self,
 4717        should_report_inline_completion_event: bool,
 4718        cx: &mut ViewContext<Self>,
 4719    ) -> bool {
 4720        if should_report_inline_completion_event {
 4721            self.report_inline_completion_event(false, cx);
 4722        }
 4723
 4724        if let Some(provider) = self.inline_completion_provider() {
 4725            provider.discard(cx);
 4726        }
 4727
 4728        self.take_active_inline_completion(cx).is_some()
 4729    }
 4730
 4731    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4732        let Some(provider) = self.inline_completion_provider() else {
 4733            return;
 4734        };
 4735        let Some(project) = self.project.as_ref() else {
 4736            return;
 4737        };
 4738        let Some((_, buffer, _)) = self
 4739            .buffer
 4740            .read(cx)
 4741            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4742        else {
 4743            return;
 4744        };
 4745
 4746        let project = project.read(cx);
 4747        let extension = buffer
 4748            .read(cx)
 4749            .file()
 4750            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4751        project.client().telemetry().report_inline_completion_event(
 4752            provider.name().into(),
 4753            accepted,
 4754            extension,
 4755        );
 4756    }
 4757
 4758    pub fn has_active_inline_completion(&self) -> bool {
 4759        self.active_inline_completion.is_some()
 4760    }
 4761
 4762    fn take_active_inline_completion(
 4763        &mut self,
 4764        cx: &mut ViewContext<Self>,
 4765    ) -> Option<InlineCompletion> {
 4766        let active_inline_completion = self.active_inline_completion.take()?;
 4767        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4768        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4769        Some(active_inline_completion.completion)
 4770    }
 4771
 4772    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4773        let selection = self.selections.newest_anchor();
 4774        let cursor = selection.head();
 4775        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4776        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4777        let excerpt_id = cursor.excerpt_id;
 4778
 4779        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 4780            && (self.context_menu.borrow().is_some()
 4781                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 4782        if completions_menu_has_precedence
 4783            || !offset_selection.is_empty()
 4784            || self
 4785                .active_inline_completion
 4786                .as_ref()
 4787                .map_or(false, |completion| {
 4788                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4789                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4790                    !invalidation_range.contains(&offset_selection.head())
 4791                })
 4792        {
 4793            self.discard_inline_completion(false, cx);
 4794            return None;
 4795        }
 4796
 4797        self.take_active_inline_completion(cx);
 4798        let provider = self.inline_completion_provider()?;
 4799
 4800        let (buffer, cursor_buffer_position) =
 4801            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4802
 4803        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4804        let edits = completion
 4805            .edits
 4806            .into_iter()
 4807            .flat_map(|(range, new_text)| {
 4808                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4809                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4810                Some((start..end, new_text))
 4811            })
 4812            .collect::<Vec<_>>();
 4813        if edits.is_empty() {
 4814            return None;
 4815        }
 4816
 4817        let first_edit_start = edits.first().unwrap().0.start;
 4818        let edit_start_row = first_edit_start
 4819            .to_point(&multibuffer)
 4820            .row
 4821            .saturating_sub(2);
 4822
 4823        let last_edit_end = edits.last().unwrap().0.end;
 4824        let edit_end_row = cmp::min(
 4825            multibuffer.max_point().row,
 4826            last_edit_end.to_point(&multibuffer).row + 2,
 4827        );
 4828
 4829        let cursor_row = cursor.to_point(&multibuffer).row;
 4830
 4831        let mut inlay_ids = Vec::new();
 4832        let invalidation_row_range;
 4833        let completion;
 4834        if cursor_row < edit_start_row {
 4835            invalidation_row_range = cursor_row..edit_end_row;
 4836            completion = InlineCompletion::Move(first_edit_start);
 4837        } else if cursor_row > edit_end_row {
 4838            invalidation_row_range = edit_start_row..cursor_row;
 4839            completion = InlineCompletion::Move(first_edit_start);
 4840        } else {
 4841            if edits
 4842                .iter()
 4843                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4844            {
 4845                let mut inlays = Vec::new();
 4846                for (range, new_text) in &edits {
 4847                    let inlay = Inlay::inline_completion(
 4848                        post_inc(&mut self.next_inlay_id),
 4849                        range.start,
 4850                        new_text.as_str(),
 4851                    );
 4852                    inlay_ids.push(inlay.id);
 4853                    inlays.push(inlay);
 4854                }
 4855
 4856                self.splice_inlays(vec![], inlays, cx);
 4857            } else {
 4858                let background_color = cx.theme().status().deleted_background;
 4859                self.highlight_text::<InlineCompletionHighlight>(
 4860                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4861                    HighlightStyle {
 4862                        background_color: Some(background_color),
 4863                        ..Default::default()
 4864                    },
 4865                    cx,
 4866                );
 4867            }
 4868
 4869            invalidation_row_range = edit_start_row..edit_end_row;
 4870            completion = InlineCompletion::Edit(edits);
 4871        };
 4872
 4873        let invalidation_range = multibuffer
 4874            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4875            ..multibuffer.anchor_after(Point::new(
 4876                invalidation_row_range.end,
 4877                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4878            ));
 4879
 4880        self.active_inline_completion = Some(InlineCompletionState {
 4881            inlay_ids,
 4882            completion,
 4883            invalidation_range,
 4884        });
 4885
 4886        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 4887            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4888                match self.context_menu.borrow_mut().as_mut() {
 4889                    Some(CodeContextMenu::Completions(menu)) => {
 4890                        menu.show_inline_completion_hint(hint);
 4891                    }
 4892                    _ => {}
 4893                }
 4894            }
 4895        }
 4896
 4897        cx.notify();
 4898
 4899        Some(())
 4900    }
 4901
 4902    fn inline_completion_menu_hint(
 4903        &mut self,
 4904        cx: &mut ViewContext<Self>,
 4905    ) -> Option<InlineCompletionMenuHint> {
 4906        if self.has_active_inline_completion() {
 4907            let provider_name = self.inline_completion_provider()?.display_name();
 4908            let editor_snapshot = self.snapshot(cx);
 4909
 4910            let text = match &self.active_inline_completion.as_ref()?.completion {
 4911                InlineCompletion::Edit(edits) => {
 4912                    inline_completion_edit_text(&editor_snapshot, edits, true, cx)
 4913                }
 4914                InlineCompletion::Move(target) => {
 4915                    let target_point =
 4916                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4917                    let target_line = target_point.row + 1;
 4918                    InlineCompletionText::Move(
 4919                        format!("Jump to edit in line {}", target_line).into(),
 4920                    )
 4921                }
 4922            };
 4923
 4924            Some(InlineCompletionMenuHint {
 4925                provider_name,
 4926                text,
 4927            })
 4928        } else {
 4929            None
 4930        }
 4931    }
 4932
 4933    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4934        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4935    }
 4936
 4937    fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
 4938        EditorSettings::get_global(cx).show_inline_completions_in_menu
 4939            && self
 4940                .inline_completion_provider()
 4941                .map_or(false, |provider| provider.show_completions_in_menu())
 4942    }
 4943
 4944    fn render_code_actions_indicator(
 4945        &self,
 4946        _style: &EditorStyle,
 4947        row: DisplayRow,
 4948        is_active: bool,
 4949        cx: &mut ViewContext<Self>,
 4950    ) -> Option<IconButton> {
 4951        if self.available_code_actions.is_some() {
 4952            Some(
 4953                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4954                    .shape(ui::IconButtonShape::Square)
 4955                    .icon_size(IconSize::XSmall)
 4956                    .icon_color(Color::Muted)
 4957                    .toggle_state(is_active)
 4958                    .tooltip({
 4959                        let focus_handle = self.focus_handle.clone();
 4960                        move |cx| {
 4961                            Tooltip::for_action_in(
 4962                                "Toggle Code Actions",
 4963                                &ToggleCodeActions {
 4964                                    deployed_from_indicator: None,
 4965                                },
 4966                                &focus_handle,
 4967                                cx,
 4968                            )
 4969                        }
 4970                    })
 4971                    .on_click(cx.listener(move |editor, _e, cx| {
 4972                        editor.focus(cx);
 4973                        editor.toggle_code_actions(
 4974                            &ToggleCodeActions {
 4975                                deployed_from_indicator: Some(row),
 4976                            },
 4977                            cx,
 4978                        );
 4979                    })),
 4980            )
 4981        } else {
 4982            None
 4983        }
 4984    }
 4985
 4986    fn clear_tasks(&mut self) {
 4987        self.tasks.clear()
 4988    }
 4989
 4990    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4991        if self.tasks.insert(key, value).is_some() {
 4992            // This case should hopefully be rare, but just in case...
 4993            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4994        }
 4995    }
 4996
 4997    fn build_tasks_context(
 4998        project: &Model<Project>,
 4999        buffer: &Model<Buffer>,
 5000        buffer_row: u32,
 5001        tasks: &Arc<RunnableTasks>,
 5002        cx: &mut ViewContext<Self>,
 5003    ) -> Task<Option<task::TaskContext>> {
 5004        let position = Point::new(buffer_row, tasks.column);
 5005        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5006        let location = Location {
 5007            buffer: buffer.clone(),
 5008            range: range_start..range_start,
 5009        };
 5010        // Fill in the environmental variables from the tree-sitter captures
 5011        let mut captured_task_variables = TaskVariables::default();
 5012        for (capture_name, value) in tasks.extra_variables.clone() {
 5013            captured_task_variables.insert(
 5014                task::VariableName::Custom(capture_name.into()),
 5015                value.clone(),
 5016            );
 5017        }
 5018        project.update(cx, |project, cx| {
 5019            project.task_store().update(cx, |task_store, cx| {
 5020                task_store.task_context_for_location(captured_task_variables, location, cx)
 5021            })
 5022        })
 5023    }
 5024
 5025    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5026        let Some((workspace, _)) = self.workspace.clone() else {
 5027            return;
 5028        };
 5029        let Some(project) = self.project.clone() else {
 5030            return;
 5031        };
 5032
 5033        // Try to find a closest, enclosing node using tree-sitter that has a
 5034        // task
 5035        let Some((buffer, buffer_row, tasks)) = self
 5036            .find_enclosing_node_task(cx)
 5037            // Or find the task that's closest in row-distance.
 5038            .or_else(|| self.find_closest_task(cx))
 5039        else {
 5040            return;
 5041        };
 5042
 5043        let reveal_strategy = action.reveal;
 5044        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5045        cx.spawn(|_, mut cx| async move {
 5046            let context = task_context.await?;
 5047            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5048
 5049            let resolved = resolved_task.resolved.as_mut()?;
 5050            resolved.reveal = reveal_strategy;
 5051
 5052            workspace
 5053                .update(&mut cx, |workspace, cx| {
 5054                    workspace::tasks::schedule_resolved_task(
 5055                        workspace,
 5056                        task_source_kind,
 5057                        resolved_task,
 5058                        false,
 5059                        cx,
 5060                    );
 5061                })
 5062                .ok()
 5063        })
 5064        .detach();
 5065    }
 5066
 5067    fn find_closest_task(
 5068        &mut self,
 5069        cx: &mut ViewContext<Self>,
 5070    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5071        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5072
 5073        let ((buffer_id, row), tasks) = self
 5074            .tasks
 5075            .iter()
 5076            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5077
 5078        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5079        let tasks = Arc::new(tasks.to_owned());
 5080        Some((buffer, *row, tasks))
 5081    }
 5082
 5083    fn find_enclosing_node_task(
 5084        &mut self,
 5085        cx: &mut ViewContext<Self>,
 5086    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5087        let snapshot = self.buffer.read(cx).snapshot(cx);
 5088        let offset = self.selections.newest::<usize>(cx).head();
 5089        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5090        let buffer_id = excerpt.buffer().remote_id();
 5091
 5092        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5093        let mut cursor = layer.node().walk();
 5094
 5095        while cursor.goto_first_child_for_byte(offset).is_some() {
 5096            if cursor.node().end_byte() == offset {
 5097                cursor.goto_next_sibling();
 5098            }
 5099        }
 5100
 5101        // Ascend to the smallest ancestor that contains the range and has a task.
 5102        loop {
 5103            let node = cursor.node();
 5104            let node_range = node.byte_range();
 5105            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5106
 5107            // Check if this node contains our offset
 5108            if node_range.start <= offset && node_range.end >= offset {
 5109                // If it contains offset, check for task
 5110                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5111                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5112                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5113                }
 5114            }
 5115
 5116            if !cursor.goto_parent() {
 5117                break;
 5118            }
 5119        }
 5120        None
 5121    }
 5122
 5123    fn render_run_indicator(
 5124        &self,
 5125        _style: &EditorStyle,
 5126        is_active: bool,
 5127        row: DisplayRow,
 5128        cx: &mut ViewContext<Self>,
 5129    ) -> IconButton {
 5130        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5131            .shape(ui::IconButtonShape::Square)
 5132            .icon_size(IconSize::XSmall)
 5133            .icon_color(Color::Muted)
 5134            .toggle_state(is_active)
 5135            .on_click(cx.listener(move |editor, _e, cx| {
 5136                editor.focus(cx);
 5137                editor.toggle_code_actions(
 5138                    &ToggleCodeActions {
 5139                        deployed_from_indicator: Some(row),
 5140                    },
 5141                    cx,
 5142                );
 5143            }))
 5144    }
 5145
 5146    #[cfg(any(feature = "test-support", test))]
 5147    pub fn context_menu_visible(&self) -> bool {
 5148        self.context_menu
 5149            .borrow()
 5150            .as_ref()
 5151            .map_or(false, |menu| menu.visible())
 5152    }
 5153
 5154    #[cfg(feature = "test-support")]
 5155    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5156        self.context_menu
 5157            .borrow()
 5158            .as_ref()
 5159            .map_or(false, |menu| match menu {
 5160                CodeContextMenu::Completions(menu) => {
 5161                    menu.entries.borrow().first().map_or(false, |entry| {
 5162                        matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5163                    })
 5164                }
 5165                CodeContextMenu::CodeActions(_) => false,
 5166            })
 5167    }
 5168
 5169    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5170        self.context_menu
 5171            .borrow()
 5172            .as_ref()
 5173            .map(|menu| menu.origin(cursor_position))
 5174    }
 5175
 5176    fn render_context_menu(
 5177        &self,
 5178        style: &EditorStyle,
 5179        max_height_in_lines: u32,
 5180        cx: &mut ViewContext<Editor>,
 5181    ) -> Option<AnyElement> {
 5182        self.context_menu.borrow().as_ref().and_then(|menu| {
 5183            if menu.visible() {
 5184                Some(menu.render(style, max_height_in_lines, cx))
 5185            } else {
 5186                None
 5187            }
 5188        })
 5189    }
 5190
 5191    fn render_context_menu_aside(
 5192        &self,
 5193        style: &EditorStyle,
 5194        max_size: Size<Pixels>,
 5195        cx: &mut ViewContext<Editor>,
 5196    ) -> Option<AnyElement> {
 5197        self.context_menu.borrow().as_ref().and_then(|menu| {
 5198            if menu.visible() {
 5199                menu.render_aside(
 5200                    style,
 5201                    max_size,
 5202                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5203                    cx,
 5204                )
 5205            } else {
 5206                None
 5207            }
 5208        })
 5209    }
 5210
 5211    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5212        cx.notify();
 5213        self.completion_tasks.clear();
 5214        let context_menu = self.context_menu.borrow_mut().take();
 5215        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5216            self.update_visible_inline_completion(cx);
 5217        }
 5218        context_menu
 5219    }
 5220
 5221    fn show_snippet_choices(
 5222        &mut self,
 5223        choices: &Vec<String>,
 5224        selection: Range<Anchor>,
 5225        cx: &mut ViewContext<Self>,
 5226    ) {
 5227        if selection.start.buffer_id.is_none() {
 5228            return;
 5229        }
 5230        let buffer_id = selection.start.buffer_id.unwrap();
 5231        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5232        let id = post_inc(&mut self.next_completion_id);
 5233
 5234        if let Some(buffer) = buffer {
 5235            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5236                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5237            ));
 5238        }
 5239    }
 5240
 5241    pub fn insert_snippet(
 5242        &mut self,
 5243        insertion_ranges: &[Range<usize>],
 5244        snippet: Snippet,
 5245        cx: &mut ViewContext<Self>,
 5246    ) -> Result<()> {
 5247        struct Tabstop<T> {
 5248            is_end_tabstop: bool,
 5249            ranges: Vec<Range<T>>,
 5250            choices: Option<Vec<String>>,
 5251        }
 5252
 5253        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5254            let snippet_text: Arc<str> = snippet.text.clone().into();
 5255            buffer.edit(
 5256                insertion_ranges
 5257                    .iter()
 5258                    .cloned()
 5259                    .map(|range| (range, snippet_text.clone())),
 5260                Some(AutoindentMode::EachLine),
 5261                cx,
 5262            );
 5263
 5264            let snapshot = &*buffer.read(cx);
 5265            let snippet = &snippet;
 5266            snippet
 5267                .tabstops
 5268                .iter()
 5269                .map(|tabstop| {
 5270                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5271                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5272                    });
 5273                    let mut tabstop_ranges = tabstop
 5274                        .ranges
 5275                        .iter()
 5276                        .flat_map(|tabstop_range| {
 5277                            let mut delta = 0_isize;
 5278                            insertion_ranges.iter().map(move |insertion_range| {
 5279                                let insertion_start = insertion_range.start as isize + delta;
 5280                                delta +=
 5281                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5282
 5283                                let start = ((insertion_start + tabstop_range.start) as usize)
 5284                                    .min(snapshot.len());
 5285                                let end = ((insertion_start + tabstop_range.end) as usize)
 5286                                    .min(snapshot.len());
 5287                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5288                            })
 5289                        })
 5290                        .collect::<Vec<_>>();
 5291                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5292
 5293                    Tabstop {
 5294                        is_end_tabstop,
 5295                        ranges: tabstop_ranges,
 5296                        choices: tabstop.choices.clone(),
 5297                    }
 5298                })
 5299                .collect::<Vec<_>>()
 5300        });
 5301        if let Some(tabstop) = tabstops.first() {
 5302            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5303                s.select_ranges(tabstop.ranges.iter().cloned());
 5304            });
 5305
 5306            if let Some(choices) = &tabstop.choices {
 5307                if let Some(selection) = tabstop.ranges.first() {
 5308                    self.show_snippet_choices(choices, selection.clone(), cx)
 5309                }
 5310            }
 5311
 5312            // If we're already at the last tabstop and it's at the end of the snippet,
 5313            // we're done, we don't need to keep the state around.
 5314            if !tabstop.is_end_tabstop {
 5315                let choices = tabstops
 5316                    .iter()
 5317                    .map(|tabstop| tabstop.choices.clone())
 5318                    .collect();
 5319
 5320                let ranges = tabstops
 5321                    .into_iter()
 5322                    .map(|tabstop| tabstop.ranges)
 5323                    .collect::<Vec<_>>();
 5324
 5325                self.snippet_stack.push(SnippetState {
 5326                    active_index: 0,
 5327                    ranges,
 5328                    choices,
 5329                });
 5330            }
 5331
 5332            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5333            if self.autoclose_regions.is_empty() {
 5334                let snapshot = self.buffer.read(cx).snapshot(cx);
 5335                for selection in &mut self.selections.all::<Point>(cx) {
 5336                    let selection_head = selection.head();
 5337                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5338                        continue;
 5339                    };
 5340
 5341                    let mut bracket_pair = None;
 5342                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5343                    let prev_chars = snapshot
 5344                        .reversed_chars_at(selection_head)
 5345                        .collect::<String>();
 5346                    for (pair, enabled) in scope.brackets() {
 5347                        if enabled
 5348                            && pair.close
 5349                            && prev_chars.starts_with(pair.start.as_str())
 5350                            && next_chars.starts_with(pair.end.as_str())
 5351                        {
 5352                            bracket_pair = Some(pair.clone());
 5353                            break;
 5354                        }
 5355                    }
 5356                    if let Some(pair) = bracket_pair {
 5357                        let start = snapshot.anchor_after(selection_head);
 5358                        let end = snapshot.anchor_after(selection_head);
 5359                        self.autoclose_regions.push(AutocloseRegion {
 5360                            selection_id: selection.id,
 5361                            range: start..end,
 5362                            pair,
 5363                        });
 5364                    }
 5365                }
 5366            }
 5367        }
 5368        Ok(())
 5369    }
 5370
 5371    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5372        self.move_to_snippet_tabstop(Bias::Right, cx)
 5373    }
 5374
 5375    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5376        self.move_to_snippet_tabstop(Bias::Left, cx)
 5377    }
 5378
 5379    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5380        if let Some(mut snippet) = self.snippet_stack.pop() {
 5381            match bias {
 5382                Bias::Left => {
 5383                    if snippet.active_index > 0 {
 5384                        snippet.active_index -= 1;
 5385                    } else {
 5386                        self.snippet_stack.push(snippet);
 5387                        return false;
 5388                    }
 5389                }
 5390                Bias::Right => {
 5391                    if snippet.active_index + 1 < snippet.ranges.len() {
 5392                        snippet.active_index += 1;
 5393                    } else {
 5394                        self.snippet_stack.push(snippet);
 5395                        return false;
 5396                    }
 5397                }
 5398            }
 5399            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5400                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5401                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5402                });
 5403
 5404                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5405                    if let Some(selection) = current_ranges.first() {
 5406                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5407                    }
 5408                }
 5409
 5410                // If snippet state is not at the last tabstop, push it back on the stack
 5411                if snippet.active_index + 1 < snippet.ranges.len() {
 5412                    self.snippet_stack.push(snippet);
 5413                }
 5414                return true;
 5415            }
 5416        }
 5417
 5418        false
 5419    }
 5420
 5421    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5422        self.transact(cx, |this, cx| {
 5423            this.select_all(&SelectAll, cx);
 5424            this.insert("", cx);
 5425        });
 5426    }
 5427
 5428    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5429        self.transact(cx, |this, cx| {
 5430            this.select_autoclose_pair(cx);
 5431            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5432            if !this.linked_edit_ranges.is_empty() {
 5433                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5434                let snapshot = this.buffer.read(cx).snapshot(cx);
 5435
 5436                for selection in selections.iter() {
 5437                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5438                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5439                    if selection_start.buffer_id != selection_end.buffer_id {
 5440                        continue;
 5441                    }
 5442                    if let Some(ranges) =
 5443                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5444                    {
 5445                        for (buffer, entries) in ranges {
 5446                            linked_ranges.entry(buffer).or_default().extend(entries);
 5447                        }
 5448                    }
 5449                }
 5450            }
 5451
 5452            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5453            if !this.selections.line_mode {
 5454                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5455                for selection in &mut selections {
 5456                    if selection.is_empty() {
 5457                        let old_head = selection.head();
 5458                        let mut new_head =
 5459                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5460                                .to_point(&display_map);
 5461                        if let Some((buffer, line_buffer_range)) = display_map
 5462                            .buffer_snapshot
 5463                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5464                        {
 5465                            let indent_size =
 5466                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5467                            let indent_len = match indent_size.kind {
 5468                                IndentKind::Space => {
 5469                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5470                                }
 5471                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5472                            };
 5473                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5474                                let indent_len = indent_len.get();
 5475                                new_head = cmp::min(
 5476                                    new_head,
 5477                                    MultiBufferPoint::new(
 5478                                        old_head.row,
 5479                                        ((old_head.column - 1) / indent_len) * indent_len,
 5480                                    ),
 5481                                );
 5482                            }
 5483                        }
 5484
 5485                        selection.set_head(new_head, SelectionGoal::None);
 5486                    }
 5487                }
 5488            }
 5489
 5490            this.signature_help_state.set_backspace_pressed(true);
 5491            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5492            this.insert("", cx);
 5493            let empty_str: Arc<str> = Arc::from("");
 5494            for (buffer, edits) in linked_ranges {
 5495                let snapshot = buffer.read(cx).snapshot();
 5496                use text::ToPoint as TP;
 5497
 5498                let edits = edits
 5499                    .into_iter()
 5500                    .map(|range| {
 5501                        let end_point = TP::to_point(&range.end, &snapshot);
 5502                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5503
 5504                        if end_point == start_point {
 5505                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5506                                .saturating_sub(1);
 5507                            start_point =
 5508                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5509                        };
 5510
 5511                        (start_point..end_point, empty_str.clone())
 5512                    })
 5513                    .sorted_by_key(|(range, _)| range.start)
 5514                    .collect::<Vec<_>>();
 5515                buffer.update(cx, |this, cx| {
 5516                    this.edit(edits, None, cx);
 5517                })
 5518            }
 5519            this.refresh_inline_completion(true, false, cx);
 5520            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5521        });
 5522    }
 5523
 5524    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5525        self.transact(cx, |this, cx| {
 5526            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5527                let line_mode = s.line_mode;
 5528                s.move_with(|map, selection| {
 5529                    if selection.is_empty() && !line_mode {
 5530                        let cursor = movement::right(map, selection.head());
 5531                        selection.end = cursor;
 5532                        selection.reversed = true;
 5533                        selection.goal = SelectionGoal::None;
 5534                    }
 5535                })
 5536            });
 5537            this.insert("", cx);
 5538            this.refresh_inline_completion(true, false, cx);
 5539        });
 5540    }
 5541
 5542    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5543        if self.move_to_prev_snippet_tabstop(cx) {
 5544            return;
 5545        }
 5546
 5547        self.outdent(&Outdent, cx);
 5548    }
 5549
 5550    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5551        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5552            return;
 5553        }
 5554
 5555        let mut selections = self.selections.all_adjusted(cx);
 5556        let buffer = self.buffer.read(cx);
 5557        let snapshot = buffer.snapshot(cx);
 5558        let rows_iter = selections.iter().map(|s| s.head().row);
 5559        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5560
 5561        let mut edits = Vec::new();
 5562        let mut prev_edited_row = 0;
 5563        let mut row_delta = 0;
 5564        for selection in &mut selections {
 5565            if selection.start.row != prev_edited_row {
 5566                row_delta = 0;
 5567            }
 5568            prev_edited_row = selection.end.row;
 5569
 5570            // If the selection is non-empty, then increase the indentation of the selected lines.
 5571            if !selection.is_empty() {
 5572                row_delta =
 5573                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5574                continue;
 5575            }
 5576
 5577            // If the selection is empty and the cursor is in the leading whitespace before the
 5578            // suggested indentation, then auto-indent the line.
 5579            let cursor = selection.head();
 5580            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5581            if let Some(suggested_indent) =
 5582                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5583            {
 5584                if cursor.column < suggested_indent.len
 5585                    && cursor.column <= current_indent.len
 5586                    && current_indent.len <= suggested_indent.len
 5587                {
 5588                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5589                    selection.end = selection.start;
 5590                    if row_delta == 0 {
 5591                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5592                            cursor.row,
 5593                            current_indent,
 5594                            suggested_indent,
 5595                        ));
 5596                        row_delta = suggested_indent.len - current_indent.len;
 5597                    }
 5598                    continue;
 5599                }
 5600            }
 5601
 5602            // Otherwise, insert a hard or soft tab.
 5603            let settings = buffer.settings_at(cursor, cx);
 5604            let tab_size = if settings.hard_tabs {
 5605                IndentSize::tab()
 5606            } else {
 5607                let tab_size = settings.tab_size.get();
 5608                let char_column = snapshot
 5609                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5610                    .flat_map(str::chars)
 5611                    .count()
 5612                    + row_delta as usize;
 5613                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5614                IndentSize::spaces(chars_to_next_tab_stop)
 5615            };
 5616            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5617            selection.end = selection.start;
 5618            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5619            row_delta += tab_size.len;
 5620        }
 5621
 5622        self.transact(cx, |this, cx| {
 5623            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5624            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5625            this.refresh_inline_completion(true, false, cx);
 5626        });
 5627    }
 5628
 5629    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5630        if self.read_only(cx) {
 5631            return;
 5632        }
 5633        let mut selections = self.selections.all::<Point>(cx);
 5634        let mut prev_edited_row = 0;
 5635        let mut row_delta = 0;
 5636        let mut edits = Vec::new();
 5637        let buffer = self.buffer.read(cx);
 5638        let snapshot = buffer.snapshot(cx);
 5639        for selection in &mut selections {
 5640            if selection.start.row != prev_edited_row {
 5641                row_delta = 0;
 5642            }
 5643            prev_edited_row = selection.end.row;
 5644
 5645            row_delta =
 5646                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5647        }
 5648
 5649        self.transact(cx, |this, cx| {
 5650            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5651            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5652        });
 5653    }
 5654
 5655    fn indent_selection(
 5656        buffer: &MultiBuffer,
 5657        snapshot: &MultiBufferSnapshot,
 5658        selection: &mut Selection<Point>,
 5659        edits: &mut Vec<(Range<Point>, String)>,
 5660        delta_for_start_row: u32,
 5661        cx: &AppContext,
 5662    ) -> u32 {
 5663        let settings = buffer.settings_at(selection.start, cx);
 5664        let tab_size = settings.tab_size.get();
 5665        let indent_kind = if settings.hard_tabs {
 5666            IndentKind::Tab
 5667        } else {
 5668            IndentKind::Space
 5669        };
 5670        let mut start_row = selection.start.row;
 5671        let mut end_row = selection.end.row + 1;
 5672
 5673        // If a selection ends at the beginning of a line, don't indent
 5674        // that last line.
 5675        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5676            end_row -= 1;
 5677        }
 5678
 5679        // Avoid re-indenting a row that has already been indented by a
 5680        // previous selection, but still update this selection's column
 5681        // to reflect that indentation.
 5682        if delta_for_start_row > 0 {
 5683            start_row += 1;
 5684            selection.start.column += delta_for_start_row;
 5685            if selection.end.row == selection.start.row {
 5686                selection.end.column += delta_for_start_row;
 5687            }
 5688        }
 5689
 5690        let mut delta_for_end_row = 0;
 5691        let has_multiple_rows = start_row + 1 != end_row;
 5692        for row in start_row..end_row {
 5693            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5694            let indent_delta = match (current_indent.kind, indent_kind) {
 5695                (IndentKind::Space, IndentKind::Space) => {
 5696                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5697                    IndentSize::spaces(columns_to_next_tab_stop)
 5698                }
 5699                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5700                (_, IndentKind::Tab) => IndentSize::tab(),
 5701            };
 5702
 5703            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5704                0
 5705            } else {
 5706                selection.start.column
 5707            };
 5708            let row_start = Point::new(row, start);
 5709            edits.push((
 5710                row_start..row_start,
 5711                indent_delta.chars().collect::<String>(),
 5712            ));
 5713
 5714            // Update this selection's endpoints to reflect the indentation.
 5715            if row == selection.start.row {
 5716                selection.start.column += indent_delta.len;
 5717            }
 5718            if row == selection.end.row {
 5719                selection.end.column += indent_delta.len;
 5720                delta_for_end_row = indent_delta.len;
 5721            }
 5722        }
 5723
 5724        if selection.start.row == selection.end.row {
 5725            delta_for_start_row + delta_for_end_row
 5726        } else {
 5727            delta_for_end_row
 5728        }
 5729    }
 5730
 5731    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5732        if self.read_only(cx) {
 5733            return;
 5734        }
 5735        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5736        let selections = self.selections.all::<Point>(cx);
 5737        let mut deletion_ranges = Vec::new();
 5738        let mut last_outdent = None;
 5739        {
 5740            let buffer = self.buffer.read(cx);
 5741            let snapshot = buffer.snapshot(cx);
 5742            for selection in &selections {
 5743                let settings = buffer.settings_at(selection.start, cx);
 5744                let tab_size = settings.tab_size.get();
 5745                let mut rows = selection.spanned_rows(false, &display_map);
 5746
 5747                // Avoid re-outdenting a row that has already been outdented by a
 5748                // previous selection.
 5749                if let Some(last_row) = last_outdent {
 5750                    if last_row == rows.start {
 5751                        rows.start = rows.start.next_row();
 5752                    }
 5753                }
 5754                let has_multiple_rows = rows.len() > 1;
 5755                for row in rows.iter_rows() {
 5756                    let indent_size = snapshot.indent_size_for_line(row);
 5757                    if indent_size.len > 0 {
 5758                        let deletion_len = match indent_size.kind {
 5759                            IndentKind::Space => {
 5760                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5761                                if columns_to_prev_tab_stop == 0 {
 5762                                    tab_size
 5763                                } else {
 5764                                    columns_to_prev_tab_stop
 5765                                }
 5766                            }
 5767                            IndentKind::Tab => 1,
 5768                        };
 5769                        let start = if has_multiple_rows
 5770                            || deletion_len > selection.start.column
 5771                            || indent_size.len < selection.start.column
 5772                        {
 5773                            0
 5774                        } else {
 5775                            selection.start.column - deletion_len
 5776                        };
 5777                        deletion_ranges.push(
 5778                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5779                        );
 5780                        last_outdent = Some(row);
 5781                    }
 5782                }
 5783            }
 5784        }
 5785
 5786        self.transact(cx, |this, cx| {
 5787            this.buffer.update(cx, |buffer, cx| {
 5788                let empty_str: Arc<str> = Arc::default();
 5789                buffer.edit(
 5790                    deletion_ranges
 5791                        .into_iter()
 5792                        .map(|range| (range, empty_str.clone())),
 5793                    None,
 5794                    cx,
 5795                );
 5796            });
 5797            let selections = this.selections.all::<usize>(cx);
 5798            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5799        });
 5800    }
 5801
 5802    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5803        if self.read_only(cx) {
 5804            return;
 5805        }
 5806        let selections = self
 5807            .selections
 5808            .all::<usize>(cx)
 5809            .into_iter()
 5810            .map(|s| s.range());
 5811
 5812        self.transact(cx, |this, cx| {
 5813            this.buffer.update(cx, |buffer, cx| {
 5814                buffer.autoindent_ranges(selections, cx);
 5815            });
 5816            let selections = this.selections.all::<usize>(cx);
 5817            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5818        });
 5819    }
 5820
 5821    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5822        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5823        let selections = self.selections.all::<Point>(cx);
 5824
 5825        let mut new_cursors = Vec::new();
 5826        let mut edit_ranges = Vec::new();
 5827        let mut selections = selections.iter().peekable();
 5828        while let Some(selection) = selections.next() {
 5829            let mut rows = selection.spanned_rows(false, &display_map);
 5830            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5831
 5832            // Accumulate contiguous regions of rows that we want to delete.
 5833            while let Some(next_selection) = selections.peek() {
 5834                let next_rows = next_selection.spanned_rows(false, &display_map);
 5835                if next_rows.start <= rows.end {
 5836                    rows.end = next_rows.end;
 5837                    selections.next().unwrap();
 5838                } else {
 5839                    break;
 5840                }
 5841            }
 5842
 5843            let buffer = &display_map.buffer_snapshot;
 5844            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5845            let edit_end;
 5846            let cursor_buffer_row;
 5847            if buffer.max_point().row >= rows.end.0 {
 5848                // If there's a line after the range, delete the \n from the end of the row range
 5849                // and position the cursor on the next line.
 5850                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5851                cursor_buffer_row = rows.end;
 5852            } else {
 5853                // If there isn't a line after the range, delete the \n from the line before the
 5854                // start of the row range and position the cursor there.
 5855                edit_start = edit_start.saturating_sub(1);
 5856                edit_end = buffer.len();
 5857                cursor_buffer_row = rows.start.previous_row();
 5858            }
 5859
 5860            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5861            *cursor.column_mut() =
 5862                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5863
 5864            new_cursors.push((
 5865                selection.id,
 5866                buffer.anchor_after(cursor.to_point(&display_map)),
 5867            ));
 5868            edit_ranges.push(edit_start..edit_end);
 5869        }
 5870
 5871        self.transact(cx, |this, cx| {
 5872            let buffer = this.buffer.update(cx, |buffer, cx| {
 5873                let empty_str: Arc<str> = Arc::default();
 5874                buffer.edit(
 5875                    edit_ranges
 5876                        .into_iter()
 5877                        .map(|range| (range, empty_str.clone())),
 5878                    None,
 5879                    cx,
 5880                );
 5881                buffer.snapshot(cx)
 5882            });
 5883            let new_selections = new_cursors
 5884                .into_iter()
 5885                .map(|(id, cursor)| {
 5886                    let cursor = cursor.to_point(&buffer);
 5887                    Selection {
 5888                        id,
 5889                        start: cursor,
 5890                        end: cursor,
 5891                        reversed: false,
 5892                        goal: SelectionGoal::None,
 5893                    }
 5894                })
 5895                .collect();
 5896
 5897            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5898                s.select(new_selections);
 5899            });
 5900        });
 5901    }
 5902
 5903    pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
 5904        if self.read_only(cx) {
 5905            return;
 5906        }
 5907        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5908        for selection in self.selections.all::<Point>(cx) {
 5909            let start = MultiBufferRow(selection.start.row);
 5910            // Treat single line selections as if they include the next line. Otherwise this action
 5911            // would do nothing for single line selections individual cursors.
 5912            let end = if selection.start.row == selection.end.row {
 5913                MultiBufferRow(selection.start.row + 1)
 5914            } else {
 5915                MultiBufferRow(selection.end.row)
 5916            };
 5917
 5918            if let Some(last_row_range) = row_ranges.last_mut() {
 5919                if start <= last_row_range.end {
 5920                    last_row_range.end = end;
 5921                    continue;
 5922                }
 5923            }
 5924            row_ranges.push(start..end);
 5925        }
 5926
 5927        let snapshot = self.buffer.read(cx).snapshot(cx);
 5928        let mut cursor_positions = Vec::new();
 5929        for row_range in &row_ranges {
 5930            let anchor = snapshot.anchor_before(Point::new(
 5931                row_range.end.previous_row().0,
 5932                snapshot.line_len(row_range.end.previous_row()),
 5933            ));
 5934            cursor_positions.push(anchor..anchor);
 5935        }
 5936
 5937        self.transact(cx, |this, cx| {
 5938            for row_range in row_ranges.into_iter().rev() {
 5939                for row in row_range.iter_rows().rev() {
 5940                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5941                    let next_line_row = row.next_row();
 5942                    let indent = snapshot.indent_size_for_line(next_line_row);
 5943                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5944
 5945                    let replace =
 5946                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 5947                            " "
 5948                        } else {
 5949                            ""
 5950                        };
 5951
 5952                    this.buffer.update(cx, |buffer, cx| {
 5953                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5954                    });
 5955                }
 5956            }
 5957
 5958            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5959                s.select_anchor_ranges(cursor_positions)
 5960            });
 5961        });
 5962    }
 5963
 5964    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5965        self.join_lines_impl(true, cx);
 5966    }
 5967
 5968    pub fn sort_lines_case_sensitive(
 5969        &mut self,
 5970        _: &SortLinesCaseSensitive,
 5971        cx: &mut ViewContext<Self>,
 5972    ) {
 5973        self.manipulate_lines(cx, |lines| lines.sort())
 5974    }
 5975
 5976    pub fn sort_lines_case_insensitive(
 5977        &mut self,
 5978        _: &SortLinesCaseInsensitive,
 5979        cx: &mut ViewContext<Self>,
 5980    ) {
 5981        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5982    }
 5983
 5984    pub fn unique_lines_case_insensitive(
 5985        &mut self,
 5986        _: &UniqueLinesCaseInsensitive,
 5987        cx: &mut ViewContext<Self>,
 5988    ) {
 5989        self.manipulate_lines(cx, |lines| {
 5990            let mut seen = HashSet::default();
 5991            lines.retain(|line| seen.insert(line.to_lowercase()));
 5992        })
 5993    }
 5994
 5995    pub fn unique_lines_case_sensitive(
 5996        &mut self,
 5997        _: &UniqueLinesCaseSensitive,
 5998        cx: &mut ViewContext<Self>,
 5999    ) {
 6000        self.manipulate_lines(cx, |lines| {
 6001            let mut seen = HashSet::default();
 6002            lines.retain(|line| seen.insert(*line));
 6003        })
 6004    }
 6005
 6006    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6007        let mut revert_changes = HashMap::default();
 6008        let snapshot = self.snapshot(cx);
 6009        for hunk in hunks_for_ranges(
 6010            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 6011            &snapshot,
 6012        ) {
 6013            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6014        }
 6015        if !revert_changes.is_empty() {
 6016            self.transact(cx, |editor, cx| {
 6017                editor.revert(revert_changes, cx);
 6018            });
 6019        }
 6020    }
 6021
 6022    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6023        let Some(project) = self.project.clone() else {
 6024            return;
 6025        };
 6026        self.reload(project, cx).detach_and_notify_err(cx);
 6027    }
 6028
 6029    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6030        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 6031        if !revert_changes.is_empty() {
 6032            self.transact(cx, |editor, cx| {
 6033                editor.revert(revert_changes, cx);
 6034            });
 6035        }
 6036    }
 6037
 6038    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 6039        let snapshot = self.buffer.read(cx).read(cx);
 6040        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 6041            drop(snapshot);
 6042            let mut revert_changes = HashMap::default();
 6043            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6044            if !revert_changes.is_empty() {
 6045                self.revert(revert_changes, cx)
 6046            }
 6047        }
 6048    }
 6049
 6050    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6051        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6052            let project_path = buffer.read(cx).project_path(cx)?;
 6053            let project = self.project.as_ref()?.read(cx);
 6054            let entry = project.entry_for_path(&project_path, cx)?;
 6055            let parent = match &entry.canonical_path {
 6056                Some(canonical_path) => canonical_path.to_path_buf(),
 6057                None => project.absolute_path(&project_path, cx)?,
 6058            }
 6059            .parent()?
 6060            .to_path_buf();
 6061            Some(parent)
 6062        }) {
 6063            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6064        }
 6065    }
 6066
 6067    fn gather_revert_changes(
 6068        &mut self,
 6069        selections: &[Selection<Point>],
 6070        cx: &mut ViewContext<Editor>,
 6071    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6072        let mut revert_changes = HashMap::default();
 6073        let snapshot = self.snapshot(cx);
 6074        for hunk in hunks_for_selections(&snapshot, selections) {
 6075            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6076        }
 6077        revert_changes
 6078    }
 6079
 6080    pub fn prepare_revert_change(
 6081        &mut self,
 6082        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6083        hunk: &MultiBufferDiffHunk,
 6084        cx: &AppContext,
 6085    ) -> Option<()> {
 6086        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6087        let buffer = buffer.read(cx);
 6088        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6089        let original_text = change_set
 6090            .read(cx)
 6091            .base_text
 6092            .as_ref()?
 6093            .read(cx)
 6094            .as_rope()
 6095            .slice(hunk.diff_base_byte_range.clone());
 6096        let buffer_snapshot = buffer.snapshot();
 6097        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6098        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6099            probe
 6100                .0
 6101                .start
 6102                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6103                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6104        }) {
 6105            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6106            Some(())
 6107        } else {
 6108            None
 6109        }
 6110    }
 6111
 6112    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6113        self.manipulate_lines(cx, |lines| lines.reverse())
 6114    }
 6115
 6116    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6117        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6118    }
 6119
 6120    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6121    where
 6122        Fn: FnMut(&mut Vec<&str>),
 6123    {
 6124        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6125        let buffer = self.buffer.read(cx).snapshot(cx);
 6126
 6127        let mut edits = Vec::new();
 6128
 6129        let selections = self.selections.all::<Point>(cx);
 6130        let mut selections = selections.iter().peekable();
 6131        let mut contiguous_row_selections = Vec::new();
 6132        let mut new_selections = Vec::new();
 6133        let mut added_lines = 0;
 6134        let mut removed_lines = 0;
 6135
 6136        while let Some(selection) = selections.next() {
 6137            let (start_row, end_row) = consume_contiguous_rows(
 6138                &mut contiguous_row_selections,
 6139                selection,
 6140                &display_map,
 6141                &mut selections,
 6142            );
 6143
 6144            let start_point = Point::new(start_row.0, 0);
 6145            let end_point = Point::new(
 6146                end_row.previous_row().0,
 6147                buffer.line_len(end_row.previous_row()),
 6148            );
 6149            let text = buffer
 6150                .text_for_range(start_point..end_point)
 6151                .collect::<String>();
 6152
 6153            let mut lines = text.split('\n').collect_vec();
 6154
 6155            let lines_before = lines.len();
 6156            callback(&mut lines);
 6157            let lines_after = lines.len();
 6158
 6159            edits.push((start_point..end_point, lines.join("\n")));
 6160
 6161            // Selections must change based on added and removed line count
 6162            let start_row =
 6163                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6164            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6165            new_selections.push(Selection {
 6166                id: selection.id,
 6167                start: start_row,
 6168                end: end_row,
 6169                goal: SelectionGoal::None,
 6170                reversed: selection.reversed,
 6171            });
 6172
 6173            if lines_after > lines_before {
 6174                added_lines += lines_after - lines_before;
 6175            } else if lines_before > lines_after {
 6176                removed_lines += lines_before - lines_after;
 6177            }
 6178        }
 6179
 6180        self.transact(cx, |this, cx| {
 6181            let buffer = this.buffer.update(cx, |buffer, cx| {
 6182                buffer.edit(edits, None, cx);
 6183                buffer.snapshot(cx)
 6184            });
 6185
 6186            // Recalculate offsets on newly edited buffer
 6187            let new_selections = new_selections
 6188                .iter()
 6189                .map(|s| {
 6190                    let start_point = Point::new(s.start.0, 0);
 6191                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6192                    Selection {
 6193                        id: s.id,
 6194                        start: buffer.point_to_offset(start_point),
 6195                        end: buffer.point_to_offset(end_point),
 6196                        goal: s.goal,
 6197                        reversed: s.reversed,
 6198                    }
 6199                })
 6200                .collect();
 6201
 6202            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6203                s.select(new_selections);
 6204            });
 6205
 6206            this.request_autoscroll(Autoscroll::fit(), cx);
 6207        });
 6208    }
 6209
 6210    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6211        self.manipulate_text(cx, |text| text.to_uppercase())
 6212    }
 6213
 6214    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6215        self.manipulate_text(cx, |text| text.to_lowercase())
 6216    }
 6217
 6218    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6219        self.manipulate_text(cx, |text| {
 6220            text.split('\n')
 6221                .map(|line| line.to_case(Case::Title))
 6222                .join("\n")
 6223        })
 6224    }
 6225
 6226    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6227        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6228    }
 6229
 6230    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6231        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6232    }
 6233
 6234    pub fn convert_to_upper_camel_case(
 6235        &mut self,
 6236        _: &ConvertToUpperCamelCase,
 6237        cx: &mut ViewContext<Self>,
 6238    ) {
 6239        self.manipulate_text(cx, |text| {
 6240            text.split('\n')
 6241                .map(|line| line.to_case(Case::UpperCamel))
 6242                .join("\n")
 6243        })
 6244    }
 6245
 6246    pub fn convert_to_lower_camel_case(
 6247        &mut self,
 6248        _: &ConvertToLowerCamelCase,
 6249        cx: &mut ViewContext<Self>,
 6250    ) {
 6251        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6252    }
 6253
 6254    pub fn convert_to_opposite_case(
 6255        &mut self,
 6256        _: &ConvertToOppositeCase,
 6257        cx: &mut ViewContext<Self>,
 6258    ) {
 6259        self.manipulate_text(cx, |text| {
 6260            text.chars()
 6261                .fold(String::with_capacity(text.len()), |mut t, c| {
 6262                    if c.is_uppercase() {
 6263                        t.extend(c.to_lowercase());
 6264                    } else {
 6265                        t.extend(c.to_uppercase());
 6266                    }
 6267                    t
 6268                })
 6269        })
 6270    }
 6271
 6272    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6273    where
 6274        Fn: FnMut(&str) -> String,
 6275    {
 6276        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6277        let buffer = self.buffer.read(cx).snapshot(cx);
 6278
 6279        let mut new_selections = Vec::new();
 6280        let mut edits = Vec::new();
 6281        let mut selection_adjustment = 0i32;
 6282
 6283        for selection in self.selections.all::<usize>(cx) {
 6284            let selection_is_empty = selection.is_empty();
 6285
 6286            let (start, end) = if selection_is_empty {
 6287                let word_range = movement::surrounding_word(
 6288                    &display_map,
 6289                    selection.start.to_display_point(&display_map),
 6290                );
 6291                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6292                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6293                (start, end)
 6294            } else {
 6295                (selection.start, selection.end)
 6296            };
 6297
 6298            let text = buffer.text_for_range(start..end).collect::<String>();
 6299            let old_length = text.len() as i32;
 6300            let text = callback(&text);
 6301
 6302            new_selections.push(Selection {
 6303                start: (start as i32 - selection_adjustment) as usize,
 6304                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6305                goal: SelectionGoal::None,
 6306                ..selection
 6307            });
 6308
 6309            selection_adjustment += old_length - text.len() as i32;
 6310
 6311            edits.push((start..end, text));
 6312        }
 6313
 6314        self.transact(cx, |this, cx| {
 6315            this.buffer.update(cx, |buffer, cx| {
 6316                buffer.edit(edits, None, cx);
 6317            });
 6318
 6319            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6320                s.select(new_selections);
 6321            });
 6322
 6323            this.request_autoscroll(Autoscroll::fit(), cx);
 6324        });
 6325    }
 6326
 6327    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6328        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6329        let buffer = &display_map.buffer_snapshot;
 6330        let selections = self.selections.all::<Point>(cx);
 6331
 6332        let mut edits = Vec::new();
 6333        let mut selections_iter = selections.iter().peekable();
 6334        while let Some(selection) = selections_iter.next() {
 6335            let mut rows = selection.spanned_rows(false, &display_map);
 6336            // duplicate line-wise
 6337            if whole_lines || selection.start == selection.end {
 6338                // Avoid duplicating the same lines twice.
 6339                while let Some(next_selection) = selections_iter.peek() {
 6340                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6341                    if next_rows.start < rows.end {
 6342                        rows.end = next_rows.end;
 6343                        selections_iter.next().unwrap();
 6344                    } else {
 6345                        break;
 6346                    }
 6347                }
 6348
 6349                // Copy the text from the selected row region and splice it either at the start
 6350                // or end of the region.
 6351                let start = Point::new(rows.start.0, 0);
 6352                let end = Point::new(
 6353                    rows.end.previous_row().0,
 6354                    buffer.line_len(rows.end.previous_row()),
 6355                );
 6356                let text = buffer
 6357                    .text_for_range(start..end)
 6358                    .chain(Some("\n"))
 6359                    .collect::<String>();
 6360                let insert_location = if upwards {
 6361                    Point::new(rows.end.0, 0)
 6362                } else {
 6363                    start
 6364                };
 6365                edits.push((insert_location..insert_location, text));
 6366            } else {
 6367                // duplicate character-wise
 6368                let start = selection.start;
 6369                let end = selection.end;
 6370                let text = buffer.text_for_range(start..end).collect::<String>();
 6371                edits.push((selection.end..selection.end, text));
 6372            }
 6373        }
 6374
 6375        self.transact(cx, |this, cx| {
 6376            this.buffer.update(cx, |buffer, cx| {
 6377                buffer.edit(edits, None, cx);
 6378            });
 6379
 6380            this.request_autoscroll(Autoscroll::fit(), cx);
 6381        });
 6382    }
 6383
 6384    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6385        self.duplicate(true, true, cx);
 6386    }
 6387
 6388    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6389        self.duplicate(false, true, cx);
 6390    }
 6391
 6392    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6393        self.duplicate(false, false, cx);
 6394    }
 6395
 6396    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6397        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6398        let buffer = self.buffer.read(cx).snapshot(cx);
 6399
 6400        let mut edits = Vec::new();
 6401        let mut unfold_ranges = Vec::new();
 6402        let mut refold_creases = Vec::new();
 6403
 6404        let selections = self.selections.all::<Point>(cx);
 6405        let mut selections = selections.iter().peekable();
 6406        let mut contiguous_row_selections = Vec::new();
 6407        let mut new_selections = Vec::new();
 6408
 6409        while let Some(selection) = selections.next() {
 6410            // Find all the selections that span a contiguous row range
 6411            let (start_row, end_row) = consume_contiguous_rows(
 6412                &mut contiguous_row_selections,
 6413                selection,
 6414                &display_map,
 6415                &mut selections,
 6416            );
 6417
 6418            // Move the text spanned by the row range to be before the line preceding the row range
 6419            if start_row.0 > 0 {
 6420                let range_to_move = Point::new(
 6421                    start_row.previous_row().0,
 6422                    buffer.line_len(start_row.previous_row()),
 6423                )
 6424                    ..Point::new(
 6425                        end_row.previous_row().0,
 6426                        buffer.line_len(end_row.previous_row()),
 6427                    );
 6428                let insertion_point = display_map
 6429                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6430                    .0;
 6431
 6432                // Don't move lines across excerpts
 6433                if buffer
 6434                    .excerpt_boundaries_in_range((
 6435                        Bound::Excluded(insertion_point),
 6436                        Bound::Included(range_to_move.end),
 6437                    ))
 6438                    .next()
 6439                    .is_none()
 6440                {
 6441                    let text = buffer
 6442                        .text_for_range(range_to_move.clone())
 6443                        .flat_map(|s| s.chars())
 6444                        .skip(1)
 6445                        .chain(['\n'])
 6446                        .collect::<String>();
 6447
 6448                    edits.push((
 6449                        buffer.anchor_after(range_to_move.start)
 6450                            ..buffer.anchor_before(range_to_move.end),
 6451                        String::new(),
 6452                    ));
 6453                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6454                    edits.push((insertion_anchor..insertion_anchor, text));
 6455
 6456                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6457
 6458                    // Move selections up
 6459                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6460                        |mut selection| {
 6461                            selection.start.row -= row_delta;
 6462                            selection.end.row -= row_delta;
 6463                            selection
 6464                        },
 6465                    ));
 6466
 6467                    // Move folds up
 6468                    unfold_ranges.push(range_to_move.clone());
 6469                    for fold in display_map.folds_in_range(
 6470                        buffer.anchor_before(range_to_move.start)
 6471                            ..buffer.anchor_after(range_to_move.end),
 6472                    ) {
 6473                        let mut start = fold.range.start.to_point(&buffer);
 6474                        let mut end = fold.range.end.to_point(&buffer);
 6475                        start.row -= row_delta;
 6476                        end.row -= row_delta;
 6477                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6478                    }
 6479                }
 6480            }
 6481
 6482            // If we didn't move line(s), preserve the existing selections
 6483            new_selections.append(&mut contiguous_row_selections);
 6484        }
 6485
 6486        self.transact(cx, |this, cx| {
 6487            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6488            this.buffer.update(cx, |buffer, cx| {
 6489                for (range, text) in edits {
 6490                    buffer.edit([(range, text)], None, cx);
 6491                }
 6492            });
 6493            this.fold_creases(refold_creases, true, cx);
 6494            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6495                s.select(new_selections);
 6496            })
 6497        });
 6498    }
 6499
 6500    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6501        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6502        let buffer = self.buffer.read(cx).snapshot(cx);
 6503
 6504        let mut edits = Vec::new();
 6505        let mut unfold_ranges = Vec::new();
 6506        let mut refold_creases = Vec::new();
 6507
 6508        let selections = self.selections.all::<Point>(cx);
 6509        let mut selections = selections.iter().peekable();
 6510        let mut contiguous_row_selections = Vec::new();
 6511        let mut new_selections = Vec::new();
 6512
 6513        while let Some(selection) = selections.next() {
 6514            // Find all the selections that span a contiguous row range
 6515            let (start_row, end_row) = consume_contiguous_rows(
 6516                &mut contiguous_row_selections,
 6517                selection,
 6518                &display_map,
 6519                &mut selections,
 6520            );
 6521
 6522            // Move the text spanned by the row range to be after the last line of the row range
 6523            if end_row.0 <= buffer.max_point().row {
 6524                let range_to_move =
 6525                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6526                let insertion_point = display_map
 6527                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6528                    .0;
 6529
 6530                // Don't move lines across excerpt boundaries
 6531                if buffer
 6532                    .excerpt_boundaries_in_range((
 6533                        Bound::Excluded(range_to_move.start),
 6534                        Bound::Included(insertion_point),
 6535                    ))
 6536                    .next()
 6537                    .is_none()
 6538                {
 6539                    let mut text = String::from("\n");
 6540                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6541                    text.pop(); // Drop trailing newline
 6542                    edits.push((
 6543                        buffer.anchor_after(range_to_move.start)
 6544                            ..buffer.anchor_before(range_to_move.end),
 6545                        String::new(),
 6546                    ));
 6547                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6548                    edits.push((insertion_anchor..insertion_anchor, text));
 6549
 6550                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6551
 6552                    // Move selections down
 6553                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6554                        |mut selection| {
 6555                            selection.start.row += row_delta;
 6556                            selection.end.row += row_delta;
 6557                            selection
 6558                        },
 6559                    ));
 6560
 6561                    // Move folds down
 6562                    unfold_ranges.push(range_to_move.clone());
 6563                    for fold in display_map.folds_in_range(
 6564                        buffer.anchor_before(range_to_move.start)
 6565                            ..buffer.anchor_after(range_to_move.end),
 6566                    ) {
 6567                        let mut start = fold.range.start.to_point(&buffer);
 6568                        let mut end = fold.range.end.to_point(&buffer);
 6569                        start.row += row_delta;
 6570                        end.row += row_delta;
 6571                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6572                    }
 6573                }
 6574            }
 6575
 6576            // If we didn't move line(s), preserve the existing selections
 6577            new_selections.append(&mut contiguous_row_selections);
 6578        }
 6579
 6580        self.transact(cx, |this, cx| {
 6581            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6582            this.buffer.update(cx, |buffer, cx| {
 6583                for (range, text) in edits {
 6584                    buffer.edit([(range, text)], None, cx);
 6585                }
 6586            });
 6587            this.fold_creases(refold_creases, true, cx);
 6588            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6589        });
 6590    }
 6591
 6592    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6593        let text_layout_details = &self.text_layout_details(cx);
 6594        self.transact(cx, |this, cx| {
 6595            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6596                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6597                let line_mode = s.line_mode;
 6598                s.move_with(|display_map, selection| {
 6599                    if !selection.is_empty() || line_mode {
 6600                        return;
 6601                    }
 6602
 6603                    let mut head = selection.head();
 6604                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6605                    if head.column() == display_map.line_len(head.row()) {
 6606                        transpose_offset = display_map
 6607                            .buffer_snapshot
 6608                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6609                    }
 6610
 6611                    if transpose_offset == 0 {
 6612                        return;
 6613                    }
 6614
 6615                    *head.column_mut() += 1;
 6616                    head = display_map.clip_point(head, Bias::Right);
 6617                    let goal = SelectionGoal::HorizontalPosition(
 6618                        display_map
 6619                            .x_for_display_point(head, text_layout_details)
 6620                            .into(),
 6621                    );
 6622                    selection.collapse_to(head, goal);
 6623
 6624                    let transpose_start = display_map
 6625                        .buffer_snapshot
 6626                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6627                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6628                        let transpose_end = display_map
 6629                            .buffer_snapshot
 6630                            .clip_offset(transpose_offset + 1, Bias::Right);
 6631                        if let Some(ch) =
 6632                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6633                        {
 6634                            edits.push((transpose_start..transpose_offset, String::new()));
 6635                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6636                        }
 6637                    }
 6638                });
 6639                edits
 6640            });
 6641            this.buffer
 6642                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6643            let selections = this.selections.all::<usize>(cx);
 6644            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6645                s.select(selections);
 6646            });
 6647        });
 6648    }
 6649
 6650    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6651        self.rewrap_impl(IsVimMode::No, cx)
 6652    }
 6653
 6654    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6655        let buffer = self.buffer.read(cx).snapshot(cx);
 6656        let selections = self.selections.all::<Point>(cx);
 6657        let mut selections = selections.iter().peekable();
 6658
 6659        let mut edits = Vec::new();
 6660        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6661
 6662        while let Some(selection) = selections.next() {
 6663            let mut start_row = selection.start.row;
 6664            let mut end_row = selection.end.row;
 6665
 6666            // Skip selections that overlap with a range that has already been rewrapped.
 6667            let selection_range = start_row..end_row;
 6668            if rewrapped_row_ranges
 6669                .iter()
 6670                .any(|range| range.overlaps(&selection_range))
 6671            {
 6672                continue;
 6673            }
 6674
 6675            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6676
 6677            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6678                match language_scope.language_name().0.as_ref() {
 6679                    "Markdown" | "Plain Text" => {
 6680                        should_rewrap = true;
 6681                    }
 6682                    _ => {}
 6683                }
 6684            }
 6685
 6686            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6687
 6688            // Since not all lines in the selection may be at the same indent
 6689            // level, choose the indent size that is the most common between all
 6690            // of the lines.
 6691            //
 6692            // If there is a tie, we use the deepest indent.
 6693            let (indent_size, indent_end) = {
 6694                let mut indent_size_occurrences = HashMap::default();
 6695                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6696
 6697                for row in start_row..=end_row {
 6698                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6699                    rows_by_indent_size.entry(indent).or_default().push(row);
 6700                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6701                }
 6702
 6703                let indent_size = indent_size_occurrences
 6704                    .into_iter()
 6705                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6706                    .map(|(indent, _)| indent)
 6707                    .unwrap_or_default();
 6708                let row = rows_by_indent_size[&indent_size][0];
 6709                let indent_end = Point::new(row, indent_size.len);
 6710
 6711                (indent_size, indent_end)
 6712            };
 6713
 6714            let mut line_prefix = indent_size.chars().collect::<String>();
 6715
 6716            if let Some(comment_prefix) =
 6717                buffer
 6718                    .language_scope_at(selection.head())
 6719                    .and_then(|language| {
 6720                        language
 6721                            .line_comment_prefixes()
 6722                            .iter()
 6723                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6724                            .cloned()
 6725                    })
 6726            {
 6727                line_prefix.push_str(&comment_prefix);
 6728                should_rewrap = true;
 6729            }
 6730
 6731            if !should_rewrap {
 6732                continue;
 6733            }
 6734
 6735            if selection.is_empty() {
 6736                'expand_upwards: while start_row > 0 {
 6737                    let prev_row = start_row - 1;
 6738                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6739                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6740                    {
 6741                        start_row = prev_row;
 6742                    } else {
 6743                        break 'expand_upwards;
 6744                    }
 6745                }
 6746
 6747                'expand_downwards: while end_row < buffer.max_point().row {
 6748                    let next_row = end_row + 1;
 6749                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6750                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6751                    {
 6752                        end_row = next_row;
 6753                    } else {
 6754                        break 'expand_downwards;
 6755                    }
 6756                }
 6757            }
 6758
 6759            let start = Point::new(start_row, 0);
 6760            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6761            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6762            let Some(lines_without_prefixes) = selection_text
 6763                .lines()
 6764                .map(|line| {
 6765                    line.strip_prefix(&line_prefix)
 6766                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6767                        .ok_or_else(|| {
 6768                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6769                        })
 6770                })
 6771                .collect::<Result<Vec<_>, _>>()
 6772                .log_err()
 6773            else {
 6774                continue;
 6775            };
 6776
 6777            let wrap_column = buffer
 6778                .settings_at(Point::new(start_row, 0), cx)
 6779                .preferred_line_length as usize;
 6780            let wrapped_text = wrap_with_prefix(
 6781                line_prefix,
 6782                lines_without_prefixes.join(" "),
 6783                wrap_column,
 6784                tab_size,
 6785            );
 6786
 6787            // TODO: should always use char-based diff while still supporting cursor behavior that
 6788            // matches vim.
 6789            let diff = match is_vim_mode {
 6790                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6791                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6792            };
 6793            let mut offset = start.to_offset(&buffer);
 6794            let mut moved_since_edit = true;
 6795
 6796            for change in diff.iter_all_changes() {
 6797                let value = change.value();
 6798                match change.tag() {
 6799                    ChangeTag::Equal => {
 6800                        offset += value.len();
 6801                        moved_since_edit = true;
 6802                    }
 6803                    ChangeTag::Delete => {
 6804                        let start = buffer.anchor_after(offset);
 6805                        let end = buffer.anchor_before(offset + value.len());
 6806
 6807                        if moved_since_edit {
 6808                            edits.push((start..end, String::new()));
 6809                        } else {
 6810                            edits.last_mut().unwrap().0.end = end;
 6811                        }
 6812
 6813                        offset += value.len();
 6814                        moved_since_edit = false;
 6815                    }
 6816                    ChangeTag::Insert => {
 6817                        if moved_since_edit {
 6818                            let anchor = buffer.anchor_after(offset);
 6819                            edits.push((anchor..anchor, value.to_string()));
 6820                        } else {
 6821                            edits.last_mut().unwrap().1.push_str(value);
 6822                        }
 6823
 6824                        moved_since_edit = false;
 6825                    }
 6826                }
 6827            }
 6828
 6829            rewrapped_row_ranges.push(start_row..=end_row);
 6830        }
 6831
 6832        self.buffer
 6833            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6834    }
 6835
 6836    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6837        let mut text = String::new();
 6838        let buffer = self.buffer.read(cx).snapshot(cx);
 6839        let mut selections = self.selections.all::<Point>(cx);
 6840        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6841        {
 6842            let max_point = buffer.max_point();
 6843            let mut is_first = true;
 6844            for selection in &mut selections {
 6845                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6846                if is_entire_line {
 6847                    selection.start = Point::new(selection.start.row, 0);
 6848                    if !selection.is_empty() && selection.end.column == 0 {
 6849                        selection.end = cmp::min(max_point, selection.end);
 6850                    } else {
 6851                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6852                    }
 6853                    selection.goal = SelectionGoal::None;
 6854                }
 6855                if is_first {
 6856                    is_first = false;
 6857                } else {
 6858                    text += "\n";
 6859                }
 6860                let mut len = 0;
 6861                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6862                    text.push_str(chunk);
 6863                    len += chunk.len();
 6864                }
 6865                clipboard_selections.push(ClipboardSelection {
 6866                    len,
 6867                    is_entire_line,
 6868                    first_line_indent: buffer
 6869                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6870                        .len,
 6871                });
 6872            }
 6873        }
 6874
 6875        self.transact(cx, |this, cx| {
 6876            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6877                s.select(selections);
 6878            });
 6879            this.insert("", cx);
 6880        });
 6881        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6882    }
 6883
 6884    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6885        let item = self.cut_common(cx);
 6886        cx.write_to_clipboard(item);
 6887    }
 6888
 6889    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6890        self.change_selections(None, cx, |s| {
 6891            s.move_with(|snapshot, sel| {
 6892                if sel.is_empty() {
 6893                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6894                }
 6895            });
 6896        });
 6897        let item = self.cut_common(cx);
 6898        cx.set_global(KillRing(item))
 6899    }
 6900
 6901    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6902        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6903            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6904                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6905            } else {
 6906                return;
 6907            }
 6908        } else {
 6909            return;
 6910        };
 6911        self.do_paste(&text, metadata, false, cx);
 6912    }
 6913
 6914    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6915        let selections = self.selections.all::<Point>(cx);
 6916        let buffer = self.buffer.read(cx).read(cx);
 6917        let mut text = String::new();
 6918
 6919        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6920        {
 6921            let max_point = buffer.max_point();
 6922            let mut is_first = true;
 6923            for selection in selections.iter() {
 6924                let mut start = selection.start;
 6925                let mut end = selection.end;
 6926                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6927                if is_entire_line {
 6928                    start = Point::new(start.row, 0);
 6929                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6930                }
 6931                if is_first {
 6932                    is_first = false;
 6933                } else {
 6934                    text += "\n";
 6935                }
 6936                let mut len = 0;
 6937                for chunk in buffer.text_for_range(start..end) {
 6938                    text.push_str(chunk);
 6939                    len += chunk.len();
 6940                }
 6941                clipboard_selections.push(ClipboardSelection {
 6942                    len,
 6943                    is_entire_line,
 6944                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6945                });
 6946            }
 6947        }
 6948
 6949        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6950            text,
 6951            clipboard_selections,
 6952        ));
 6953    }
 6954
 6955    pub fn do_paste(
 6956        &mut self,
 6957        text: &String,
 6958        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6959        handle_entire_lines: bool,
 6960        cx: &mut ViewContext<Self>,
 6961    ) {
 6962        if self.read_only(cx) {
 6963            return;
 6964        }
 6965
 6966        let clipboard_text = Cow::Borrowed(text);
 6967
 6968        self.transact(cx, |this, cx| {
 6969            if let Some(mut clipboard_selections) = clipboard_selections {
 6970                let old_selections = this.selections.all::<usize>(cx);
 6971                let all_selections_were_entire_line =
 6972                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6973                let first_selection_indent_column =
 6974                    clipboard_selections.first().map(|s| s.first_line_indent);
 6975                if clipboard_selections.len() != old_selections.len() {
 6976                    clipboard_selections.drain(..);
 6977                }
 6978                let cursor_offset = this.selections.last::<usize>(cx).head();
 6979                let mut auto_indent_on_paste = true;
 6980
 6981                this.buffer.update(cx, |buffer, cx| {
 6982                    let snapshot = buffer.read(cx);
 6983                    auto_indent_on_paste =
 6984                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6985
 6986                    let mut start_offset = 0;
 6987                    let mut edits = Vec::new();
 6988                    let mut original_indent_columns = Vec::new();
 6989                    for (ix, selection) in old_selections.iter().enumerate() {
 6990                        let to_insert;
 6991                        let entire_line;
 6992                        let original_indent_column;
 6993                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6994                            let end_offset = start_offset + clipboard_selection.len;
 6995                            to_insert = &clipboard_text[start_offset..end_offset];
 6996                            entire_line = clipboard_selection.is_entire_line;
 6997                            start_offset = end_offset + 1;
 6998                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6999                        } else {
 7000                            to_insert = clipboard_text.as_str();
 7001                            entire_line = all_selections_were_entire_line;
 7002                            original_indent_column = first_selection_indent_column
 7003                        }
 7004
 7005                        // If the corresponding selection was empty when this slice of the
 7006                        // clipboard text was written, then the entire line containing the
 7007                        // selection was copied. If this selection is also currently empty,
 7008                        // then paste the line before the current line of the buffer.
 7009                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7010                            let column = selection.start.to_point(&snapshot).column as usize;
 7011                            let line_start = selection.start - column;
 7012                            line_start..line_start
 7013                        } else {
 7014                            selection.range()
 7015                        };
 7016
 7017                        edits.push((range, to_insert));
 7018                        original_indent_columns.extend(original_indent_column);
 7019                    }
 7020                    drop(snapshot);
 7021
 7022                    buffer.edit(
 7023                        edits,
 7024                        if auto_indent_on_paste {
 7025                            Some(AutoindentMode::Block {
 7026                                original_indent_columns,
 7027                            })
 7028                        } else {
 7029                            None
 7030                        },
 7031                        cx,
 7032                    );
 7033                });
 7034
 7035                let selections = this.selections.all::<usize>(cx);
 7036                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7037            } else {
 7038                this.insert(&clipboard_text, cx);
 7039            }
 7040        });
 7041    }
 7042
 7043    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7044        if let Some(item) = cx.read_from_clipboard() {
 7045            let entries = item.entries();
 7046
 7047            match entries.first() {
 7048                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7049                // of all the pasted entries.
 7050                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7051                    .do_paste(
 7052                        clipboard_string.text(),
 7053                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7054                        true,
 7055                        cx,
 7056                    ),
 7057                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7058            }
 7059        }
 7060    }
 7061
 7062    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7063        if self.read_only(cx) {
 7064            return;
 7065        }
 7066
 7067        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7068            if let Some((selections, _)) =
 7069                self.selection_history.transaction(transaction_id).cloned()
 7070            {
 7071                self.change_selections(None, cx, |s| {
 7072                    s.select_anchors(selections.to_vec());
 7073                });
 7074            }
 7075            self.request_autoscroll(Autoscroll::fit(), cx);
 7076            self.unmark_text(cx);
 7077            self.refresh_inline_completion(true, false, cx);
 7078            cx.emit(EditorEvent::Edited { transaction_id });
 7079            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7080        }
 7081    }
 7082
 7083    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7084        if self.read_only(cx) {
 7085            return;
 7086        }
 7087
 7088        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7089            if let Some((_, Some(selections))) =
 7090                self.selection_history.transaction(transaction_id).cloned()
 7091            {
 7092                self.change_selections(None, cx, |s| {
 7093                    s.select_anchors(selections.to_vec());
 7094                });
 7095            }
 7096            self.request_autoscroll(Autoscroll::fit(), cx);
 7097            self.unmark_text(cx);
 7098            self.refresh_inline_completion(true, false, cx);
 7099            cx.emit(EditorEvent::Edited { transaction_id });
 7100        }
 7101    }
 7102
 7103    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7104        self.buffer
 7105            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7106    }
 7107
 7108    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7109        self.buffer
 7110            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7111    }
 7112
 7113    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7114        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7115            let line_mode = s.line_mode;
 7116            s.move_with(|map, selection| {
 7117                let cursor = if selection.is_empty() && !line_mode {
 7118                    movement::left(map, selection.start)
 7119                } else {
 7120                    selection.start
 7121                };
 7122                selection.collapse_to(cursor, SelectionGoal::None);
 7123            });
 7124        })
 7125    }
 7126
 7127    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7128        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7129            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7130        })
 7131    }
 7132
 7133    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7134        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7135            let line_mode = s.line_mode;
 7136            s.move_with(|map, selection| {
 7137                let cursor = if selection.is_empty() && !line_mode {
 7138                    movement::right(map, selection.end)
 7139                } else {
 7140                    selection.end
 7141                };
 7142                selection.collapse_to(cursor, SelectionGoal::None)
 7143            });
 7144        })
 7145    }
 7146
 7147    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7148        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7149            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7150        })
 7151    }
 7152
 7153    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7154        if self.take_rename(true, cx).is_some() {
 7155            return;
 7156        }
 7157
 7158        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7159            cx.propagate();
 7160            return;
 7161        }
 7162
 7163        let text_layout_details = &self.text_layout_details(cx);
 7164        let selection_count = self.selections.count();
 7165        let first_selection = self.selections.first_anchor();
 7166
 7167        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7168            let line_mode = s.line_mode;
 7169            s.move_with(|map, selection| {
 7170                if !selection.is_empty() && !line_mode {
 7171                    selection.goal = SelectionGoal::None;
 7172                }
 7173                let (cursor, goal) = movement::up(
 7174                    map,
 7175                    selection.start,
 7176                    selection.goal,
 7177                    false,
 7178                    text_layout_details,
 7179                );
 7180                selection.collapse_to(cursor, goal);
 7181            });
 7182        });
 7183
 7184        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7185        {
 7186            cx.propagate();
 7187        }
 7188    }
 7189
 7190    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7191        if self.take_rename(true, cx).is_some() {
 7192            return;
 7193        }
 7194
 7195        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7196            cx.propagate();
 7197            return;
 7198        }
 7199
 7200        let text_layout_details = &self.text_layout_details(cx);
 7201
 7202        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7203            let line_mode = s.line_mode;
 7204            s.move_with(|map, selection| {
 7205                if !selection.is_empty() && !line_mode {
 7206                    selection.goal = SelectionGoal::None;
 7207                }
 7208                let (cursor, goal) = movement::up_by_rows(
 7209                    map,
 7210                    selection.start,
 7211                    action.lines,
 7212                    selection.goal,
 7213                    false,
 7214                    text_layout_details,
 7215                );
 7216                selection.collapse_to(cursor, goal);
 7217            });
 7218        })
 7219    }
 7220
 7221    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7222        if self.take_rename(true, cx).is_some() {
 7223            return;
 7224        }
 7225
 7226        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7227            cx.propagate();
 7228            return;
 7229        }
 7230
 7231        let text_layout_details = &self.text_layout_details(cx);
 7232
 7233        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7234            let line_mode = s.line_mode;
 7235            s.move_with(|map, selection| {
 7236                if !selection.is_empty() && !line_mode {
 7237                    selection.goal = SelectionGoal::None;
 7238                }
 7239                let (cursor, goal) = movement::down_by_rows(
 7240                    map,
 7241                    selection.start,
 7242                    action.lines,
 7243                    selection.goal,
 7244                    false,
 7245                    text_layout_details,
 7246                );
 7247                selection.collapse_to(cursor, goal);
 7248            });
 7249        })
 7250    }
 7251
 7252    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7253        let text_layout_details = &self.text_layout_details(cx);
 7254        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7255            s.move_heads_with(|map, head, goal| {
 7256                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7257            })
 7258        })
 7259    }
 7260
 7261    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7262        let text_layout_details = &self.text_layout_details(cx);
 7263        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7264            s.move_heads_with(|map, head, goal| {
 7265                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7266            })
 7267        })
 7268    }
 7269
 7270    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7271        let Some(row_count) = self.visible_row_count() else {
 7272            return;
 7273        };
 7274
 7275        let text_layout_details = &self.text_layout_details(cx);
 7276
 7277        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7278            s.move_heads_with(|map, head, goal| {
 7279                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7280            })
 7281        })
 7282    }
 7283
 7284    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7285        if self.take_rename(true, cx).is_some() {
 7286            return;
 7287        }
 7288
 7289        if self
 7290            .context_menu
 7291            .borrow_mut()
 7292            .as_mut()
 7293            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7294            .unwrap_or(false)
 7295        {
 7296            return;
 7297        }
 7298
 7299        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7300            cx.propagate();
 7301            return;
 7302        }
 7303
 7304        let Some(row_count) = self.visible_row_count() else {
 7305            return;
 7306        };
 7307
 7308        let autoscroll = if action.center_cursor {
 7309            Autoscroll::center()
 7310        } else {
 7311            Autoscroll::fit()
 7312        };
 7313
 7314        let text_layout_details = &self.text_layout_details(cx);
 7315
 7316        self.change_selections(Some(autoscroll), cx, |s| {
 7317            let line_mode = s.line_mode;
 7318            s.move_with(|map, selection| {
 7319                if !selection.is_empty() && !line_mode {
 7320                    selection.goal = SelectionGoal::None;
 7321                }
 7322                let (cursor, goal) = movement::up_by_rows(
 7323                    map,
 7324                    selection.end,
 7325                    row_count,
 7326                    selection.goal,
 7327                    false,
 7328                    text_layout_details,
 7329                );
 7330                selection.collapse_to(cursor, goal);
 7331            });
 7332        });
 7333    }
 7334
 7335    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7336        let text_layout_details = &self.text_layout_details(cx);
 7337        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7338            s.move_heads_with(|map, head, goal| {
 7339                movement::up(map, head, goal, false, text_layout_details)
 7340            })
 7341        })
 7342    }
 7343
 7344    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7345        self.take_rename(true, cx);
 7346
 7347        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7348            cx.propagate();
 7349            return;
 7350        }
 7351
 7352        let text_layout_details = &self.text_layout_details(cx);
 7353        let selection_count = self.selections.count();
 7354        let first_selection = self.selections.first_anchor();
 7355
 7356        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7357            let line_mode = s.line_mode;
 7358            s.move_with(|map, selection| {
 7359                if !selection.is_empty() && !line_mode {
 7360                    selection.goal = SelectionGoal::None;
 7361                }
 7362                let (cursor, goal) = movement::down(
 7363                    map,
 7364                    selection.end,
 7365                    selection.goal,
 7366                    false,
 7367                    text_layout_details,
 7368                );
 7369                selection.collapse_to(cursor, goal);
 7370            });
 7371        });
 7372
 7373        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7374        {
 7375            cx.propagate();
 7376        }
 7377    }
 7378
 7379    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7380        let Some(row_count) = self.visible_row_count() else {
 7381            return;
 7382        };
 7383
 7384        let text_layout_details = &self.text_layout_details(cx);
 7385
 7386        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7387            s.move_heads_with(|map, head, goal| {
 7388                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7389            })
 7390        })
 7391    }
 7392
 7393    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7394        if self.take_rename(true, cx).is_some() {
 7395            return;
 7396        }
 7397
 7398        if self
 7399            .context_menu
 7400            .borrow_mut()
 7401            .as_mut()
 7402            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7403            .unwrap_or(false)
 7404        {
 7405            return;
 7406        }
 7407
 7408        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7409            cx.propagate();
 7410            return;
 7411        }
 7412
 7413        let Some(row_count) = self.visible_row_count() else {
 7414            return;
 7415        };
 7416
 7417        let autoscroll = if action.center_cursor {
 7418            Autoscroll::center()
 7419        } else {
 7420            Autoscroll::fit()
 7421        };
 7422
 7423        let text_layout_details = &self.text_layout_details(cx);
 7424        self.change_selections(Some(autoscroll), cx, |s| {
 7425            let line_mode = s.line_mode;
 7426            s.move_with(|map, selection| {
 7427                if !selection.is_empty() && !line_mode {
 7428                    selection.goal = SelectionGoal::None;
 7429                }
 7430                let (cursor, goal) = movement::down_by_rows(
 7431                    map,
 7432                    selection.end,
 7433                    row_count,
 7434                    selection.goal,
 7435                    false,
 7436                    text_layout_details,
 7437                );
 7438                selection.collapse_to(cursor, goal);
 7439            });
 7440        });
 7441    }
 7442
 7443    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7444        let text_layout_details = &self.text_layout_details(cx);
 7445        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7446            s.move_heads_with(|map, head, goal| {
 7447                movement::down(map, head, goal, false, text_layout_details)
 7448            })
 7449        });
 7450    }
 7451
 7452    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7453        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7454            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7455        }
 7456    }
 7457
 7458    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7459        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7460            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7461        }
 7462    }
 7463
 7464    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7465        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7466            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7467        }
 7468    }
 7469
 7470    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7471        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7472            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7473        }
 7474    }
 7475
 7476    pub fn move_to_previous_word_start(
 7477        &mut self,
 7478        _: &MoveToPreviousWordStart,
 7479        cx: &mut ViewContext<Self>,
 7480    ) {
 7481        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7482            s.move_cursors_with(|map, head, _| {
 7483                (
 7484                    movement::previous_word_start(map, head),
 7485                    SelectionGoal::None,
 7486                )
 7487            });
 7488        })
 7489    }
 7490
 7491    pub fn move_to_previous_subword_start(
 7492        &mut self,
 7493        _: &MoveToPreviousSubwordStart,
 7494        cx: &mut ViewContext<Self>,
 7495    ) {
 7496        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7497            s.move_cursors_with(|map, head, _| {
 7498                (
 7499                    movement::previous_subword_start(map, head),
 7500                    SelectionGoal::None,
 7501                )
 7502            });
 7503        })
 7504    }
 7505
 7506    pub fn select_to_previous_word_start(
 7507        &mut self,
 7508        _: &SelectToPreviousWordStart,
 7509        cx: &mut ViewContext<Self>,
 7510    ) {
 7511        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7512            s.move_heads_with(|map, head, _| {
 7513                (
 7514                    movement::previous_word_start(map, head),
 7515                    SelectionGoal::None,
 7516                )
 7517            });
 7518        })
 7519    }
 7520
 7521    pub fn select_to_previous_subword_start(
 7522        &mut self,
 7523        _: &SelectToPreviousSubwordStart,
 7524        cx: &mut ViewContext<Self>,
 7525    ) {
 7526        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7527            s.move_heads_with(|map, head, _| {
 7528                (
 7529                    movement::previous_subword_start(map, head),
 7530                    SelectionGoal::None,
 7531                )
 7532            });
 7533        })
 7534    }
 7535
 7536    pub fn delete_to_previous_word_start(
 7537        &mut self,
 7538        action: &DeleteToPreviousWordStart,
 7539        cx: &mut ViewContext<Self>,
 7540    ) {
 7541        self.transact(cx, |this, cx| {
 7542            this.select_autoclose_pair(cx);
 7543            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7544                let line_mode = s.line_mode;
 7545                s.move_with(|map, selection| {
 7546                    if selection.is_empty() && !line_mode {
 7547                        let cursor = if action.ignore_newlines {
 7548                            movement::previous_word_start(map, selection.head())
 7549                        } else {
 7550                            movement::previous_word_start_or_newline(map, selection.head())
 7551                        };
 7552                        selection.set_head(cursor, SelectionGoal::None);
 7553                    }
 7554                });
 7555            });
 7556            this.insert("", cx);
 7557        });
 7558    }
 7559
 7560    pub fn delete_to_previous_subword_start(
 7561        &mut self,
 7562        _: &DeleteToPreviousSubwordStart,
 7563        cx: &mut ViewContext<Self>,
 7564    ) {
 7565        self.transact(cx, |this, cx| {
 7566            this.select_autoclose_pair(cx);
 7567            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7568                let line_mode = s.line_mode;
 7569                s.move_with(|map, selection| {
 7570                    if selection.is_empty() && !line_mode {
 7571                        let cursor = movement::previous_subword_start(map, selection.head());
 7572                        selection.set_head(cursor, SelectionGoal::None);
 7573                    }
 7574                });
 7575            });
 7576            this.insert("", cx);
 7577        });
 7578    }
 7579
 7580    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7581        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7582            s.move_cursors_with(|map, head, _| {
 7583                (movement::next_word_end(map, head), SelectionGoal::None)
 7584            });
 7585        })
 7586    }
 7587
 7588    pub fn move_to_next_subword_end(
 7589        &mut self,
 7590        _: &MoveToNextSubwordEnd,
 7591        cx: &mut ViewContext<Self>,
 7592    ) {
 7593        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7594            s.move_cursors_with(|map, head, _| {
 7595                (movement::next_subword_end(map, head), SelectionGoal::None)
 7596            });
 7597        })
 7598    }
 7599
 7600    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7601        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7602            s.move_heads_with(|map, head, _| {
 7603                (movement::next_word_end(map, head), SelectionGoal::None)
 7604            });
 7605        })
 7606    }
 7607
 7608    pub fn select_to_next_subword_end(
 7609        &mut self,
 7610        _: &SelectToNextSubwordEnd,
 7611        cx: &mut ViewContext<Self>,
 7612    ) {
 7613        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7614            s.move_heads_with(|map, head, _| {
 7615                (movement::next_subword_end(map, head), SelectionGoal::None)
 7616            });
 7617        })
 7618    }
 7619
 7620    pub fn delete_to_next_word_end(
 7621        &mut self,
 7622        action: &DeleteToNextWordEnd,
 7623        cx: &mut ViewContext<Self>,
 7624    ) {
 7625        self.transact(cx, |this, cx| {
 7626            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7627                let line_mode = s.line_mode;
 7628                s.move_with(|map, selection| {
 7629                    if selection.is_empty() && !line_mode {
 7630                        let cursor = if action.ignore_newlines {
 7631                            movement::next_word_end(map, selection.head())
 7632                        } else {
 7633                            movement::next_word_end_or_newline(map, selection.head())
 7634                        };
 7635                        selection.set_head(cursor, SelectionGoal::None);
 7636                    }
 7637                });
 7638            });
 7639            this.insert("", cx);
 7640        });
 7641    }
 7642
 7643    pub fn delete_to_next_subword_end(
 7644        &mut self,
 7645        _: &DeleteToNextSubwordEnd,
 7646        cx: &mut ViewContext<Self>,
 7647    ) {
 7648        self.transact(cx, |this, cx| {
 7649            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7650                s.move_with(|map, selection| {
 7651                    if selection.is_empty() {
 7652                        let cursor = movement::next_subword_end(map, selection.head());
 7653                        selection.set_head(cursor, SelectionGoal::None);
 7654                    }
 7655                });
 7656            });
 7657            this.insert("", cx);
 7658        });
 7659    }
 7660
 7661    pub fn move_to_beginning_of_line(
 7662        &mut self,
 7663        action: &MoveToBeginningOfLine,
 7664        cx: &mut ViewContext<Self>,
 7665    ) {
 7666        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7667            s.move_cursors_with(|map, head, _| {
 7668                (
 7669                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7670                    SelectionGoal::None,
 7671                )
 7672            });
 7673        })
 7674    }
 7675
 7676    pub fn select_to_beginning_of_line(
 7677        &mut self,
 7678        action: &SelectToBeginningOfLine,
 7679        cx: &mut ViewContext<Self>,
 7680    ) {
 7681        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7682            s.move_heads_with(|map, head, _| {
 7683                (
 7684                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7685                    SelectionGoal::None,
 7686                )
 7687            });
 7688        });
 7689    }
 7690
 7691    pub fn delete_to_beginning_of_line(
 7692        &mut self,
 7693        _: &DeleteToBeginningOfLine,
 7694        cx: &mut ViewContext<Self>,
 7695    ) {
 7696        self.transact(cx, |this, cx| {
 7697            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7698                s.move_with(|_, selection| {
 7699                    selection.reversed = true;
 7700                });
 7701            });
 7702
 7703            this.select_to_beginning_of_line(
 7704                &SelectToBeginningOfLine {
 7705                    stop_at_soft_wraps: false,
 7706                },
 7707                cx,
 7708            );
 7709            this.backspace(&Backspace, cx);
 7710        });
 7711    }
 7712
 7713    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7714        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7715            s.move_cursors_with(|map, head, _| {
 7716                (
 7717                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7718                    SelectionGoal::None,
 7719                )
 7720            });
 7721        })
 7722    }
 7723
 7724    pub fn select_to_end_of_line(
 7725        &mut self,
 7726        action: &SelectToEndOfLine,
 7727        cx: &mut ViewContext<Self>,
 7728    ) {
 7729        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7730            s.move_heads_with(|map, head, _| {
 7731                (
 7732                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7733                    SelectionGoal::None,
 7734                )
 7735            });
 7736        })
 7737    }
 7738
 7739    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7740        self.transact(cx, |this, cx| {
 7741            this.select_to_end_of_line(
 7742                &SelectToEndOfLine {
 7743                    stop_at_soft_wraps: false,
 7744                },
 7745                cx,
 7746            );
 7747            this.delete(&Delete, cx);
 7748        });
 7749    }
 7750
 7751    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7752        self.transact(cx, |this, cx| {
 7753            this.select_to_end_of_line(
 7754                &SelectToEndOfLine {
 7755                    stop_at_soft_wraps: false,
 7756                },
 7757                cx,
 7758            );
 7759            this.cut(&Cut, cx);
 7760        });
 7761    }
 7762
 7763    pub fn move_to_start_of_paragraph(
 7764        &mut self,
 7765        _: &MoveToStartOfParagraph,
 7766        cx: &mut ViewContext<Self>,
 7767    ) {
 7768        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7769            cx.propagate();
 7770            return;
 7771        }
 7772
 7773        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7774            s.move_with(|map, selection| {
 7775                selection.collapse_to(
 7776                    movement::start_of_paragraph(map, selection.head(), 1),
 7777                    SelectionGoal::None,
 7778                )
 7779            });
 7780        })
 7781    }
 7782
 7783    pub fn move_to_end_of_paragraph(
 7784        &mut self,
 7785        _: &MoveToEndOfParagraph,
 7786        cx: &mut ViewContext<Self>,
 7787    ) {
 7788        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7789            cx.propagate();
 7790            return;
 7791        }
 7792
 7793        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7794            s.move_with(|map, selection| {
 7795                selection.collapse_to(
 7796                    movement::end_of_paragraph(map, selection.head(), 1),
 7797                    SelectionGoal::None,
 7798                )
 7799            });
 7800        })
 7801    }
 7802
 7803    pub fn select_to_start_of_paragraph(
 7804        &mut self,
 7805        _: &SelectToStartOfParagraph,
 7806        cx: &mut ViewContext<Self>,
 7807    ) {
 7808        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7809            cx.propagate();
 7810            return;
 7811        }
 7812
 7813        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7814            s.move_heads_with(|map, head, _| {
 7815                (
 7816                    movement::start_of_paragraph(map, head, 1),
 7817                    SelectionGoal::None,
 7818                )
 7819            });
 7820        })
 7821    }
 7822
 7823    pub fn select_to_end_of_paragraph(
 7824        &mut self,
 7825        _: &SelectToEndOfParagraph,
 7826        cx: &mut ViewContext<Self>,
 7827    ) {
 7828        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7829            cx.propagate();
 7830            return;
 7831        }
 7832
 7833        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7834            s.move_heads_with(|map, head, _| {
 7835                (
 7836                    movement::end_of_paragraph(map, head, 1),
 7837                    SelectionGoal::None,
 7838                )
 7839            });
 7840        })
 7841    }
 7842
 7843    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7844        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7845            cx.propagate();
 7846            return;
 7847        }
 7848
 7849        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7850            s.select_ranges(vec![0..0]);
 7851        });
 7852    }
 7853
 7854    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7855        let mut selection = self.selections.last::<Point>(cx);
 7856        selection.set_head(Point::zero(), SelectionGoal::None);
 7857
 7858        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7859            s.select(vec![selection]);
 7860        });
 7861    }
 7862
 7863    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7864        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7865            cx.propagate();
 7866            return;
 7867        }
 7868
 7869        let cursor = self.buffer.read(cx).read(cx).len();
 7870        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7871            s.select_ranges(vec![cursor..cursor])
 7872        });
 7873    }
 7874
 7875    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7876        self.nav_history = nav_history;
 7877    }
 7878
 7879    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7880        self.nav_history.as_ref()
 7881    }
 7882
 7883    fn push_to_nav_history(
 7884        &mut self,
 7885        cursor_anchor: Anchor,
 7886        new_position: Option<Point>,
 7887        cx: &mut ViewContext<Self>,
 7888    ) {
 7889        if let Some(nav_history) = self.nav_history.as_mut() {
 7890            let buffer = self.buffer.read(cx).read(cx);
 7891            let cursor_position = cursor_anchor.to_point(&buffer);
 7892            let scroll_state = self.scroll_manager.anchor();
 7893            let scroll_top_row = scroll_state.top_row(&buffer);
 7894            drop(buffer);
 7895
 7896            if let Some(new_position) = new_position {
 7897                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7898                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7899                    return;
 7900                }
 7901            }
 7902
 7903            nav_history.push(
 7904                Some(NavigationData {
 7905                    cursor_anchor,
 7906                    cursor_position,
 7907                    scroll_anchor: scroll_state,
 7908                    scroll_top_row,
 7909                }),
 7910                cx,
 7911            );
 7912        }
 7913    }
 7914
 7915    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7916        let buffer = self.buffer.read(cx).snapshot(cx);
 7917        let mut selection = self.selections.first::<usize>(cx);
 7918        selection.set_head(buffer.len(), SelectionGoal::None);
 7919        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7920            s.select(vec![selection]);
 7921        });
 7922    }
 7923
 7924    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7925        let end = self.buffer.read(cx).read(cx).len();
 7926        self.change_selections(None, cx, |s| {
 7927            s.select_ranges(vec![0..end]);
 7928        });
 7929    }
 7930
 7931    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7932        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7933        let mut selections = self.selections.all::<Point>(cx);
 7934        let max_point = display_map.buffer_snapshot.max_point();
 7935        for selection in &mut selections {
 7936            let rows = selection.spanned_rows(true, &display_map);
 7937            selection.start = Point::new(rows.start.0, 0);
 7938            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7939            selection.reversed = false;
 7940        }
 7941        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7942            s.select(selections);
 7943        });
 7944    }
 7945
 7946    pub fn split_selection_into_lines(
 7947        &mut self,
 7948        _: &SplitSelectionIntoLines,
 7949        cx: &mut ViewContext<Self>,
 7950    ) {
 7951        let mut to_unfold = Vec::new();
 7952        let mut new_selection_ranges = Vec::new();
 7953        {
 7954            let selections = self.selections.all::<Point>(cx);
 7955            let buffer = self.buffer.read(cx).read(cx);
 7956            for selection in selections {
 7957                for row in selection.start.row..selection.end.row {
 7958                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7959                    new_selection_ranges.push(cursor..cursor);
 7960                }
 7961                new_selection_ranges.push(selection.end..selection.end);
 7962                to_unfold.push(selection.start..selection.end);
 7963            }
 7964        }
 7965        self.unfold_ranges(&to_unfold, true, true, cx);
 7966        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7967            s.select_ranges(new_selection_ranges);
 7968        });
 7969    }
 7970
 7971    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7972        self.add_selection(true, cx);
 7973    }
 7974
 7975    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7976        self.add_selection(false, cx);
 7977    }
 7978
 7979    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7980        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7981        let mut selections = self.selections.all::<Point>(cx);
 7982        let text_layout_details = self.text_layout_details(cx);
 7983        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7984            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7985            let range = oldest_selection.display_range(&display_map).sorted();
 7986
 7987            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7988            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7989            let positions = start_x.min(end_x)..start_x.max(end_x);
 7990
 7991            selections.clear();
 7992            let mut stack = Vec::new();
 7993            for row in range.start.row().0..=range.end.row().0 {
 7994                if let Some(selection) = self.selections.build_columnar_selection(
 7995                    &display_map,
 7996                    DisplayRow(row),
 7997                    &positions,
 7998                    oldest_selection.reversed,
 7999                    &text_layout_details,
 8000                ) {
 8001                    stack.push(selection.id);
 8002                    selections.push(selection);
 8003                }
 8004            }
 8005
 8006            if above {
 8007                stack.reverse();
 8008            }
 8009
 8010            AddSelectionsState { above, stack }
 8011        });
 8012
 8013        let last_added_selection = *state.stack.last().unwrap();
 8014        let mut new_selections = Vec::new();
 8015        if above == state.above {
 8016            let end_row = if above {
 8017                DisplayRow(0)
 8018            } else {
 8019                display_map.max_point().row()
 8020            };
 8021
 8022            'outer: for selection in selections {
 8023                if selection.id == last_added_selection {
 8024                    let range = selection.display_range(&display_map).sorted();
 8025                    debug_assert_eq!(range.start.row(), range.end.row());
 8026                    let mut row = range.start.row();
 8027                    let positions =
 8028                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8029                            px(start)..px(end)
 8030                        } else {
 8031                            let start_x =
 8032                                display_map.x_for_display_point(range.start, &text_layout_details);
 8033                            let end_x =
 8034                                display_map.x_for_display_point(range.end, &text_layout_details);
 8035                            start_x.min(end_x)..start_x.max(end_x)
 8036                        };
 8037
 8038                    while row != end_row {
 8039                        if above {
 8040                            row.0 -= 1;
 8041                        } else {
 8042                            row.0 += 1;
 8043                        }
 8044
 8045                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8046                            &display_map,
 8047                            row,
 8048                            &positions,
 8049                            selection.reversed,
 8050                            &text_layout_details,
 8051                        ) {
 8052                            state.stack.push(new_selection.id);
 8053                            if above {
 8054                                new_selections.push(new_selection);
 8055                                new_selections.push(selection);
 8056                            } else {
 8057                                new_selections.push(selection);
 8058                                new_selections.push(new_selection);
 8059                            }
 8060
 8061                            continue 'outer;
 8062                        }
 8063                    }
 8064                }
 8065
 8066                new_selections.push(selection);
 8067            }
 8068        } else {
 8069            new_selections = selections;
 8070            new_selections.retain(|s| s.id != last_added_selection);
 8071            state.stack.pop();
 8072        }
 8073
 8074        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8075            s.select(new_selections);
 8076        });
 8077        if state.stack.len() > 1 {
 8078            self.add_selections_state = Some(state);
 8079        }
 8080    }
 8081
 8082    pub fn select_next_match_internal(
 8083        &mut self,
 8084        display_map: &DisplaySnapshot,
 8085        replace_newest: bool,
 8086        autoscroll: Option<Autoscroll>,
 8087        cx: &mut ViewContext<Self>,
 8088    ) -> Result<()> {
 8089        fn select_next_match_ranges(
 8090            this: &mut Editor,
 8091            range: Range<usize>,
 8092            replace_newest: bool,
 8093            auto_scroll: Option<Autoscroll>,
 8094            cx: &mut ViewContext<Editor>,
 8095        ) {
 8096            this.unfold_ranges(&[range.clone()], false, true, cx);
 8097            this.change_selections(auto_scroll, cx, |s| {
 8098                if replace_newest {
 8099                    s.delete(s.newest_anchor().id);
 8100                }
 8101                s.insert_range(range.clone());
 8102            });
 8103        }
 8104
 8105        let buffer = &display_map.buffer_snapshot;
 8106        let mut selections = self.selections.all::<usize>(cx);
 8107        if let Some(mut select_next_state) = self.select_next_state.take() {
 8108            let query = &select_next_state.query;
 8109            if !select_next_state.done {
 8110                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8111                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8112                let mut next_selected_range = None;
 8113
 8114                let bytes_after_last_selection =
 8115                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8116                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8117                let query_matches = query
 8118                    .stream_find_iter(bytes_after_last_selection)
 8119                    .map(|result| (last_selection.end, result))
 8120                    .chain(
 8121                        query
 8122                            .stream_find_iter(bytes_before_first_selection)
 8123                            .map(|result| (0, result)),
 8124                    );
 8125
 8126                for (start_offset, query_match) in query_matches {
 8127                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8128                    let offset_range =
 8129                        start_offset + query_match.start()..start_offset + query_match.end();
 8130                    let display_range = offset_range.start.to_display_point(display_map)
 8131                        ..offset_range.end.to_display_point(display_map);
 8132
 8133                    if !select_next_state.wordwise
 8134                        || (!movement::is_inside_word(display_map, display_range.start)
 8135                            && !movement::is_inside_word(display_map, display_range.end))
 8136                    {
 8137                        // TODO: This is n^2, because we might check all the selections
 8138                        if !selections
 8139                            .iter()
 8140                            .any(|selection| selection.range().overlaps(&offset_range))
 8141                        {
 8142                            next_selected_range = Some(offset_range);
 8143                            break;
 8144                        }
 8145                    }
 8146                }
 8147
 8148                if let Some(next_selected_range) = next_selected_range {
 8149                    select_next_match_ranges(
 8150                        self,
 8151                        next_selected_range,
 8152                        replace_newest,
 8153                        autoscroll,
 8154                        cx,
 8155                    );
 8156                } else {
 8157                    select_next_state.done = true;
 8158                }
 8159            }
 8160
 8161            self.select_next_state = Some(select_next_state);
 8162        } else {
 8163            let mut only_carets = true;
 8164            let mut same_text_selected = true;
 8165            let mut selected_text = None;
 8166
 8167            let mut selections_iter = selections.iter().peekable();
 8168            while let Some(selection) = selections_iter.next() {
 8169                if selection.start != selection.end {
 8170                    only_carets = false;
 8171                }
 8172
 8173                if same_text_selected {
 8174                    if selected_text.is_none() {
 8175                        selected_text =
 8176                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8177                    }
 8178
 8179                    if let Some(next_selection) = selections_iter.peek() {
 8180                        if next_selection.range().len() == selection.range().len() {
 8181                            let next_selected_text = buffer
 8182                                .text_for_range(next_selection.range())
 8183                                .collect::<String>();
 8184                            if Some(next_selected_text) != selected_text {
 8185                                same_text_selected = false;
 8186                                selected_text = None;
 8187                            }
 8188                        } else {
 8189                            same_text_selected = false;
 8190                            selected_text = None;
 8191                        }
 8192                    }
 8193                }
 8194            }
 8195
 8196            if only_carets {
 8197                for selection in &mut selections {
 8198                    let word_range = movement::surrounding_word(
 8199                        display_map,
 8200                        selection.start.to_display_point(display_map),
 8201                    );
 8202                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8203                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8204                    selection.goal = SelectionGoal::None;
 8205                    selection.reversed = false;
 8206                    select_next_match_ranges(
 8207                        self,
 8208                        selection.start..selection.end,
 8209                        replace_newest,
 8210                        autoscroll,
 8211                        cx,
 8212                    );
 8213                }
 8214
 8215                if selections.len() == 1 {
 8216                    let selection = selections
 8217                        .last()
 8218                        .expect("ensured that there's only one selection");
 8219                    let query = buffer
 8220                        .text_for_range(selection.start..selection.end)
 8221                        .collect::<String>();
 8222                    let is_empty = query.is_empty();
 8223                    let select_state = SelectNextState {
 8224                        query: AhoCorasick::new(&[query])?,
 8225                        wordwise: true,
 8226                        done: is_empty,
 8227                    };
 8228                    self.select_next_state = Some(select_state);
 8229                } else {
 8230                    self.select_next_state = None;
 8231                }
 8232            } else if let Some(selected_text) = selected_text {
 8233                self.select_next_state = Some(SelectNextState {
 8234                    query: AhoCorasick::new(&[selected_text])?,
 8235                    wordwise: false,
 8236                    done: false,
 8237                });
 8238                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8239            }
 8240        }
 8241        Ok(())
 8242    }
 8243
 8244    pub fn select_all_matches(
 8245        &mut self,
 8246        _action: &SelectAllMatches,
 8247        cx: &mut ViewContext<Self>,
 8248    ) -> Result<()> {
 8249        self.push_to_selection_history();
 8250        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8251
 8252        self.select_next_match_internal(&display_map, false, None, cx)?;
 8253        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8254            return Ok(());
 8255        };
 8256        if select_next_state.done {
 8257            return Ok(());
 8258        }
 8259
 8260        let mut new_selections = self.selections.all::<usize>(cx);
 8261
 8262        let buffer = &display_map.buffer_snapshot;
 8263        let query_matches = select_next_state
 8264            .query
 8265            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8266
 8267        for query_match in query_matches {
 8268            let query_match = query_match.unwrap(); // can only fail due to I/O
 8269            let offset_range = query_match.start()..query_match.end();
 8270            let display_range = offset_range.start.to_display_point(&display_map)
 8271                ..offset_range.end.to_display_point(&display_map);
 8272
 8273            if !select_next_state.wordwise
 8274                || (!movement::is_inside_word(&display_map, display_range.start)
 8275                    && !movement::is_inside_word(&display_map, display_range.end))
 8276            {
 8277                self.selections.change_with(cx, |selections| {
 8278                    new_selections.push(Selection {
 8279                        id: selections.new_selection_id(),
 8280                        start: offset_range.start,
 8281                        end: offset_range.end,
 8282                        reversed: false,
 8283                        goal: SelectionGoal::None,
 8284                    });
 8285                });
 8286            }
 8287        }
 8288
 8289        new_selections.sort_by_key(|selection| selection.start);
 8290        let mut ix = 0;
 8291        while ix + 1 < new_selections.len() {
 8292            let current_selection = &new_selections[ix];
 8293            let next_selection = &new_selections[ix + 1];
 8294            if current_selection.range().overlaps(&next_selection.range()) {
 8295                if current_selection.id < next_selection.id {
 8296                    new_selections.remove(ix + 1);
 8297                } else {
 8298                    new_selections.remove(ix);
 8299                }
 8300            } else {
 8301                ix += 1;
 8302            }
 8303        }
 8304
 8305        select_next_state.done = true;
 8306        self.unfold_ranges(
 8307            &new_selections
 8308                .iter()
 8309                .map(|selection| selection.range())
 8310                .collect::<Vec<_>>(),
 8311            false,
 8312            false,
 8313            cx,
 8314        );
 8315        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8316            selections.select(new_selections)
 8317        });
 8318
 8319        Ok(())
 8320    }
 8321
 8322    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8323        self.push_to_selection_history();
 8324        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8325        self.select_next_match_internal(
 8326            &display_map,
 8327            action.replace_newest,
 8328            Some(Autoscroll::newest()),
 8329            cx,
 8330        )?;
 8331        Ok(())
 8332    }
 8333
 8334    pub fn select_previous(
 8335        &mut self,
 8336        action: &SelectPrevious,
 8337        cx: &mut ViewContext<Self>,
 8338    ) -> Result<()> {
 8339        self.push_to_selection_history();
 8340        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8341        let buffer = &display_map.buffer_snapshot;
 8342        let mut selections = self.selections.all::<usize>(cx);
 8343        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8344            let query = &select_prev_state.query;
 8345            if !select_prev_state.done {
 8346                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8347                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8348                let mut next_selected_range = None;
 8349                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8350                let bytes_before_last_selection =
 8351                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8352                let bytes_after_first_selection =
 8353                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8354                let query_matches = query
 8355                    .stream_find_iter(bytes_before_last_selection)
 8356                    .map(|result| (last_selection.start, result))
 8357                    .chain(
 8358                        query
 8359                            .stream_find_iter(bytes_after_first_selection)
 8360                            .map(|result| (buffer.len(), result)),
 8361                    );
 8362                for (end_offset, query_match) in query_matches {
 8363                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8364                    let offset_range =
 8365                        end_offset - query_match.end()..end_offset - query_match.start();
 8366                    let display_range = offset_range.start.to_display_point(&display_map)
 8367                        ..offset_range.end.to_display_point(&display_map);
 8368
 8369                    if !select_prev_state.wordwise
 8370                        || (!movement::is_inside_word(&display_map, display_range.start)
 8371                            && !movement::is_inside_word(&display_map, display_range.end))
 8372                    {
 8373                        next_selected_range = Some(offset_range);
 8374                        break;
 8375                    }
 8376                }
 8377
 8378                if let Some(next_selected_range) = next_selected_range {
 8379                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8380                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8381                        if action.replace_newest {
 8382                            s.delete(s.newest_anchor().id);
 8383                        }
 8384                        s.insert_range(next_selected_range);
 8385                    });
 8386                } else {
 8387                    select_prev_state.done = true;
 8388                }
 8389            }
 8390
 8391            self.select_prev_state = Some(select_prev_state);
 8392        } else {
 8393            let mut only_carets = true;
 8394            let mut same_text_selected = true;
 8395            let mut selected_text = None;
 8396
 8397            let mut selections_iter = selections.iter().peekable();
 8398            while let Some(selection) = selections_iter.next() {
 8399                if selection.start != selection.end {
 8400                    only_carets = false;
 8401                }
 8402
 8403                if same_text_selected {
 8404                    if selected_text.is_none() {
 8405                        selected_text =
 8406                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8407                    }
 8408
 8409                    if let Some(next_selection) = selections_iter.peek() {
 8410                        if next_selection.range().len() == selection.range().len() {
 8411                            let next_selected_text = buffer
 8412                                .text_for_range(next_selection.range())
 8413                                .collect::<String>();
 8414                            if Some(next_selected_text) != selected_text {
 8415                                same_text_selected = false;
 8416                                selected_text = None;
 8417                            }
 8418                        } else {
 8419                            same_text_selected = false;
 8420                            selected_text = None;
 8421                        }
 8422                    }
 8423                }
 8424            }
 8425
 8426            if only_carets {
 8427                for selection in &mut selections {
 8428                    let word_range = movement::surrounding_word(
 8429                        &display_map,
 8430                        selection.start.to_display_point(&display_map),
 8431                    );
 8432                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8433                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8434                    selection.goal = SelectionGoal::None;
 8435                    selection.reversed = false;
 8436                }
 8437                if selections.len() == 1 {
 8438                    let selection = selections
 8439                        .last()
 8440                        .expect("ensured that there's only one selection");
 8441                    let query = buffer
 8442                        .text_for_range(selection.start..selection.end)
 8443                        .collect::<String>();
 8444                    let is_empty = query.is_empty();
 8445                    let select_state = SelectNextState {
 8446                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8447                        wordwise: true,
 8448                        done: is_empty,
 8449                    };
 8450                    self.select_prev_state = Some(select_state);
 8451                } else {
 8452                    self.select_prev_state = None;
 8453                }
 8454
 8455                self.unfold_ranges(
 8456                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8457                    false,
 8458                    true,
 8459                    cx,
 8460                );
 8461                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8462                    s.select(selections);
 8463                });
 8464            } else if let Some(selected_text) = selected_text {
 8465                self.select_prev_state = Some(SelectNextState {
 8466                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8467                    wordwise: false,
 8468                    done: false,
 8469                });
 8470                self.select_previous(action, cx)?;
 8471            }
 8472        }
 8473        Ok(())
 8474    }
 8475
 8476    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8477        if self.read_only(cx) {
 8478            return;
 8479        }
 8480        let text_layout_details = &self.text_layout_details(cx);
 8481        self.transact(cx, |this, cx| {
 8482            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8483            let mut edits = Vec::new();
 8484            let mut selection_edit_ranges = Vec::new();
 8485            let mut last_toggled_row = None;
 8486            let snapshot = this.buffer.read(cx).read(cx);
 8487            let empty_str: Arc<str> = Arc::default();
 8488            let mut suffixes_inserted = Vec::new();
 8489            let ignore_indent = action.ignore_indent;
 8490
 8491            fn comment_prefix_range(
 8492                snapshot: &MultiBufferSnapshot,
 8493                row: MultiBufferRow,
 8494                comment_prefix: &str,
 8495                comment_prefix_whitespace: &str,
 8496                ignore_indent: bool,
 8497            ) -> Range<Point> {
 8498                let indent_size = if ignore_indent {
 8499                    0
 8500                } else {
 8501                    snapshot.indent_size_for_line(row).len
 8502                };
 8503
 8504                let start = Point::new(row.0, indent_size);
 8505
 8506                let mut line_bytes = snapshot
 8507                    .bytes_in_range(start..snapshot.max_point())
 8508                    .flatten()
 8509                    .copied();
 8510
 8511                // If this line currently begins with the line comment prefix, then record
 8512                // the range containing the prefix.
 8513                if line_bytes
 8514                    .by_ref()
 8515                    .take(comment_prefix.len())
 8516                    .eq(comment_prefix.bytes())
 8517                {
 8518                    // Include any whitespace that matches the comment prefix.
 8519                    let matching_whitespace_len = line_bytes
 8520                        .zip(comment_prefix_whitespace.bytes())
 8521                        .take_while(|(a, b)| a == b)
 8522                        .count() as u32;
 8523                    let end = Point::new(
 8524                        start.row,
 8525                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8526                    );
 8527                    start..end
 8528                } else {
 8529                    start..start
 8530                }
 8531            }
 8532
 8533            fn comment_suffix_range(
 8534                snapshot: &MultiBufferSnapshot,
 8535                row: MultiBufferRow,
 8536                comment_suffix: &str,
 8537                comment_suffix_has_leading_space: bool,
 8538            ) -> Range<Point> {
 8539                let end = Point::new(row.0, snapshot.line_len(row));
 8540                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8541
 8542                let mut line_end_bytes = snapshot
 8543                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8544                    .flatten()
 8545                    .copied();
 8546
 8547                let leading_space_len = if suffix_start_column > 0
 8548                    && line_end_bytes.next() == Some(b' ')
 8549                    && comment_suffix_has_leading_space
 8550                {
 8551                    1
 8552                } else {
 8553                    0
 8554                };
 8555
 8556                // If this line currently begins with the line comment prefix, then record
 8557                // the range containing the prefix.
 8558                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8559                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8560                    start..end
 8561                } else {
 8562                    end..end
 8563                }
 8564            }
 8565
 8566            // TODO: Handle selections that cross excerpts
 8567            for selection in &mut selections {
 8568                let start_column = snapshot
 8569                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8570                    .len;
 8571                let language = if let Some(language) =
 8572                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8573                {
 8574                    language
 8575                } else {
 8576                    continue;
 8577                };
 8578
 8579                selection_edit_ranges.clear();
 8580
 8581                // If multiple selections contain a given row, avoid processing that
 8582                // row more than once.
 8583                let mut start_row = MultiBufferRow(selection.start.row);
 8584                if last_toggled_row == Some(start_row) {
 8585                    start_row = start_row.next_row();
 8586                }
 8587                let end_row =
 8588                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8589                        MultiBufferRow(selection.end.row - 1)
 8590                    } else {
 8591                        MultiBufferRow(selection.end.row)
 8592                    };
 8593                last_toggled_row = Some(end_row);
 8594
 8595                if start_row > end_row {
 8596                    continue;
 8597                }
 8598
 8599                // If the language has line comments, toggle those.
 8600                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8601
 8602                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8603                if ignore_indent {
 8604                    full_comment_prefixes = full_comment_prefixes
 8605                        .into_iter()
 8606                        .map(|s| Arc::from(s.trim_end()))
 8607                        .collect();
 8608                }
 8609
 8610                if !full_comment_prefixes.is_empty() {
 8611                    let first_prefix = full_comment_prefixes
 8612                        .first()
 8613                        .expect("prefixes is non-empty");
 8614                    let prefix_trimmed_lengths = full_comment_prefixes
 8615                        .iter()
 8616                        .map(|p| p.trim_end_matches(' ').len())
 8617                        .collect::<SmallVec<[usize; 4]>>();
 8618
 8619                    let mut all_selection_lines_are_comments = true;
 8620
 8621                    for row in start_row.0..=end_row.0 {
 8622                        let row = MultiBufferRow(row);
 8623                        if start_row < end_row && snapshot.is_line_blank(row) {
 8624                            continue;
 8625                        }
 8626
 8627                        let prefix_range = full_comment_prefixes
 8628                            .iter()
 8629                            .zip(prefix_trimmed_lengths.iter().copied())
 8630                            .map(|(prefix, trimmed_prefix_len)| {
 8631                                comment_prefix_range(
 8632                                    snapshot.deref(),
 8633                                    row,
 8634                                    &prefix[..trimmed_prefix_len],
 8635                                    &prefix[trimmed_prefix_len..],
 8636                                    ignore_indent,
 8637                                )
 8638                            })
 8639                            .max_by_key(|range| range.end.column - range.start.column)
 8640                            .expect("prefixes is non-empty");
 8641
 8642                        if prefix_range.is_empty() {
 8643                            all_selection_lines_are_comments = false;
 8644                        }
 8645
 8646                        selection_edit_ranges.push(prefix_range);
 8647                    }
 8648
 8649                    if all_selection_lines_are_comments {
 8650                        edits.extend(
 8651                            selection_edit_ranges
 8652                                .iter()
 8653                                .cloned()
 8654                                .map(|range| (range, empty_str.clone())),
 8655                        );
 8656                    } else {
 8657                        let min_column = selection_edit_ranges
 8658                            .iter()
 8659                            .map(|range| range.start.column)
 8660                            .min()
 8661                            .unwrap_or(0);
 8662                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8663                            let position = Point::new(range.start.row, min_column);
 8664                            (position..position, first_prefix.clone())
 8665                        }));
 8666                    }
 8667                } else if let Some((full_comment_prefix, comment_suffix)) =
 8668                    language.block_comment_delimiters()
 8669                {
 8670                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8671                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8672                    let prefix_range = comment_prefix_range(
 8673                        snapshot.deref(),
 8674                        start_row,
 8675                        comment_prefix,
 8676                        comment_prefix_whitespace,
 8677                        ignore_indent,
 8678                    );
 8679                    let suffix_range = comment_suffix_range(
 8680                        snapshot.deref(),
 8681                        end_row,
 8682                        comment_suffix.trim_start_matches(' '),
 8683                        comment_suffix.starts_with(' '),
 8684                    );
 8685
 8686                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8687                        edits.push((
 8688                            prefix_range.start..prefix_range.start,
 8689                            full_comment_prefix.clone(),
 8690                        ));
 8691                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8692                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8693                    } else {
 8694                        edits.push((prefix_range, empty_str.clone()));
 8695                        edits.push((suffix_range, empty_str.clone()));
 8696                    }
 8697                } else {
 8698                    continue;
 8699                }
 8700            }
 8701
 8702            drop(snapshot);
 8703            this.buffer.update(cx, |buffer, cx| {
 8704                buffer.edit(edits, None, cx);
 8705            });
 8706
 8707            // Adjust selections so that they end before any comment suffixes that
 8708            // were inserted.
 8709            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8710            let mut selections = this.selections.all::<Point>(cx);
 8711            let snapshot = this.buffer.read(cx).read(cx);
 8712            for selection in &mut selections {
 8713                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8714                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8715                        Ordering::Less => {
 8716                            suffixes_inserted.next();
 8717                            continue;
 8718                        }
 8719                        Ordering::Greater => break,
 8720                        Ordering::Equal => {
 8721                            if selection.end.column == snapshot.line_len(row) {
 8722                                if selection.is_empty() {
 8723                                    selection.start.column -= suffix_len as u32;
 8724                                }
 8725                                selection.end.column -= suffix_len as u32;
 8726                            }
 8727                            break;
 8728                        }
 8729                    }
 8730                }
 8731            }
 8732
 8733            drop(snapshot);
 8734            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8735
 8736            let selections = this.selections.all::<Point>(cx);
 8737            let selections_on_single_row = selections.windows(2).all(|selections| {
 8738                selections[0].start.row == selections[1].start.row
 8739                    && selections[0].end.row == selections[1].end.row
 8740                    && selections[0].start.row == selections[0].end.row
 8741            });
 8742            let selections_selecting = selections
 8743                .iter()
 8744                .any(|selection| selection.start != selection.end);
 8745            let advance_downwards = action.advance_downwards
 8746                && selections_on_single_row
 8747                && !selections_selecting
 8748                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8749
 8750            if advance_downwards {
 8751                let snapshot = this.buffer.read(cx).snapshot(cx);
 8752
 8753                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8754                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8755                        let mut point = display_point.to_point(display_snapshot);
 8756                        point.row += 1;
 8757                        point = snapshot.clip_point(point, Bias::Left);
 8758                        let display_point = point.to_display_point(display_snapshot);
 8759                        let goal = SelectionGoal::HorizontalPosition(
 8760                            display_snapshot
 8761                                .x_for_display_point(display_point, text_layout_details)
 8762                                .into(),
 8763                        );
 8764                        (display_point, goal)
 8765                    })
 8766                });
 8767            }
 8768        });
 8769    }
 8770
 8771    pub fn select_enclosing_symbol(
 8772        &mut self,
 8773        _: &SelectEnclosingSymbol,
 8774        cx: &mut ViewContext<Self>,
 8775    ) {
 8776        let buffer = self.buffer.read(cx).snapshot(cx);
 8777        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8778
 8779        fn update_selection(
 8780            selection: &Selection<usize>,
 8781            buffer_snap: &MultiBufferSnapshot,
 8782        ) -> Option<Selection<usize>> {
 8783            let cursor = selection.head();
 8784            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8785            for symbol in symbols.iter().rev() {
 8786                let start = symbol.range.start.to_offset(buffer_snap);
 8787                let end = symbol.range.end.to_offset(buffer_snap);
 8788                let new_range = start..end;
 8789                if start < selection.start || end > selection.end {
 8790                    return Some(Selection {
 8791                        id: selection.id,
 8792                        start: new_range.start,
 8793                        end: new_range.end,
 8794                        goal: SelectionGoal::None,
 8795                        reversed: selection.reversed,
 8796                    });
 8797                }
 8798            }
 8799            None
 8800        }
 8801
 8802        let mut selected_larger_symbol = false;
 8803        let new_selections = old_selections
 8804            .iter()
 8805            .map(|selection| match update_selection(selection, &buffer) {
 8806                Some(new_selection) => {
 8807                    if new_selection.range() != selection.range() {
 8808                        selected_larger_symbol = true;
 8809                    }
 8810                    new_selection
 8811                }
 8812                None => selection.clone(),
 8813            })
 8814            .collect::<Vec<_>>();
 8815
 8816        if selected_larger_symbol {
 8817            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8818                s.select(new_selections);
 8819            });
 8820        }
 8821    }
 8822
 8823    pub fn select_larger_syntax_node(
 8824        &mut self,
 8825        _: &SelectLargerSyntaxNode,
 8826        cx: &mut ViewContext<Self>,
 8827    ) {
 8828        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8829        let buffer = self.buffer.read(cx).snapshot(cx);
 8830        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8831
 8832        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8833        let mut selected_larger_node = false;
 8834        let new_selections = old_selections
 8835            .iter()
 8836            .map(|selection| {
 8837                let old_range = selection.start..selection.end;
 8838                let mut new_range = old_range.clone();
 8839                let mut new_node = None;
 8840                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 8841                {
 8842                    new_node = Some(node);
 8843                    new_range = containing_range;
 8844                    if !display_map.intersects_fold(new_range.start)
 8845                        && !display_map.intersects_fold(new_range.end)
 8846                    {
 8847                        break;
 8848                    }
 8849                }
 8850
 8851                if let Some(node) = new_node {
 8852                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 8853                    // nodes. Parent and grandparent are also logged because this operation will not
 8854                    // visit nodes that have the same range as their parent.
 8855                    log::info!("Node: {node:?}");
 8856                    let parent = node.parent();
 8857                    log::info!("Parent: {parent:?}");
 8858                    let grandparent = parent.and_then(|x| x.parent());
 8859                    log::info!("Grandparent: {grandparent:?}");
 8860                }
 8861
 8862                selected_larger_node |= new_range != old_range;
 8863                Selection {
 8864                    id: selection.id,
 8865                    start: new_range.start,
 8866                    end: new_range.end,
 8867                    goal: SelectionGoal::None,
 8868                    reversed: selection.reversed,
 8869                }
 8870            })
 8871            .collect::<Vec<_>>();
 8872
 8873        if selected_larger_node {
 8874            stack.push(old_selections);
 8875            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8876                s.select(new_selections);
 8877            });
 8878        }
 8879        self.select_larger_syntax_node_stack = stack;
 8880    }
 8881
 8882    pub fn select_smaller_syntax_node(
 8883        &mut self,
 8884        _: &SelectSmallerSyntaxNode,
 8885        cx: &mut ViewContext<Self>,
 8886    ) {
 8887        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8888        if let Some(selections) = stack.pop() {
 8889            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8890                s.select(selections.to_vec());
 8891            });
 8892        }
 8893        self.select_larger_syntax_node_stack = stack;
 8894    }
 8895
 8896    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8897        if !EditorSettings::get_global(cx).gutter.runnables {
 8898            self.clear_tasks();
 8899            return Task::ready(());
 8900        }
 8901        let project = self.project.as_ref().map(Model::downgrade);
 8902        cx.spawn(|this, mut cx| async move {
 8903            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8904            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8905                return;
 8906            };
 8907            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8908                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8909            }) else {
 8910                return;
 8911            };
 8912
 8913            let hide_runnables = project
 8914                .update(&mut cx, |project, cx| {
 8915                    // Do not display any test indicators in non-dev server remote projects.
 8916                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8917                })
 8918                .unwrap_or(true);
 8919            if hide_runnables {
 8920                return;
 8921            }
 8922            let new_rows =
 8923                cx.background_executor()
 8924                    .spawn({
 8925                        let snapshot = display_snapshot.clone();
 8926                        async move {
 8927                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8928                        }
 8929                    })
 8930                    .await;
 8931            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8932
 8933            this.update(&mut cx, |this, _| {
 8934                this.clear_tasks();
 8935                for (key, value) in rows {
 8936                    this.insert_tasks(key, value);
 8937                }
 8938            })
 8939            .ok();
 8940        })
 8941    }
 8942    fn fetch_runnable_ranges(
 8943        snapshot: &DisplaySnapshot,
 8944        range: Range<Anchor>,
 8945    ) -> Vec<language::RunnableRange> {
 8946        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8947    }
 8948
 8949    fn runnable_rows(
 8950        project: Model<Project>,
 8951        snapshot: DisplaySnapshot,
 8952        runnable_ranges: Vec<RunnableRange>,
 8953        mut cx: AsyncWindowContext,
 8954    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8955        runnable_ranges
 8956            .into_iter()
 8957            .filter_map(|mut runnable| {
 8958                let tasks = cx
 8959                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8960                    .ok()?;
 8961                if tasks.is_empty() {
 8962                    return None;
 8963                }
 8964
 8965                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8966
 8967                let row = snapshot
 8968                    .buffer_snapshot
 8969                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8970                    .1
 8971                    .start
 8972                    .row;
 8973
 8974                let context_range =
 8975                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8976                Some((
 8977                    (runnable.buffer_id, row),
 8978                    RunnableTasks {
 8979                        templates: tasks,
 8980                        offset: MultiBufferOffset(runnable.run_range.start),
 8981                        context_range,
 8982                        column: point.column,
 8983                        extra_variables: runnable.extra_captures,
 8984                    },
 8985                ))
 8986            })
 8987            .collect()
 8988    }
 8989
 8990    fn templates_with_tags(
 8991        project: &Model<Project>,
 8992        runnable: &mut Runnable,
 8993        cx: &WindowContext,
 8994    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8995        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8996            let (worktree_id, file) = project
 8997                .buffer_for_id(runnable.buffer, cx)
 8998                .and_then(|buffer| buffer.read(cx).file())
 8999                .map(|file| (file.worktree_id(cx), file.clone()))
 9000                .unzip();
 9001
 9002            (
 9003                project.task_store().read(cx).task_inventory().cloned(),
 9004                worktree_id,
 9005                file,
 9006            )
 9007        });
 9008
 9009        let tags = mem::take(&mut runnable.tags);
 9010        let mut tags: Vec<_> = tags
 9011            .into_iter()
 9012            .flat_map(|tag| {
 9013                let tag = tag.0.clone();
 9014                inventory
 9015                    .as_ref()
 9016                    .into_iter()
 9017                    .flat_map(|inventory| {
 9018                        inventory.read(cx).list_tasks(
 9019                            file.clone(),
 9020                            Some(runnable.language.clone()),
 9021                            worktree_id,
 9022                            cx,
 9023                        )
 9024                    })
 9025                    .filter(move |(_, template)| {
 9026                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9027                    })
 9028            })
 9029            .sorted_by_key(|(kind, _)| kind.to_owned())
 9030            .collect();
 9031        if let Some((leading_tag_source, _)) = tags.first() {
 9032            // Strongest source wins; if we have worktree tag binding, prefer that to
 9033            // global and language bindings;
 9034            // if we have a global binding, prefer that to language binding.
 9035            let first_mismatch = tags
 9036                .iter()
 9037                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9038            if let Some(index) = first_mismatch {
 9039                tags.truncate(index);
 9040            }
 9041        }
 9042
 9043        tags
 9044    }
 9045
 9046    pub fn move_to_enclosing_bracket(
 9047        &mut self,
 9048        _: &MoveToEnclosingBracket,
 9049        cx: &mut ViewContext<Self>,
 9050    ) {
 9051        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9052            s.move_offsets_with(|snapshot, selection| {
 9053                let Some(enclosing_bracket_ranges) =
 9054                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9055                else {
 9056                    return;
 9057                };
 9058
 9059                let mut best_length = usize::MAX;
 9060                let mut best_inside = false;
 9061                let mut best_in_bracket_range = false;
 9062                let mut best_destination = None;
 9063                for (open, close) in enclosing_bracket_ranges {
 9064                    let close = close.to_inclusive();
 9065                    let length = close.end() - open.start;
 9066                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9067                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9068                        || close.contains(&selection.head());
 9069
 9070                    // If best is next to a bracket and current isn't, skip
 9071                    if !in_bracket_range && best_in_bracket_range {
 9072                        continue;
 9073                    }
 9074
 9075                    // Prefer smaller lengths unless best is inside and current isn't
 9076                    if length > best_length && (best_inside || !inside) {
 9077                        continue;
 9078                    }
 9079
 9080                    best_length = length;
 9081                    best_inside = inside;
 9082                    best_in_bracket_range = in_bracket_range;
 9083                    best_destination = Some(
 9084                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9085                            if inside {
 9086                                open.end
 9087                            } else {
 9088                                open.start
 9089                            }
 9090                        } else if inside {
 9091                            *close.start()
 9092                        } else {
 9093                            *close.end()
 9094                        },
 9095                    );
 9096                }
 9097
 9098                if let Some(destination) = best_destination {
 9099                    selection.collapse_to(destination, SelectionGoal::None);
 9100                }
 9101            })
 9102        });
 9103    }
 9104
 9105    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9106        self.end_selection(cx);
 9107        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9108        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9109            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9110            self.select_next_state = entry.select_next_state;
 9111            self.select_prev_state = entry.select_prev_state;
 9112            self.add_selections_state = entry.add_selections_state;
 9113            self.request_autoscroll(Autoscroll::newest(), cx);
 9114        }
 9115        self.selection_history.mode = SelectionHistoryMode::Normal;
 9116    }
 9117
 9118    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9119        self.end_selection(cx);
 9120        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9121        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9122            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9123            self.select_next_state = entry.select_next_state;
 9124            self.select_prev_state = entry.select_prev_state;
 9125            self.add_selections_state = entry.add_selections_state;
 9126            self.request_autoscroll(Autoscroll::newest(), cx);
 9127        }
 9128        self.selection_history.mode = SelectionHistoryMode::Normal;
 9129    }
 9130
 9131    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9132        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9133    }
 9134
 9135    pub fn expand_excerpts_down(
 9136        &mut self,
 9137        action: &ExpandExcerptsDown,
 9138        cx: &mut ViewContext<Self>,
 9139    ) {
 9140        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9141    }
 9142
 9143    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9144        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9145    }
 9146
 9147    pub fn expand_excerpts_for_direction(
 9148        &mut self,
 9149        lines: u32,
 9150        direction: ExpandExcerptDirection,
 9151        cx: &mut ViewContext<Self>,
 9152    ) {
 9153        let selections = self.selections.disjoint_anchors();
 9154
 9155        let lines = if lines == 0 {
 9156            EditorSettings::get_global(cx).expand_excerpt_lines
 9157        } else {
 9158            lines
 9159        };
 9160
 9161        self.buffer.update(cx, |buffer, cx| {
 9162            let snapshot = buffer.snapshot(cx);
 9163            let mut excerpt_ids = selections
 9164                .iter()
 9165                .flat_map(|selection| {
 9166                    snapshot
 9167                        .excerpts_for_range(selection.range())
 9168                        .map(|excerpt| excerpt.id())
 9169                })
 9170                .collect::<Vec<_>>();
 9171            excerpt_ids.sort();
 9172            excerpt_ids.dedup();
 9173            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9174        })
 9175    }
 9176
 9177    pub fn expand_excerpt(
 9178        &mut self,
 9179        excerpt: ExcerptId,
 9180        direction: ExpandExcerptDirection,
 9181        cx: &mut ViewContext<Self>,
 9182    ) {
 9183        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9184        self.buffer.update(cx, |buffer, cx| {
 9185            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9186        })
 9187    }
 9188
 9189    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9190        self.go_to_diagnostic_impl(Direction::Next, cx)
 9191    }
 9192
 9193    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9194        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9195    }
 9196
 9197    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9198        let buffer = self.buffer.read(cx).snapshot(cx);
 9199        let selection = self.selections.newest::<usize>(cx);
 9200
 9201        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9202        if direction == Direction::Next {
 9203            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9204                self.activate_diagnostics(popover.group_id(), cx);
 9205                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9206                    let primary_range_start = active_diagnostics.primary_range.start;
 9207                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9208                        let mut new_selection = s.newest_anchor().clone();
 9209                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9210                        s.select_anchors(vec![new_selection.clone()]);
 9211                    });
 9212                }
 9213                return;
 9214            }
 9215        }
 9216
 9217        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9218            active_diagnostics
 9219                .primary_range
 9220                .to_offset(&buffer)
 9221                .to_inclusive()
 9222        });
 9223        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9224            if active_primary_range.contains(&selection.head()) {
 9225                *active_primary_range.start()
 9226            } else {
 9227                selection.head()
 9228            }
 9229        } else {
 9230            selection.head()
 9231        };
 9232        let snapshot = self.snapshot(cx);
 9233        loop {
 9234            let diagnostics = if direction == Direction::Prev {
 9235                buffer
 9236                    .diagnostics_in_range(0..search_start, true)
 9237                    .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
 9238                        diagnostic,
 9239                        range: range.to_offset(&buffer),
 9240                    })
 9241                    .collect::<Vec<_>>()
 9242            } else {
 9243                buffer
 9244                    .diagnostics_in_range(search_start..buffer.len(), false)
 9245                    .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
 9246                        diagnostic,
 9247                        range: range.to_offset(&buffer),
 9248                    })
 9249                    .collect::<Vec<_>>()
 9250            }
 9251            .into_iter()
 9252            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9253            let group = diagnostics
 9254                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9255                // be sorted in a stable way
 9256                // skip until we are at current active diagnostic, if it exists
 9257                .skip_while(|entry| {
 9258                    (match direction {
 9259                        Direction::Prev => entry.range.start >= search_start,
 9260                        Direction::Next => entry.range.start <= search_start,
 9261                    }) && self
 9262                        .active_diagnostics
 9263                        .as_ref()
 9264                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9265                })
 9266                .find_map(|entry| {
 9267                    if entry.diagnostic.is_primary
 9268                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9269                        && !entry.range.is_empty()
 9270                        // if we match with the active diagnostic, skip it
 9271                        && Some(entry.diagnostic.group_id)
 9272                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9273                    {
 9274                        Some((entry.range, entry.diagnostic.group_id))
 9275                    } else {
 9276                        None
 9277                    }
 9278                });
 9279
 9280            if let Some((primary_range, group_id)) = group {
 9281                self.activate_diagnostics(group_id, cx);
 9282                if self.active_diagnostics.is_some() {
 9283                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9284                        s.select(vec![Selection {
 9285                            id: selection.id,
 9286                            start: primary_range.start,
 9287                            end: primary_range.start,
 9288                            reversed: false,
 9289                            goal: SelectionGoal::None,
 9290                        }]);
 9291                    });
 9292                }
 9293                break;
 9294            } else {
 9295                // Cycle around to the start of the buffer, potentially moving back to the start of
 9296                // the currently active diagnostic.
 9297                active_primary_range.take();
 9298                if direction == Direction::Prev {
 9299                    if search_start == buffer.len() {
 9300                        break;
 9301                    } else {
 9302                        search_start = buffer.len();
 9303                    }
 9304                } else if search_start == 0 {
 9305                    break;
 9306                } else {
 9307                    search_start = 0;
 9308                }
 9309            }
 9310        }
 9311    }
 9312
 9313    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9314        let snapshot = self.snapshot(cx);
 9315        let selection = self.selections.newest::<Point>(cx);
 9316        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9317    }
 9318
 9319    fn go_to_hunk_after_position(
 9320        &mut self,
 9321        snapshot: &EditorSnapshot,
 9322        position: Point,
 9323        cx: &mut ViewContext<Editor>,
 9324    ) -> Option<MultiBufferDiffHunk> {
 9325        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9326            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9327                snapshot,
 9328                position,
 9329                ix > 0,
 9330                snapshot.diff_map.diff_hunks_in_range(
 9331                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9332                    &snapshot.buffer_snapshot,
 9333                ),
 9334                cx,
 9335            ) {
 9336                return Some(hunk);
 9337            }
 9338        }
 9339        None
 9340    }
 9341
 9342    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9343        let snapshot = self.snapshot(cx);
 9344        let selection = self.selections.newest::<Point>(cx);
 9345        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9346    }
 9347
 9348    fn go_to_hunk_before_position(
 9349        &mut self,
 9350        snapshot: &EditorSnapshot,
 9351        position: Point,
 9352        cx: &mut ViewContext<Editor>,
 9353    ) -> Option<MultiBufferDiffHunk> {
 9354        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9355            .into_iter()
 9356            .enumerate()
 9357        {
 9358            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9359                snapshot,
 9360                position,
 9361                ix > 0,
 9362                snapshot
 9363                    .diff_map
 9364                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9365                cx,
 9366            ) {
 9367                return Some(hunk);
 9368            }
 9369        }
 9370        None
 9371    }
 9372
 9373    fn go_to_next_hunk_in_direction(
 9374        &mut self,
 9375        snapshot: &DisplaySnapshot,
 9376        initial_point: Point,
 9377        is_wrapped: bool,
 9378        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9379        cx: &mut ViewContext<Editor>,
 9380    ) -> Option<MultiBufferDiffHunk> {
 9381        let display_point = initial_point.to_display_point(snapshot);
 9382        let mut hunks = hunks
 9383            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9384            .filter(|(display_hunk, _)| {
 9385                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9386            })
 9387            .dedup();
 9388
 9389        if let Some((display_hunk, hunk)) = hunks.next() {
 9390            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9391                let row = display_hunk.start_display_row();
 9392                let point = DisplayPoint::new(row, 0);
 9393                s.select_display_ranges([point..point]);
 9394            });
 9395
 9396            Some(hunk)
 9397        } else {
 9398            None
 9399        }
 9400    }
 9401
 9402    pub fn go_to_definition(
 9403        &mut self,
 9404        _: &GoToDefinition,
 9405        cx: &mut ViewContext<Self>,
 9406    ) -> Task<Result<Navigated>> {
 9407        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9408        cx.spawn(|editor, mut cx| async move {
 9409            if definition.await? == Navigated::Yes {
 9410                return Ok(Navigated::Yes);
 9411            }
 9412            match editor.update(&mut cx, |editor, cx| {
 9413                editor.find_all_references(&FindAllReferences, cx)
 9414            })? {
 9415                Some(references) => references.await,
 9416                None => Ok(Navigated::No),
 9417            }
 9418        })
 9419    }
 9420
 9421    pub fn go_to_declaration(
 9422        &mut self,
 9423        _: &GoToDeclaration,
 9424        cx: &mut ViewContext<Self>,
 9425    ) -> Task<Result<Navigated>> {
 9426        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9427    }
 9428
 9429    pub fn go_to_declaration_split(
 9430        &mut self,
 9431        _: &GoToDeclaration,
 9432        cx: &mut ViewContext<Self>,
 9433    ) -> Task<Result<Navigated>> {
 9434        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9435    }
 9436
 9437    pub fn go_to_implementation(
 9438        &mut self,
 9439        _: &GoToImplementation,
 9440        cx: &mut ViewContext<Self>,
 9441    ) -> Task<Result<Navigated>> {
 9442        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9443    }
 9444
 9445    pub fn go_to_implementation_split(
 9446        &mut self,
 9447        _: &GoToImplementationSplit,
 9448        cx: &mut ViewContext<Self>,
 9449    ) -> Task<Result<Navigated>> {
 9450        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9451    }
 9452
 9453    pub fn go_to_type_definition(
 9454        &mut self,
 9455        _: &GoToTypeDefinition,
 9456        cx: &mut ViewContext<Self>,
 9457    ) -> Task<Result<Navigated>> {
 9458        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9459    }
 9460
 9461    pub fn go_to_definition_split(
 9462        &mut self,
 9463        _: &GoToDefinitionSplit,
 9464        cx: &mut ViewContext<Self>,
 9465    ) -> Task<Result<Navigated>> {
 9466        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9467    }
 9468
 9469    pub fn go_to_type_definition_split(
 9470        &mut self,
 9471        _: &GoToTypeDefinitionSplit,
 9472        cx: &mut ViewContext<Self>,
 9473    ) -> Task<Result<Navigated>> {
 9474        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9475    }
 9476
 9477    fn go_to_definition_of_kind(
 9478        &mut self,
 9479        kind: GotoDefinitionKind,
 9480        split: bool,
 9481        cx: &mut ViewContext<Self>,
 9482    ) -> Task<Result<Navigated>> {
 9483        let Some(provider) = self.semantics_provider.clone() else {
 9484            return Task::ready(Ok(Navigated::No));
 9485        };
 9486        let head = self.selections.newest::<usize>(cx).head();
 9487        let buffer = self.buffer.read(cx);
 9488        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9489            text_anchor
 9490        } else {
 9491            return Task::ready(Ok(Navigated::No));
 9492        };
 9493
 9494        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9495            return Task::ready(Ok(Navigated::No));
 9496        };
 9497
 9498        cx.spawn(|editor, mut cx| async move {
 9499            let definitions = definitions.await?;
 9500            let navigated = editor
 9501                .update(&mut cx, |editor, cx| {
 9502                    editor.navigate_to_hover_links(
 9503                        Some(kind),
 9504                        definitions
 9505                            .into_iter()
 9506                            .filter(|location| {
 9507                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9508                            })
 9509                            .map(HoverLink::Text)
 9510                            .collect::<Vec<_>>(),
 9511                        split,
 9512                        cx,
 9513                    )
 9514                })?
 9515                .await?;
 9516            anyhow::Ok(navigated)
 9517        })
 9518    }
 9519
 9520    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9521        let selection = self.selections.newest_anchor();
 9522        let head = selection.head();
 9523        let tail = selection.tail();
 9524
 9525        let Some((buffer, start_position)) =
 9526            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9527        else {
 9528            return;
 9529        };
 9530
 9531        let end_position = if head != tail {
 9532            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9533                return;
 9534            };
 9535            Some(pos)
 9536        } else {
 9537            None
 9538        };
 9539
 9540        let url_finder = cx.spawn(|editor, mut cx| async move {
 9541            let url = if let Some(end_pos) = end_position {
 9542                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9543            } else {
 9544                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9545            };
 9546
 9547            if let Some(url) = url {
 9548                editor.update(&mut cx, |_, cx| {
 9549                    cx.open_url(&url);
 9550                })
 9551            } else {
 9552                Ok(())
 9553            }
 9554        });
 9555
 9556        url_finder.detach();
 9557    }
 9558
 9559    pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
 9560        let Some(workspace) = self.workspace() else {
 9561            return;
 9562        };
 9563
 9564        let position = self.selections.newest_anchor().head();
 9565
 9566        let Some((buffer, buffer_position)) =
 9567            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9568        else {
 9569            return;
 9570        };
 9571
 9572        let project = self.project.clone();
 9573
 9574        cx.spawn(|_, mut cx| async move {
 9575            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9576
 9577            if let Some((_, path)) = result {
 9578                workspace
 9579                    .update(&mut cx, |workspace, cx| {
 9580                        workspace.open_resolved_path(path, cx)
 9581                    })?
 9582                    .await?;
 9583            }
 9584            anyhow::Ok(())
 9585        })
 9586        .detach();
 9587    }
 9588
 9589    pub(crate) fn navigate_to_hover_links(
 9590        &mut self,
 9591        kind: Option<GotoDefinitionKind>,
 9592        mut definitions: Vec<HoverLink>,
 9593        split: bool,
 9594        cx: &mut ViewContext<Editor>,
 9595    ) -> Task<Result<Navigated>> {
 9596        // If there is one definition, just open it directly
 9597        if definitions.len() == 1 {
 9598            let definition = definitions.pop().unwrap();
 9599
 9600            enum TargetTaskResult {
 9601                Location(Option<Location>),
 9602                AlreadyNavigated,
 9603            }
 9604
 9605            let target_task = match definition {
 9606                HoverLink::Text(link) => {
 9607                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9608                }
 9609                HoverLink::InlayHint(lsp_location, server_id) => {
 9610                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9611                    cx.background_executor().spawn(async move {
 9612                        let location = computation.await?;
 9613                        Ok(TargetTaskResult::Location(location))
 9614                    })
 9615                }
 9616                HoverLink::Url(url) => {
 9617                    cx.open_url(&url);
 9618                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9619                }
 9620                HoverLink::File(path) => {
 9621                    if let Some(workspace) = self.workspace() {
 9622                        cx.spawn(|_, mut cx| async move {
 9623                            workspace
 9624                                .update(&mut cx, |workspace, cx| {
 9625                                    workspace.open_resolved_path(path, cx)
 9626                                })?
 9627                                .await
 9628                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9629                        })
 9630                    } else {
 9631                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9632                    }
 9633                }
 9634            };
 9635            cx.spawn(|editor, mut cx| async move {
 9636                let target = match target_task.await.context("target resolution task")? {
 9637                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9638                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9639                    TargetTaskResult::Location(Some(target)) => target,
 9640                };
 9641
 9642                editor.update(&mut cx, |editor, cx| {
 9643                    let Some(workspace) = editor.workspace() else {
 9644                        return Navigated::No;
 9645                    };
 9646                    let pane = workspace.read(cx).active_pane().clone();
 9647
 9648                    let range = target.range.to_offset(target.buffer.read(cx));
 9649                    let range = editor.range_for_match(&range);
 9650
 9651                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9652                        let buffer = target.buffer.read(cx);
 9653                        let range = check_multiline_range(buffer, range);
 9654                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9655                            s.select_ranges([range]);
 9656                        });
 9657                    } else {
 9658                        cx.window_context().defer(move |cx| {
 9659                            let target_editor: View<Self> =
 9660                                workspace.update(cx, |workspace, cx| {
 9661                                    let pane = if split {
 9662                                        workspace.adjacent_pane(cx)
 9663                                    } else {
 9664                                        workspace.active_pane().clone()
 9665                                    };
 9666
 9667                                    workspace.open_project_item(
 9668                                        pane,
 9669                                        target.buffer.clone(),
 9670                                        true,
 9671                                        true,
 9672                                        cx,
 9673                                    )
 9674                                });
 9675                            target_editor.update(cx, |target_editor, cx| {
 9676                                // When selecting a definition in a different buffer, disable the nav history
 9677                                // to avoid creating a history entry at the previous cursor location.
 9678                                pane.update(cx, |pane, _| pane.disable_history());
 9679                                let buffer = target.buffer.read(cx);
 9680                                let range = check_multiline_range(buffer, range);
 9681                                target_editor.change_selections(
 9682                                    Some(Autoscroll::focused()),
 9683                                    cx,
 9684                                    |s| {
 9685                                        s.select_ranges([range]);
 9686                                    },
 9687                                );
 9688                                pane.update(cx, |pane, _| pane.enable_history());
 9689                            });
 9690                        });
 9691                    }
 9692                    Navigated::Yes
 9693                })
 9694            })
 9695        } else if !definitions.is_empty() {
 9696            cx.spawn(|editor, mut cx| async move {
 9697                let (title, location_tasks, workspace) = editor
 9698                    .update(&mut cx, |editor, cx| {
 9699                        let tab_kind = match kind {
 9700                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9701                            _ => "Definitions",
 9702                        };
 9703                        let title = definitions
 9704                            .iter()
 9705                            .find_map(|definition| match definition {
 9706                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9707                                    let buffer = origin.buffer.read(cx);
 9708                                    format!(
 9709                                        "{} for {}",
 9710                                        tab_kind,
 9711                                        buffer
 9712                                            .text_for_range(origin.range.clone())
 9713                                            .collect::<String>()
 9714                                    )
 9715                                }),
 9716                                HoverLink::InlayHint(_, _) => None,
 9717                                HoverLink::Url(_) => None,
 9718                                HoverLink::File(_) => None,
 9719                            })
 9720                            .unwrap_or(tab_kind.to_string());
 9721                        let location_tasks = definitions
 9722                            .into_iter()
 9723                            .map(|definition| match definition {
 9724                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9725                                HoverLink::InlayHint(lsp_location, server_id) => {
 9726                                    editor.compute_target_location(lsp_location, server_id, cx)
 9727                                }
 9728                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9729                                HoverLink::File(_) => Task::ready(Ok(None)),
 9730                            })
 9731                            .collect::<Vec<_>>();
 9732                        (title, location_tasks, editor.workspace().clone())
 9733                    })
 9734                    .context("location tasks preparation")?;
 9735
 9736                let locations = future::join_all(location_tasks)
 9737                    .await
 9738                    .into_iter()
 9739                    .filter_map(|location| location.transpose())
 9740                    .collect::<Result<_>>()
 9741                    .context("location tasks")?;
 9742
 9743                let Some(workspace) = workspace else {
 9744                    return Ok(Navigated::No);
 9745                };
 9746                let opened = workspace
 9747                    .update(&mut cx, |workspace, cx| {
 9748                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9749                    })
 9750                    .ok();
 9751
 9752                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9753            })
 9754        } else {
 9755            Task::ready(Ok(Navigated::No))
 9756        }
 9757    }
 9758
 9759    fn compute_target_location(
 9760        &self,
 9761        lsp_location: lsp::Location,
 9762        server_id: LanguageServerId,
 9763        cx: &mut ViewContext<Self>,
 9764    ) -> Task<anyhow::Result<Option<Location>>> {
 9765        let Some(project) = self.project.clone() else {
 9766            return Task::ready(Ok(None));
 9767        };
 9768
 9769        cx.spawn(move |editor, mut cx| async move {
 9770            let location_task = editor.update(&mut cx, |_, cx| {
 9771                project.update(cx, |project, cx| {
 9772                    let language_server_name = project
 9773                        .language_server_statuses(cx)
 9774                        .find(|(id, _)| server_id == *id)
 9775                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9776                    language_server_name.map(|language_server_name| {
 9777                        project.open_local_buffer_via_lsp(
 9778                            lsp_location.uri.clone(),
 9779                            server_id,
 9780                            language_server_name,
 9781                            cx,
 9782                        )
 9783                    })
 9784                })
 9785            })?;
 9786            let location = match location_task {
 9787                Some(task) => Some({
 9788                    let target_buffer_handle = task.await.context("open local buffer")?;
 9789                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9790                        let target_start = target_buffer
 9791                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9792                        let target_end = target_buffer
 9793                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9794                        target_buffer.anchor_after(target_start)
 9795                            ..target_buffer.anchor_before(target_end)
 9796                    })?;
 9797                    Location {
 9798                        buffer: target_buffer_handle,
 9799                        range,
 9800                    }
 9801                }),
 9802                None => None,
 9803            };
 9804            Ok(location)
 9805        })
 9806    }
 9807
 9808    pub fn find_all_references(
 9809        &mut self,
 9810        _: &FindAllReferences,
 9811        cx: &mut ViewContext<Self>,
 9812    ) -> Option<Task<Result<Navigated>>> {
 9813        let selection = self.selections.newest::<usize>(cx);
 9814        let multi_buffer = self.buffer.read(cx);
 9815        let head = selection.head();
 9816
 9817        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9818        let head_anchor = multi_buffer_snapshot.anchor_at(
 9819            head,
 9820            if head < selection.tail() {
 9821                Bias::Right
 9822            } else {
 9823                Bias::Left
 9824            },
 9825        );
 9826
 9827        match self
 9828            .find_all_references_task_sources
 9829            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9830        {
 9831            Ok(_) => {
 9832                log::info!(
 9833                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9834                );
 9835                return None;
 9836            }
 9837            Err(i) => {
 9838                self.find_all_references_task_sources.insert(i, head_anchor);
 9839            }
 9840        }
 9841
 9842        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9843        let workspace = self.workspace()?;
 9844        let project = workspace.read(cx).project().clone();
 9845        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9846        Some(cx.spawn(|editor, mut cx| async move {
 9847            let _cleanup = defer({
 9848                let mut cx = cx.clone();
 9849                move || {
 9850                    let _ = editor.update(&mut cx, |editor, _| {
 9851                        if let Ok(i) =
 9852                            editor
 9853                                .find_all_references_task_sources
 9854                                .binary_search_by(|anchor| {
 9855                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9856                                })
 9857                        {
 9858                            editor.find_all_references_task_sources.remove(i);
 9859                        }
 9860                    });
 9861                }
 9862            });
 9863
 9864            let locations = references.await?;
 9865            if locations.is_empty() {
 9866                return anyhow::Ok(Navigated::No);
 9867            }
 9868
 9869            workspace.update(&mut cx, |workspace, cx| {
 9870                let title = locations
 9871                    .first()
 9872                    .as_ref()
 9873                    .map(|location| {
 9874                        let buffer = location.buffer.read(cx);
 9875                        format!(
 9876                            "References to `{}`",
 9877                            buffer
 9878                                .text_for_range(location.range.clone())
 9879                                .collect::<String>()
 9880                        )
 9881                    })
 9882                    .unwrap();
 9883                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9884                Navigated::Yes
 9885            })
 9886        }))
 9887    }
 9888
 9889    /// Opens a multibuffer with the given project locations in it
 9890    pub fn open_locations_in_multibuffer(
 9891        workspace: &mut Workspace,
 9892        mut locations: Vec<Location>,
 9893        title: String,
 9894        split: bool,
 9895        cx: &mut ViewContext<Workspace>,
 9896    ) {
 9897        // If there are multiple definitions, open them in a multibuffer
 9898        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9899        let mut locations = locations.into_iter().peekable();
 9900        let mut ranges_to_highlight = Vec::new();
 9901        let capability = workspace.project().read(cx).capability();
 9902
 9903        let excerpt_buffer = cx.new_model(|cx| {
 9904            let mut multibuffer = MultiBuffer::new(capability);
 9905            while let Some(location) = locations.next() {
 9906                let buffer = location.buffer.read(cx);
 9907                let mut ranges_for_buffer = Vec::new();
 9908                let range = location.range.to_offset(buffer);
 9909                ranges_for_buffer.push(range.clone());
 9910
 9911                while let Some(next_location) = locations.peek() {
 9912                    if next_location.buffer == location.buffer {
 9913                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9914                        locations.next();
 9915                    } else {
 9916                        break;
 9917                    }
 9918                }
 9919
 9920                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9921                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9922                    location.buffer.clone(),
 9923                    ranges_for_buffer,
 9924                    DEFAULT_MULTIBUFFER_CONTEXT,
 9925                    cx,
 9926                ))
 9927            }
 9928
 9929            multibuffer.with_title(title)
 9930        });
 9931
 9932        let editor = cx.new_view(|cx| {
 9933            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9934        });
 9935        editor.update(cx, |editor, cx| {
 9936            if let Some(first_range) = ranges_to_highlight.first() {
 9937                editor.change_selections(None, cx, |selections| {
 9938                    selections.clear_disjoint();
 9939                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9940                });
 9941            }
 9942            editor.highlight_background::<Self>(
 9943                &ranges_to_highlight,
 9944                |theme| theme.editor_highlighted_line_background,
 9945                cx,
 9946            );
 9947            editor.register_buffers_with_language_servers(cx);
 9948        });
 9949
 9950        let item = Box::new(editor);
 9951        let item_id = item.item_id();
 9952
 9953        if split {
 9954            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9955        } else {
 9956            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9957                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9958                    pane.close_current_preview_item(cx)
 9959                } else {
 9960                    None
 9961                }
 9962            });
 9963            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9964        }
 9965        workspace.active_pane().update(cx, |pane, cx| {
 9966            pane.set_preview_item_id(Some(item_id), cx);
 9967        });
 9968    }
 9969
 9970    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9971        use language::ToOffset as _;
 9972
 9973        let provider = self.semantics_provider.clone()?;
 9974        let selection = self.selections.newest_anchor().clone();
 9975        let (cursor_buffer, cursor_buffer_position) = self
 9976            .buffer
 9977            .read(cx)
 9978            .text_anchor_for_position(selection.head(), cx)?;
 9979        let (tail_buffer, cursor_buffer_position_end) = self
 9980            .buffer
 9981            .read(cx)
 9982            .text_anchor_for_position(selection.tail(), cx)?;
 9983        if tail_buffer != cursor_buffer {
 9984            return None;
 9985        }
 9986
 9987        let snapshot = cursor_buffer.read(cx).snapshot();
 9988        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9989        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9990        let prepare_rename = provider
 9991            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9992            .unwrap_or_else(|| Task::ready(Ok(None)));
 9993        drop(snapshot);
 9994
 9995        Some(cx.spawn(|this, mut cx| async move {
 9996            let rename_range = if let Some(range) = prepare_rename.await? {
 9997                Some(range)
 9998            } else {
 9999                this.update(&mut cx, |this, cx| {
10000                    let buffer = this.buffer.read(cx).snapshot(cx);
10001                    let mut buffer_highlights = this
10002                        .document_highlights_for_position(selection.head(), &buffer)
10003                        .filter(|highlight| {
10004                            highlight.start.excerpt_id == selection.head().excerpt_id
10005                                && highlight.end.excerpt_id == selection.head().excerpt_id
10006                        });
10007                    buffer_highlights
10008                        .next()
10009                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10010                })?
10011            };
10012            if let Some(rename_range) = rename_range {
10013                this.update(&mut cx, |this, cx| {
10014                    let snapshot = cursor_buffer.read(cx).snapshot();
10015                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10016                    let cursor_offset_in_rename_range =
10017                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10018                    let cursor_offset_in_rename_range_end =
10019                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10020
10021                    this.take_rename(false, cx);
10022                    let buffer = this.buffer.read(cx).read(cx);
10023                    let cursor_offset = selection.head().to_offset(&buffer);
10024                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10025                    let rename_end = rename_start + rename_buffer_range.len();
10026                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10027                    let mut old_highlight_id = None;
10028                    let old_name: Arc<str> = buffer
10029                        .chunks(rename_start..rename_end, true)
10030                        .map(|chunk| {
10031                            if old_highlight_id.is_none() {
10032                                old_highlight_id = chunk.syntax_highlight_id;
10033                            }
10034                            chunk.text
10035                        })
10036                        .collect::<String>()
10037                        .into();
10038
10039                    drop(buffer);
10040
10041                    // Position the selection in the rename editor so that it matches the current selection.
10042                    this.show_local_selections = false;
10043                    let rename_editor = cx.new_view(|cx| {
10044                        let mut editor = Editor::single_line(cx);
10045                        editor.buffer.update(cx, |buffer, cx| {
10046                            buffer.edit([(0..0, old_name.clone())], None, cx)
10047                        });
10048                        let rename_selection_range = match cursor_offset_in_rename_range
10049                            .cmp(&cursor_offset_in_rename_range_end)
10050                        {
10051                            Ordering::Equal => {
10052                                editor.select_all(&SelectAll, cx);
10053                                return editor;
10054                            }
10055                            Ordering::Less => {
10056                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10057                            }
10058                            Ordering::Greater => {
10059                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10060                            }
10061                        };
10062                        if rename_selection_range.end > old_name.len() {
10063                            editor.select_all(&SelectAll, cx);
10064                        } else {
10065                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10066                                s.select_ranges([rename_selection_range]);
10067                            });
10068                        }
10069                        editor
10070                    });
10071                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10072                        if e == &EditorEvent::Focused {
10073                            cx.emit(EditorEvent::FocusedIn)
10074                        }
10075                    })
10076                    .detach();
10077
10078                    let write_highlights =
10079                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10080                    let read_highlights =
10081                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10082                    let ranges = write_highlights
10083                        .iter()
10084                        .flat_map(|(_, ranges)| ranges.iter())
10085                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10086                        .cloned()
10087                        .collect();
10088
10089                    this.highlight_text::<Rename>(
10090                        ranges,
10091                        HighlightStyle {
10092                            fade_out: Some(0.6),
10093                            ..Default::default()
10094                        },
10095                        cx,
10096                    );
10097                    let rename_focus_handle = rename_editor.focus_handle(cx);
10098                    cx.focus(&rename_focus_handle);
10099                    let block_id = this.insert_blocks(
10100                        [BlockProperties {
10101                            style: BlockStyle::Flex,
10102                            placement: BlockPlacement::Below(range.start),
10103                            height: 1,
10104                            render: Arc::new({
10105                                let rename_editor = rename_editor.clone();
10106                                move |cx: &mut BlockContext| {
10107                                    let mut text_style = cx.editor_style.text.clone();
10108                                    if let Some(highlight_style) = old_highlight_id
10109                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10110                                    {
10111                                        text_style = text_style.highlight(highlight_style);
10112                                    }
10113                                    div()
10114                                        .block_mouse_down()
10115                                        .pl(cx.anchor_x)
10116                                        .child(EditorElement::new(
10117                                            &rename_editor,
10118                                            EditorStyle {
10119                                                background: cx.theme().system().transparent,
10120                                                local_player: cx.editor_style.local_player,
10121                                                text: text_style,
10122                                                scrollbar_width: cx.editor_style.scrollbar_width,
10123                                                syntax: cx.editor_style.syntax.clone(),
10124                                                status: cx.editor_style.status.clone(),
10125                                                inlay_hints_style: HighlightStyle {
10126                                                    font_weight: Some(FontWeight::BOLD),
10127                                                    ..make_inlay_hints_style(cx)
10128                                                },
10129                                                inline_completion_styles: make_suggestion_styles(
10130                                                    cx,
10131                                                ),
10132                                                ..EditorStyle::default()
10133                                            },
10134                                        ))
10135                                        .into_any_element()
10136                                }
10137                            }),
10138                            priority: 0,
10139                        }],
10140                        Some(Autoscroll::fit()),
10141                        cx,
10142                    )[0];
10143                    this.pending_rename = Some(RenameState {
10144                        range,
10145                        old_name,
10146                        editor: rename_editor,
10147                        block_id,
10148                    });
10149                })?;
10150            }
10151
10152            Ok(())
10153        }))
10154    }
10155
10156    pub fn confirm_rename(
10157        &mut self,
10158        _: &ConfirmRename,
10159        cx: &mut ViewContext<Self>,
10160    ) -> Option<Task<Result<()>>> {
10161        let rename = self.take_rename(false, cx)?;
10162        let workspace = self.workspace()?.downgrade();
10163        let (buffer, start) = self
10164            .buffer
10165            .read(cx)
10166            .text_anchor_for_position(rename.range.start, cx)?;
10167        let (end_buffer, _) = self
10168            .buffer
10169            .read(cx)
10170            .text_anchor_for_position(rename.range.end, cx)?;
10171        if buffer != end_buffer {
10172            return None;
10173        }
10174
10175        let old_name = rename.old_name;
10176        let new_name = rename.editor.read(cx).text(cx);
10177
10178        let rename = self.semantics_provider.as_ref()?.perform_rename(
10179            &buffer,
10180            start,
10181            new_name.clone(),
10182            cx,
10183        )?;
10184
10185        Some(cx.spawn(|editor, mut cx| async move {
10186            let project_transaction = rename.await?;
10187            Self::open_project_transaction(
10188                &editor,
10189                workspace,
10190                project_transaction,
10191                format!("Rename: {}{}", old_name, new_name),
10192                cx.clone(),
10193            )
10194            .await?;
10195
10196            editor.update(&mut cx, |editor, cx| {
10197                editor.refresh_document_highlights(cx);
10198            })?;
10199            Ok(())
10200        }))
10201    }
10202
10203    fn take_rename(
10204        &mut self,
10205        moving_cursor: bool,
10206        cx: &mut ViewContext<Self>,
10207    ) -> Option<RenameState> {
10208        let rename = self.pending_rename.take()?;
10209        if rename.editor.focus_handle(cx).is_focused(cx) {
10210            cx.focus(&self.focus_handle);
10211        }
10212
10213        self.remove_blocks(
10214            [rename.block_id].into_iter().collect(),
10215            Some(Autoscroll::fit()),
10216            cx,
10217        );
10218        self.clear_highlights::<Rename>(cx);
10219        self.show_local_selections = true;
10220
10221        if moving_cursor {
10222            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10223                editor.selections.newest::<usize>(cx).head()
10224            });
10225
10226            // Update the selection to match the position of the selection inside
10227            // the rename editor.
10228            let snapshot = self.buffer.read(cx).read(cx);
10229            let rename_range = rename.range.to_offset(&snapshot);
10230            let cursor_in_editor = snapshot
10231                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10232                .min(rename_range.end);
10233            drop(snapshot);
10234
10235            self.change_selections(None, cx, |s| {
10236                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10237            });
10238        } else {
10239            self.refresh_document_highlights(cx);
10240        }
10241
10242        Some(rename)
10243    }
10244
10245    pub fn pending_rename(&self) -> Option<&RenameState> {
10246        self.pending_rename.as_ref()
10247    }
10248
10249    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10250        let project = match &self.project {
10251            Some(project) => project.clone(),
10252            None => return None,
10253        };
10254
10255        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10256    }
10257
10258    fn format_selections(
10259        &mut self,
10260        _: &FormatSelections,
10261        cx: &mut ViewContext<Self>,
10262    ) -> Option<Task<Result<()>>> {
10263        let project = match &self.project {
10264            Some(project) => project.clone(),
10265            None => return None,
10266        };
10267
10268        let ranges = self
10269            .selections
10270            .all_adjusted(cx)
10271            .into_iter()
10272            .map(|selection| selection.range())
10273            .collect_vec();
10274
10275        Some(self.perform_format(
10276            project,
10277            FormatTrigger::Manual,
10278            FormatTarget::Ranges(ranges),
10279            cx,
10280        ))
10281    }
10282
10283    fn perform_format(
10284        &mut self,
10285        project: Model<Project>,
10286        trigger: FormatTrigger,
10287        target: FormatTarget,
10288        cx: &mut ViewContext<Self>,
10289    ) -> Task<Result<()>> {
10290        let buffer = self.buffer.clone();
10291        let (buffers, target) = match target {
10292            FormatTarget::Buffers => {
10293                let mut buffers = buffer.read(cx).all_buffers();
10294                if trigger == FormatTrigger::Save {
10295                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
10296                }
10297                (buffers, LspFormatTarget::Buffers)
10298            }
10299            FormatTarget::Ranges(selection_ranges) => {
10300                let multi_buffer = buffer.read(cx);
10301                let snapshot = multi_buffer.read(cx);
10302                let mut buffers = HashSet::default();
10303                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10304                    BTreeMap::new();
10305                for selection_range in selection_ranges {
10306                    for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10307                    {
10308                        let buffer_id = excerpt.buffer_id();
10309                        let start = excerpt.buffer().anchor_before(buffer_range.start);
10310                        let end = excerpt.buffer().anchor_after(buffer_range.end);
10311                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10312                        buffer_id_to_ranges
10313                            .entry(buffer_id)
10314                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10315                            .or_insert_with(|| vec![start..end]);
10316                    }
10317                }
10318                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10319            }
10320        };
10321
10322        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10323        let format = project.update(cx, |project, cx| {
10324            project.format(buffers, target, true, trigger, cx)
10325        });
10326
10327        cx.spawn(|_, mut cx| async move {
10328            let transaction = futures::select_biased! {
10329                () = timeout => {
10330                    log::warn!("timed out waiting for formatting");
10331                    None
10332                }
10333                transaction = format.log_err().fuse() => transaction,
10334            };
10335
10336            buffer
10337                .update(&mut cx, |buffer, cx| {
10338                    if let Some(transaction) = transaction {
10339                        if !buffer.is_singleton() {
10340                            buffer.push_transaction(&transaction.0, cx);
10341                        }
10342                    }
10343
10344                    cx.notify();
10345                })
10346                .ok();
10347
10348            Ok(())
10349        })
10350    }
10351
10352    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10353        if let Some(project) = self.project.clone() {
10354            self.buffer.update(cx, |multi_buffer, cx| {
10355                project.update(cx, |project, cx| {
10356                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10357                });
10358            })
10359        }
10360    }
10361
10362    fn cancel_language_server_work(
10363        &mut self,
10364        _: &actions::CancelLanguageServerWork,
10365        cx: &mut ViewContext<Self>,
10366    ) {
10367        if let Some(project) = self.project.clone() {
10368            self.buffer.update(cx, |multi_buffer, cx| {
10369                project.update(cx, |project, cx| {
10370                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10371                });
10372            })
10373        }
10374    }
10375
10376    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10377        cx.show_character_palette();
10378    }
10379
10380    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10381        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10382            let buffer = self.buffer.read(cx).snapshot(cx);
10383            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10384            let is_valid = buffer
10385                .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10386                .any(|entry| {
10387                    let range = entry.range.to_offset(&buffer);
10388                    entry.diagnostic.is_primary
10389                        && !range.is_empty()
10390                        && range.start == primary_range_start
10391                        && entry.diagnostic.message == active_diagnostics.primary_message
10392                });
10393
10394            if is_valid != active_diagnostics.is_valid {
10395                active_diagnostics.is_valid = is_valid;
10396                let mut new_styles = HashMap::default();
10397                for (block_id, diagnostic) in &active_diagnostics.blocks {
10398                    new_styles.insert(
10399                        *block_id,
10400                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10401                    );
10402                }
10403                self.display_map.update(cx, |display_map, _cx| {
10404                    display_map.replace_blocks(new_styles)
10405                });
10406            }
10407        }
10408    }
10409
10410    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10411        self.dismiss_diagnostics(cx);
10412        let snapshot = self.snapshot(cx);
10413        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10414            let buffer = self.buffer.read(cx).snapshot(cx);
10415
10416            let mut primary_range = None;
10417            let mut primary_message = None;
10418            let mut group_end = Point::zero();
10419            let diagnostic_group = buffer
10420                .diagnostic_group(group_id)
10421                .filter_map(|entry| {
10422                    let start = entry.range.start.to_point(&buffer);
10423                    let end = entry.range.end.to_point(&buffer);
10424                    if snapshot.is_line_folded(MultiBufferRow(start.row))
10425                        && (start.row == end.row
10426                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
10427                    {
10428                        return None;
10429                    }
10430                    if end > group_end {
10431                        group_end = end;
10432                    }
10433                    if entry.diagnostic.is_primary {
10434                        primary_range = Some(entry.range.clone());
10435                        primary_message = Some(entry.diagnostic.message.clone());
10436                    }
10437                    Some(entry)
10438                })
10439                .collect::<Vec<_>>();
10440            let primary_range = primary_range?;
10441            let primary_message = primary_message?;
10442
10443            let blocks = display_map
10444                .insert_blocks(
10445                    diagnostic_group.iter().map(|entry| {
10446                        let diagnostic = entry.diagnostic.clone();
10447                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10448                        BlockProperties {
10449                            style: BlockStyle::Fixed,
10450                            placement: BlockPlacement::Below(
10451                                buffer.anchor_after(entry.range.start),
10452                            ),
10453                            height: message_height,
10454                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10455                            priority: 0,
10456                        }
10457                    }),
10458                    cx,
10459                )
10460                .into_iter()
10461                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10462                .collect();
10463
10464            Some(ActiveDiagnosticGroup {
10465                primary_range,
10466                primary_message,
10467                group_id,
10468                blocks,
10469                is_valid: true,
10470            })
10471        });
10472    }
10473
10474    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10475        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10476            self.display_map.update(cx, |display_map, cx| {
10477                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10478            });
10479            cx.notify();
10480        }
10481    }
10482
10483    pub fn set_selections_from_remote(
10484        &mut self,
10485        selections: Vec<Selection<Anchor>>,
10486        pending_selection: Option<Selection<Anchor>>,
10487        cx: &mut ViewContext<Self>,
10488    ) {
10489        let old_cursor_position = self.selections.newest_anchor().head();
10490        self.selections.change_with(cx, |s| {
10491            s.select_anchors(selections);
10492            if let Some(pending_selection) = pending_selection {
10493                s.set_pending(pending_selection, SelectMode::Character);
10494            } else {
10495                s.clear_pending();
10496            }
10497        });
10498        self.selections_did_change(false, &old_cursor_position, true, cx);
10499    }
10500
10501    fn push_to_selection_history(&mut self) {
10502        self.selection_history.push(SelectionHistoryEntry {
10503            selections: self.selections.disjoint_anchors(),
10504            select_next_state: self.select_next_state.clone(),
10505            select_prev_state: self.select_prev_state.clone(),
10506            add_selections_state: self.add_selections_state.clone(),
10507        });
10508    }
10509
10510    pub fn transact(
10511        &mut self,
10512        cx: &mut ViewContext<Self>,
10513        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10514    ) -> Option<TransactionId> {
10515        self.start_transaction_at(Instant::now(), cx);
10516        update(self, cx);
10517        self.end_transaction_at(Instant::now(), cx)
10518    }
10519
10520    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10521        self.end_selection(cx);
10522        if let Some(tx_id) = self
10523            .buffer
10524            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10525        {
10526            self.selection_history
10527                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10528            cx.emit(EditorEvent::TransactionBegun {
10529                transaction_id: tx_id,
10530            })
10531        }
10532    }
10533
10534    pub fn end_transaction_at(
10535        &mut self,
10536        now: Instant,
10537        cx: &mut ViewContext<Self>,
10538    ) -> Option<TransactionId> {
10539        if let Some(transaction_id) = self
10540            .buffer
10541            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10542        {
10543            if let Some((_, end_selections)) =
10544                self.selection_history.transaction_mut(transaction_id)
10545            {
10546                *end_selections = Some(self.selections.disjoint_anchors());
10547            } else {
10548                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10549            }
10550
10551            cx.emit(EditorEvent::Edited { transaction_id });
10552            Some(transaction_id)
10553        } else {
10554            None
10555        }
10556    }
10557
10558    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10559        if self.is_singleton(cx) {
10560            let selection = self.selections.newest::<Point>(cx);
10561
10562            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10563            let range = if selection.is_empty() {
10564                let point = selection.head().to_display_point(&display_map);
10565                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10566                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10567                    .to_point(&display_map);
10568                start..end
10569            } else {
10570                selection.range()
10571            };
10572            if display_map.folds_in_range(range).next().is_some() {
10573                self.unfold_lines(&Default::default(), cx)
10574            } else {
10575                self.fold(&Default::default(), cx)
10576            }
10577        } else {
10578            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10579            let mut toggled_buffers = HashSet::default();
10580            for (_, buffer_snapshot, _) in
10581                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10582            {
10583                let buffer_id = buffer_snapshot.remote_id();
10584                if toggled_buffers.insert(buffer_id) {
10585                    if self.buffer_folded(buffer_id, cx) {
10586                        self.unfold_buffer(buffer_id, cx);
10587                    } else {
10588                        self.fold_buffer(buffer_id, cx);
10589                    }
10590                }
10591            }
10592        }
10593    }
10594
10595    pub fn toggle_fold_recursive(
10596        &mut self,
10597        _: &actions::ToggleFoldRecursive,
10598        cx: &mut ViewContext<Self>,
10599    ) {
10600        let selection = self.selections.newest::<Point>(cx);
10601
10602        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10603        let range = if selection.is_empty() {
10604            let point = selection.head().to_display_point(&display_map);
10605            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10606            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10607                .to_point(&display_map);
10608            start..end
10609        } else {
10610            selection.range()
10611        };
10612        if display_map.folds_in_range(range).next().is_some() {
10613            self.unfold_recursive(&Default::default(), cx)
10614        } else {
10615            self.fold_recursive(&Default::default(), cx)
10616        }
10617    }
10618
10619    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10620        if self.is_singleton(cx) {
10621            let mut to_fold = Vec::new();
10622            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10623            let selections = self.selections.all_adjusted(cx);
10624
10625            for selection in selections {
10626                let range = selection.range().sorted();
10627                let buffer_start_row = range.start.row;
10628
10629                if range.start.row != range.end.row {
10630                    let mut found = false;
10631                    let mut row = range.start.row;
10632                    while row <= range.end.row {
10633                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10634                        {
10635                            found = true;
10636                            row = crease.range().end.row + 1;
10637                            to_fold.push(crease);
10638                        } else {
10639                            row += 1
10640                        }
10641                    }
10642                    if found {
10643                        continue;
10644                    }
10645                }
10646
10647                for row in (0..=range.start.row).rev() {
10648                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10649                        if crease.range().end.row >= buffer_start_row {
10650                            to_fold.push(crease);
10651                            if row <= range.start.row {
10652                                break;
10653                            }
10654                        }
10655                    }
10656                }
10657            }
10658
10659            self.fold_creases(to_fold, true, cx);
10660        } else {
10661            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10662            let mut folded_buffers = HashSet::default();
10663            for (_, buffer_snapshot, _) in
10664                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10665            {
10666                let buffer_id = buffer_snapshot.remote_id();
10667                if folded_buffers.insert(buffer_id) {
10668                    self.fold_buffer(buffer_id, cx);
10669                }
10670            }
10671        }
10672    }
10673
10674    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10675        if !self.buffer.read(cx).is_singleton() {
10676            return;
10677        }
10678
10679        let fold_at_level = fold_at.level;
10680        let snapshot = self.buffer.read(cx).snapshot(cx);
10681        let mut to_fold = Vec::new();
10682        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10683
10684        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10685            while start_row < end_row {
10686                match self
10687                    .snapshot(cx)
10688                    .crease_for_buffer_row(MultiBufferRow(start_row))
10689                {
10690                    Some(crease) => {
10691                        let nested_start_row = crease.range().start.row + 1;
10692                        let nested_end_row = crease.range().end.row;
10693
10694                        if current_level < fold_at_level {
10695                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10696                        } else if current_level == fold_at_level {
10697                            to_fold.push(crease);
10698                        }
10699
10700                        start_row = nested_end_row + 1;
10701                    }
10702                    None => start_row += 1,
10703                }
10704            }
10705        }
10706
10707        self.fold_creases(to_fold, true, cx);
10708    }
10709
10710    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10711        if self.buffer.read(cx).is_singleton() {
10712            let mut fold_ranges = Vec::new();
10713            let snapshot = self.buffer.read(cx).snapshot(cx);
10714
10715            for row in 0..snapshot.max_row().0 {
10716                if let Some(foldable_range) =
10717                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10718                {
10719                    fold_ranges.push(foldable_range);
10720                }
10721            }
10722
10723            self.fold_creases(fold_ranges, true, cx);
10724        } else {
10725            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10726                editor
10727                    .update(&mut cx, |editor, cx| {
10728                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10729                            editor.fold_buffer(buffer_id, cx);
10730                        }
10731                    })
10732                    .ok();
10733            });
10734        }
10735    }
10736
10737    pub fn fold_function_bodies(
10738        &mut self,
10739        _: &actions::FoldFunctionBodies,
10740        cx: &mut ViewContext<Self>,
10741    ) {
10742        let snapshot = self.buffer.read(cx).snapshot(cx);
10743        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10744            return;
10745        };
10746        let creases = buffer
10747            .function_body_fold_ranges(0..buffer.len())
10748            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10749            .collect();
10750
10751        self.fold_creases(creases, true, cx);
10752    }
10753
10754    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10755        let mut to_fold = Vec::new();
10756        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10757        let selections = self.selections.all_adjusted(cx);
10758
10759        for selection in selections {
10760            let range = selection.range().sorted();
10761            let buffer_start_row = range.start.row;
10762
10763            if range.start.row != range.end.row {
10764                let mut found = false;
10765                for row in range.start.row..=range.end.row {
10766                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10767                        found = true;
10768                        to_fold.push(crease);
10769                    }
10770                }
10771                if found {
10772                    continue;
10773                }
10774            }
10775
10776            for row in (0..=range.start.row).rev() {
10777                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10778                    if crease.range().end.row >= buffer_start_row {
10779                        to_fold.push(crease);
10780                    } else {
10781                        break;
10782                    }
10783                }
10784            }
10785        }
10786
10787        self.fold_creases(to_fold, true, cx);
10788    }
10789
10790    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10791        let buffer_row = fold_at.buffer_row;
10792        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10793
10794        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10795            let autoscroll = self
10796                .selections
10797                .all::<Point>(cx)
10798                .iter()
10799                .any(|selection| crease.range().overlaps(&selection.range()));
10800
10801            self.fold_creases(vec![crease], autoscroll, cx);
10802        }
10803    }
10804
10805    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10806        if self.is_singleton(cx) {
10807            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10808            let buffer = &display_map.buffer_snapshot;
10809            let selections = self.selections.all::<Point>(cx);
10810            let ranges = selections
10811                .iter()
10812                .map(|s| {
10813                    let range = s.display_range(&display_map).sorted();
10814                    let mut start = range.start.to_point(&display_map);
10815                    let mut end = range.end.to_point(&display_map);
10816                    start.column = 0;
10817                    end.column = buffer.line_len(MultiBufferRow(end.row));
10818                    start..end
10819                })
10820                .collect::<Vec<_>>();
10821
10822            self.unfold_ranges(&ranges, true, true, cx);
10823        } else {
10824            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10825            let mut unfolded_buffers = HashSet::default();
10826            for (_, buffer_snapshot, _) in
10827                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10828            {
10829                let buffer_id = buffer_snapshot.remote_id();
10830                if unfolded_buffers.insert(buffer_id) {
10831                    self.unfold_buffer(buffer_id, cx);
10832                }
10833            }
10834        }
10835    }
10836
10837    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10838        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10839        let selections = self.selections.all::<Point>(cx);
10840        let ranges = selections
10841            .iter()
10842            .map(|s| {
10843                let mut range = s.display_range(&display_map).sorted();
10844                *range.start.column_mut() = 0;
10845                *range.end.column_mut() = display_map.line_len(range.end.row());
10846                let start = range.start.to_point(&display_map);
10847                let end = range.end.to_point(&display_map);
10848                start..end
10849            })
10850            .collect::<Vec<_>>();
10851
10852        self.unfold_ranges(&ranges, true, true, cx);
10853    }
10854
10855    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10856        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10857
10858        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10859            ..Point::new(
10860                unfold_at.buffer_row.0,
10861                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10862            );
10863
10864        let autoscroll = self
10865            .selections
10866            .all::<Point>(cx)
10867            .iter()
10868            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10869
10870        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10871    }
10872
10873    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10874        if self.buffer.read(cx).is_singleton() {
10875            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10876            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10877        } else {
10878            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10879                editor
10880                    .update(&mut cx, |editor, cx| {
10881                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10882                            editor.unfold_buffer(buffer_id, cx);
10883                        }
10884                    })
10885                    .ok();
10886            });
10887        }
10888    }
10889
10890    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10891        let selections = self.selections.all::<Point>(cx);
10892        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10893        let line_mode = self.selections.line_mode;
10894        let ranges = selections
10895            .into_iter()
10896            .map(|s| {
10897                if line_mode {
10898                    let start = Point::new(s.start.row, 0);
10899                    let end = Point::new(
10900                        s.end.row,
10901                        display_map
10902                            .buffer_snapshot
10903                            .line_len(MultiBufferRow(s.end.row)),
10904                    );
10905                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10906                } else {
10907                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10908                }
10909            })
10910            .collect::<Vec<_>>();
10911        self.fold_creases(ranges, true, cx);
10912    }
10913
10914    pub fn fold_ranges<T: ToOffset + Clone>(
10915        &mut self,
10916        ranges: Vec<Range<T>>,
10917        auto_scroll: bool,
10918        cx: &mut ViewContext<Self>,
10919    ) {
10920        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10921        let ranges = ranges
10922            .into_iter()
10923            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
10924            .collect::<Vec<_>>();
10925        self.fold_creases(ranges, auto_scroll, cx);
10926    }
10927
10928    pub fn fold_creases<T: ToOffset + Clone>(
10929        &mut self,
10930        creases: Vec<Crease<T>>,
10931        auto_scroll: bool,
10932        cx: &mut ViewContext<Self>,
10933    ) {
10934        if creases.is_empty() {
10935            return;
10936        }
10937
10938        let mut buffers_affected = HashSet::default();
10939        let multi_buffer = self.buffer().read(cx);
10940        for crease in &creases {
10941            if let Some((_, buffer, _)) =
10942                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10943            {
10944                buffers_affected.insert(buffer.read(cx).remote_id());
10945            };
10946        }
10947
10948        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10949
10950        if auto_scroll {
10951            self.request_autoscroll(Autoscroll::fit(), cx);
10952        }
10953
10954        for buffer_id in buffers_affected {
10955            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10956        }
10957
10958        cx.notify();
10959
10960        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10961            // Clear diagnostics block when folding a range that contains it.
10962            let snapshot = self.snapshot(cx);
10963            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10964                drop(snapshot);
10965                self.active_diagnostics = Some(active_diagnostics);
10966                self.dismiss_diagnostics(cx);
10967            } else {
10968                self.active_diagnostics = Some(active_diagnostics);
10969            }
10970        }
10971
10972        self.scrollbar_marker_state.dirty = true;
10973    }
10974
10975    /// Removes any folds whose ranges intersect any of the given ranges.
10976    pub fn unfold_ranges<T: ToOffset + Clone>(
10977        &mut self,
10978        ranges: &[Range<T>],
10979        inclusive: bool,
10980        auto_scroll: bool,
10981        cx: &mut ViewContext<Self>,
10982    ) {
10983        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10984            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10985        });
10986    }
10987
10988    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10989        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10990            return;
10991        }
10992        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10993            return;
10994        };
10995        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10996        self.display_map
10997            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10998        cx.emit(EditorEvent::BufferFoldToggled {
10999            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11000            folded: true,
11001        });
11002        cx.notify();
11003    }
11004
11005    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11006        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11007            return;
11008        }
11009        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11010            return;
11011        };
11012        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11013        self.display_map.update(cx, |display_map, cx| {
11014            display_map.unfold_buffer(buffer_id, cx);
11015        });
11016        cx.emit(EditorEvent::BufferFoldToggled {
11017            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11018            folded: false,
11019        });
11020        cx.notify();
11021    }
11022
11023    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11024        self.display_map.read(cx).buffer_folded(buffer)
11025    }
11026
11027    /// Removes any folds with the given ranges.
11028    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11029        &mut self,
11030        ranges: &[Range<T>],
11031        type_id: TypeId,
11032        auto_scroll: bool,
11033        cx: &mut ViewContext<Self>,
11034    ) {
11035        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11036            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11037        });
11038    }
11039
11040    fn remove_folds_with<T: ToOffset + Clone>(
11041        &mut self,
11042        ranges: &[Range<T>],
11043        auto_scroll: bool,
11044        cx: &mut ViewContext<Self>,
11045        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11046    ) {
11047        if ranges.is_empty() {
11048            return;
11049        }
11050
11051        let mut buffers_affected = HashSet::default();
11052        let multi_buffer = self.buffer().read(cx);
11053        for range in ranges {
11054            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11055                buffers_affected.insert(buffer.read(cx).remote_id());
11056            };
11057        }
11058
11059        self.display_map.update(cx, update);
11060
11061        if auto_scroll {
11062            self.request_autoscroll(Autoscroll::fit(), cx);
11063        }
11064
11065        for buffer_id in buffers_affected {
11066            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11067        }
11068
11069        cx.notify();
11070        self.scrollbar_marker_state.dirty = true;
11071        self.active_indent_guides_state.dirty = true;
11072    }
11073
11074    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11075        self.display_map.read(cx).fold_placeholder.clone()
11076    }
11077
11078    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11079        if hovered != self.gutter_hovered {
11080            self.gutter_hovered = hovered;
11081            cx.notify();
11082        }
11083    }
11084
11085    pub fn insert_blocks(
11086        &mut self,
11087        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11088        autoscroll: Option<Autoscroll>,
11089        cx: &mut ViewContext<Self>,
11090    ) -> Vec<CustomBlockId> {
11091        let blocks = self
11092            .display_map
11093            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11094        if let Some(autoscroll) = autoscroll {
11095            self.request_autoscroll(autoscroll, cx);
11096        }
11097        cx.notify();
11098        blocks
11099    }
11100
11101    pub fn resize_blocks(
11102        &mut self,
11103        heights: HashMap<CustomBlockId, u32>,
11104        autoscroll: Option<Autoscroll>,
11105        cx: &mut ViewContext<Self>,
11106    ) {
11107        self.display_map
11108            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11109        if let Some(autoscroll) = autoscroll {
11110            self.request_autoscroll(autoscroll, cx);
11111        }
11112        cx.notify();
11113    }
11114
11115    pub fn replace_blocks(
11116        &mut self,
11117        renderers: HashMap<CustomBlockId, RenderBlock>,
11118        autoscroll: Option<Autoscroll>,
11119        cx: &mut ViewContext<Self>,
11120    ) {
11121        self.display_map
11122            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11123        if let Some(autoscroll) = autoscroll {
11124            self.request_autoscroll(autoscroll, cx);
11125        }
11126        cx.notify();
11127    }
11128
11129    pub fn remove_blocks(
11130        &mut self,
11131        block_ids: HashSet<CustomBlockId>,
11132        autoscroll: Option<Autoscroll>,
11133        cx: &mut ViewContext<Self>,
11134    ) {
11135        self.display_map.update(cx, |display_map, cx| {
11136            display_map.remove_blocks(block_ids, cx)
11137        });
11138        if let Some(autoscroll) = autoscroll {
11139            self.request_autoscroll(autoscroll, cx);
11140        }
11141        cx.notify();
11142    }
11143
11144    pub fn row_for_block(
11145        &self,
11146        block_id: CustomBlockId,
11147        cx: &mut ViewContext<Self>,
11148    ) -> Option<DisplayRow> {
11149        self.display_map
11150            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11151    }
11152
11153    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11154        self.focused_block = Some(focused_block);
11155    }
11156
11157    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11158        self.focused_block.take()
11159    }
11160
11161    pub fn insert_creases(
11162        &mut self,
11163        creases: impl IntoIterator<Item = Crease<Anchor>>,
11164        cx: &mut ViewContext<Self>,
11165    ) -> Vec<CreaseId> {
11166        self.display_map
11167            .update(cx, |map, cx| map.insert_creases(creases, cx))
11168    }
11169
11170    pub fn remove_creases(
11171        &mut self,
11172        ids: impl IntoIterator<Item = CreaseId>,
11173        cx: &mut ViewContext<Self>,
11174    ) {
11175        self.display_map
11176            .update(cx, |map, cx| map.remove_creases(ids, cx));
11177    }
11178
11179    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11180        self.display_map
11181            .update(cx, |map, cx| map.snapshot(cx))
11182            .longest_row()
11183    }
11184
11185    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11186        self.display_map
11187            .update(cx, |map, cx| map.snapshot(cx))
11188            .max_point()
11189    }
11190
11191    pub fn text(&self, cx: &AppContext) -> String {
11192        self.buffer.read(cx).read(cx).text()
11193    }
11194
11195    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11196        let text = self.text(cx);
11197        let text = text.trim();
11198
11199        if text.is_empty() {
11200            return None;
11201        }
11202
11203        Some(text.to_string())
11204    }
11205
11206    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11207        self.transact(cx, |this, cx| {
11208            this.buffer
11209                .read(cx)
11210                .as_singleton()
11211                .expect("you can only call set_text on editors for singleton buffers")
11212                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11213        });
11214    }
11215
11216    pub fn display_text(&self, cx: &mut AppContext) -> String {
11217        self.display_map
11218            .update(cx, |map, cx| map.snapshot(cx))
11219            .text()
11220    }
11221
11222    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11223        let mut wrap_guides = smallvec::smallvec![];
11224
11225        if self.show_wrap_guides == Some(false) {
11226            return wrap_guides;
11227        }
11228
11229        let settings = self.buffer.read(cx).settings_at(0, cx);
11230        if settings.show_wrap_guides {
11231            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11232                wrap_guides.push((soft_wrap as usize, true));
11233            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11234                wrap_guides.push((soft_wrap as usize, true));
11235            }
11236            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11237        }
11238
11239        wrap_guides
11240    }
11241
11242    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11243        let settings = self.buffer.read(cx).settings_at(0, cx);
11244        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11245        match mode {
11246            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11247                SoftWrap::None
11248            }
11249            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11250            language_settings::SoftWrap::PreferredLineLength => {
11251                SoftWrap::Column(settings.preferred_line_length)
11252            }
11253            language_settings::SoftWrap::Bounded => {
11254                SoftWrap::Bounded(settings.preferred_line_length)
11255            }
11256        }
11257    }
11258
11259    pub fn set_soft_wrap_mode(
11260        &mut self,
11261        mode: language_settings::SoftWrap,
11262        cx: &mut ViewContext<Self>,
11263    ) {
11264        self.soft_wrap_mode_override = Some(mode);
11265        cx.notify();
11266    }
11267
11268    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11269        self.text_style_refinement = Some(style);
11270    }
11271
11272    /// called by the Element so we know what style we were most recently rendered with.
11273    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11274        let rem_size = cx.rem_size();
11275        self.display_map.update(cx, |map, cx| {
11276            map.set_font(
11277                style.text.font(),
11278                style.text.font_size.to_pixels(rem_size),
11279                cx,
11280            )
11281        });
11282        self.style = Some(style);
11283    }
11284
11285    pub fn style(&self) -> Option<&EditorStyle> {
11286        self.style.as_ref()
11287    }
11288
11289    // Called by the element. This method is not designed to be called outside of the editor
11290    // element's layout code because it does not notify when rewrapping is computed synchronously.
11291    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11292        self.display_map
11293            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11294    }
11295
11296    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11297        if self.soft_wrap_mode_override.is_some() {
11298            self.soft_wrap_mode_override.take();
11299        } else {
11300            let soft_wrap = match self.soft_wrap_mode(cx) {
11301                SoftWrap::GitDiff => return,
11302                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11303                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11304                    language_settings::SoftWrap::None
11305                }
11306            };
11307            self.soft_wrap_mode_override = Some(soft_wrap);
11308        }
11309        cx.notify();
11310    }
11311
11312    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11313        let Some(workspace) = self.workspace() else {
11314            return;
11315        };
11316        let fs = workspace.read(cx).app_state().fs.clone();
11317        let current_show = TabBarSettings::get_global(cx).show;
11318        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11319            setting.show = Some(!current_show);
11320        });
11321    }
11322
11323    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11324        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11325            self.buffer
11326                .read(cx)
11327                .settings_at(0, cx)
11328                .indent_guides
11329                .enabled
11330        });
11331        self.show_indent_guides = Some(!currently_enabled);
11332        cx.notify();
11333    }
11334
11335    fn should_show_indent_guides(&self) -> Option<bool> {
11336        self.show_indent_guides
11337    }
11338
11339    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11340        let mut editor_settings = EditorSettings::get_global(cx).clone();
11341        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11342        EditorSettings::override_global(editor_settings, cx);
11343    }
11344
11345    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11346        self.use_relative_line_numbers
11347            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11348    }
11349
11350    pub fn toggle_relative_line_numbers(
11351        &mut self,
11352        _: &ToggleRelativeLineNumbers,
11353        cx: &mut ViewContext<Self>,
11354    ) {
11355        let is_relative = self.should_use_relative_line_numbers(cx);
11356        self.set_relative_line_number(Some(!is_relative), cx)
11357    }
11358
11359    pub fn set_relative_line_number(
11360        &mut self,
11361        is_relative: Option<bool>,
11362        cx: &mut ViewContext<Self>,
11363    ) {
11364        self.use_relative_line_numbers = is_relative;
11365        cx.notify();
11366    }
11367
11368    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11369        self.show_gutter = show_gutter;
11370        cx.notify();
11371    }
11372
11373    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11374        self.show_scrollbars = show_scrollbars;
11375        cx.notify();
11376    }
11377
11378    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11379        self.show_line_numbers = Some(show_line_numbers);
11380        cx.notify();
11381    }
11382
11383    pub fn set_show_git_diff_gutter(
11384        &mut self,
11385        show_git_diff_gutter: bool,
11386        cx: &mut ViewContext<Self>,
11387    ) {
11388        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11389        cx.notify();
11390    }
11391
11392    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11393        self.show_code_actions = Some(show_code_actions);
11394        cx.notify();
11395    }
11396
11397    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11398        self.show_runnables = Some(show_runnables);
11399        cx.notify();
11400    }
11401
11402    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11403        if self.display_map.read(cx).masked != masked {
11404            self.display_map.update(cx, |map, _| map.masked = masked);
11405        }
11406        cx.notify()
11407    }
11408
11409    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11410        self.show_wrap_guides = Some(show_wrap_guides);
11411        cx.notify();
11412    }
11413
11414    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11415        self.show_indent_guides = Some(show_indent_guides);
11416        cx.notify();
11417    }
11418
11419    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11420        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11421            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11422                if let Some(dir) = file.abs_path(cx).parent() {
11423                    return Some(dir.to_owned());
11424                }
11425            }
11426
11427            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11428                return Some(project_path.path.to_path_buf());
11429            }
11430        }
11431
11432        None
11433    }
11434
11435    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11436        self.active_excerpt(cx)?
11437            .1
11438            .read(cx)
11439            .file()
11440            .and_then(|f| f.as_local())
11441    }
11442
11443    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11444        if let Some(target) = self.target_file(cx) {
11445            cx.reveal_path(&target.abs_path(cx));
11446        }
11447    }
11448
11449    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11450        if let Some(file) = self.target_file(cx) {
11451            if let Some(path) = file.abs_path(cx).to_str() {
11452                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11453            }
11454        }
11455    }
11456
11457    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11458        if let Some(file) = self.target_file(cx) {
11459            if let Some(path) = file.path().to_str() {
11460                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11461            }
11462        }
11463    }
11464
11465    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11466        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11467
11468        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11469            self.start_git_blame(true, cx);
11470        }
11471
11472        cx.notify();
11473    }
11474
11475    pub fn toggle_git_blame_inline(
11476        &mut self,
11477        _: &ToggleGitBlameInline,
11478        cx: &mut ViewContext<Self>,
11479    ) {
11480        self.toggle_git_blame_inline_internal(true, cx);
11481        cx.notify();
11482    }
11483
11484    pub fn git_blame_inline_enabled(&self) -> bool {
11485        self.git_blame_inline_enabled
11486    }
11487
11488    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11489        self.show_selection_menu = self
11490            .show_selection_menu
11491            .map(|show_selections_menu| !show_selections_menu)
11492            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11493
11494        cx.notify();
11495    }
11496
11497    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11498        self.show_selection_menu
11499            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11500    }
11501
11502    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11503        if let Some(project) = self.project.as_ref() {
11504            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11505                return;
11506            };
11507
11508            if buffer.read(cx).file().is_none() {
11509                return;
11510            }
11511
11512            let focused = self.focus_handle(cx).contains_focused(cx);
11513
11514            let project = project.clone();
11515            let blame =
11516                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11517            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11518            self.blame = Some(blame);
11519        }
11520    }
11521
11522    fn toggle_git_blame_inline_internal(
11523        &mut self,
11524        user_triggered: bool,
11525        cx: &mut ViewContext<Self>,
11526    ) {
11527        if self.git_blame_inline_enabled {
11528            self.git_blame_inline_enabled = false;
11529            self.show_git_blame_inline = false;
11530            self.show_git_blame_inline_delay_task.take();
11531        } else {
11532            self.git_blame_inline_enabled = true;
11533            self.start_git_blame_inline(user_triggered, cx);
11534        }
11535
11536        cx.notify();
11537    }
11538
11539    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11540        self.start_git_blame(user_triggered, cx);
11541
11542        if ProjectSettings::get_global(cx)
11543            .git
11544            .inline_blame_delay()
11545            .is_some()
11546        {
11547            self.start_inline_blame_timer(cx);
11548        } else {
11549            self.show_git_blame_inline = true
11550        }
11551    }
11552
11553    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11554        self.blame.as_ref()
11555    }
11556
11557    pub fn show_git_blame_gutter(&self) -> bool {
11558        self.show_git_blame_gutter
11559    }
11560
11561    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11562        self.show_git_blame_gutter && self.has_blame_entries(cx)
11563    }
11564
11565    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11566        self.show_git_blame_inline
11567            && self.focus_handle.is_focused(cx)
11568            && !self.newest_selection_head_on_empty_line(cx)
11569            && self.has_blame_entries(cx)
11570    }
11571
11572    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11573        self.blame()
11574            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11575    }
11576
11577    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11578        let cursor_anchor = self.selections.newest_anchor().head();
11579
11580        let snapshot = self.buffer.read(cx).snapshot(cx);
11581        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11582
11583        snapshot.line_len(buffer_row) == 0
11584    }
11585
11586    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11587        let buffer_and_selection = maybe!({
11588            let selection = self.selections.newest::<Point>(cx);
11589            let selection_range = selection.range();
11590
11591            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11592                (buffer, selection_range.start.row..selection_range.end.row)
11593            } else {
11594                let multi_buffer = self.buffer().read(cx);
11595                let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11596                let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11597
11598                let (excerpt, range) = if selection.reversed {
11599                    buffer_ranges.first()
11600                } else {
11601                    buffer_ranges.last()
11602                }?;
11603
11604                let snapshot = excerpt.buffer();
11605                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11606                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11607                (
11608                    multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11609                    selection,
11610                )
11611            };
11612
11613            Some((buffer, selection))
11614        });
11615
11616        let Some((buffer, selection)) = buffer_and_selection else {
11617            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11618        };
11619
11620        let Some(project) = self.project.as_ref() else {
11621            return Task::ready(Err(anyhow!("editor does not have project")));
11622        };
11623
11624        project.update(cx, |project, cx| {
11625            project.get_permalink_to_line(&buffer, selection, cx)
11626        })
11627    }
11628
11629    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11630        let permalink_task = self.get_permalink_to_line(cx);
11631        let workspace = self.workspace();
11632
11633        cx.spawn(|_, mut cx| async move {
11634            match permalink_task.await {
11635                Ok(permalink) => {
11636                    cx.update(|cx| {
11637                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11638                    })
11639                    .ok();
11640                }
11641                Err(err) => {
11642                    let message = format!("Failed to copy permalink: {err}");
11643
11644                    Err::<(), anyhow::Error>(err).log_err();
11645
11646                    if let Some(workspace) = workspace {
11647                        workspace
11648                            .update(&mut cx, |workspace, cx| {
11649                                struct CopyPermalinkToLine;
11650
11651                                workspace.show_toast(
11652                                    Toast::new(
11653                                        NotificationId::unique::<CopyPermalinkToLine>(),
11654                                        message,
11655                                    ),
11656                                    cx,
11657                                )
11658                            })
11659                            .ok();
11660                    }
11661                }
11662            }
11663        })
11664        .detach();
11665    }
11666
11667    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11668        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11669        if let Some(file) = self.target_file(cx) {
11670            if let Some(path) = file.path().to_str() {
11671                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11672            }
11673        }
11674    }
11675
11676    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11677        let permalink_task = self.get_permalink_to_line(cx);
11678        let workspace = self.workspace();
11679
11680        cx.spawn(|_, mut cx| async move {
11681            match permalink_task.await {
11682                Ok(permalink) => {
11683                    cx.update(|cx| {
11684                        cx.open_url(permalink.as_ref());
11685                    })
11686                    .ok();
11687                }
11688                Err(err) => {
11689                    let message = format!("Failed to open permalink: {err}");
11690
11691                    Err::<(), anyhow::Error>(err).log_err();
11692
11693                    if let Some(workspace) = workspace {
11694                        workspace
11695                            .update(&mut cx, |workspace, cx| {
11696                                struct OpenPermalinkToLine;
11697
11698                                workspace.show_toast(
11699                                    Toast::new(
11700                                        NotificationId::unique::<OpenPermalinkToLine>(),
11701                                        message,
11702                                    ),
11703                                    cx,
11704                                )
11705                            })
11706                            .ok();
11707                    }
11708                }
11709            }
11710        })
11711        .detach();
11712    }
11713
11714    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11715        self.insert_uuid(UuidVersion::V4, cx);
11716    }
11717
11718    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11719        self.insert_uuid(UuidVersion::V7, cx);
11720    }
11721
11722    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11723        self.transact(cx, |this, cx| {
11724            let edits = this
11725                .selections
11726                .all::<Point>(cx)
11727                .into_iter()
11728                .map(|selection| {
11729                    let uuid = match version {
11730                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11731                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11732                    };
11733
11734                    (selection.range(), uuid.to_string())
11735                });
11736            this.edit(edits, cx);
11737            this.refresh_inline_completion(true, false, cx);
11738        });
11739    }
11740
11741    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11742    /// last highlight added will be used.
11743    ///
11744    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11745    pub fn highlight_rows<T: 'static>(
11746        &mut self,
11747        range: Range<Anchor>,
11748        color: Hsla,
11749        should_autoscroll: bool,
11750        cx: &mut ViewContext<Self>,
11751    ) {
11752        let snapshot = self.buffer().read(cx).snapshot(cx);
11753        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11754        let ix = row_highlights.binary_search_by(|highlight| {
11755            Ordering::Equal
11756                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11757                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11758        });
11759
11760        if let Err(mut ix) = ix {
11761            let index = post_inc(&mut self.highlight_order);
11762
11763            // If this range intersects with the preceding highlight, then merge it with
11764            // the preceding highlight. Otherwise insert a new highlight.
11765            let mut merged = false;
11766            if ix > 0 {
11767                let prev_highlight = &mut row_highlights[ix - 1];
11768                if prev_highlight
11769                    .range
11770                    .end
11771                    .cmp(&range.start, &snapshot)
11772                    .is_ge()
11773                {
11774                    ix -= 1;
11775                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11776                        prev_highlight.range.end = range.end;
11777                    }
11778                    merged = true;
11779                    prev_highlight.index = index;
11780                    prev_highlight.color = color;
11781                    prev_highlight.should_autoscroll = should_autoscroll;
11782                }
11783            }
11784
11785            if !merged {
11786                row_highlights.insert(
11787                    ix,
11788                    RowHighlight {
11789                        range: range.clone(),
11790                        index,
11791                        color,
11792                        should_autoscroll,
11793                    },
11794                );
11795            }
11796
11797            // If any of the following highlights intersect with this one, merge them.
11798            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11799                let highlight = &row_highlights[ix];
11800                if next_highlight
11801                    .range
11802                    .start
11803                    .cmp(&highlight.range.end, &snapshot)
11804                    .is_le()
11805                {
11806                    if next_highlight
11807                        .range
11808                        .end
11809                        .cmp(&highlight.range.end, &snapshot)
11810                        .is_gt()
11811                    {
11812                        row_highlights[ix].range.end = next_highlight.range.end;
11813                    }
11814                    row_highlights.remove(ix + 1);
11815                } else {
11816                    break;
11817                }
11818            }
11819        }
11820    }
11821
11822    /// Remove any highlighted row ranges of the given type that intersect the
11823    /// given ranges.
11824    pub fn remove_highlighted_rows<T: 'static>(
11825        &mut self,
11826        ranges_to_remove: Vec<Range<Anchor>>,
11827        cx: &mut ViewContext<Self>,
11828    ) {
11829        let snapshot = self.buffer().read(cx).snapshot(cx);
11830        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11831        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11832        row_highlights.retain(|highlight| {
11833            while let Some(range_to_remove) = ranges_to_remove.peek() {
11834                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11835                    Ordering::Less | Ordering::Equal => {
11836                        ranges_to_remove.next();
11837                    }
11838                    Ordering::Greater => {
11839                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11840                            Ordering::Less | Ordering::Equal => {
11841                                return false;
11842                            }
11843                            Ordering::Greater => break,
11844                        }
11845                    }
11846                }
11847            }
11848
11849            true
11850        })
11851    }
11852
11853    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11854    pub fn clear_row_highlights<T: 'static>(&mut self) {
11855        self.highlighted_rows.remove(&TypeId::of::<T>());
11856    }
11857
11858    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11859    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11860        self.highlighted_rows
11861            .get(&TypeId::of::<T>())
11862            .map_or(&[] as &[_], |vec| vec.as_slice())
11863            .iter()
11864            .map(|highlight| (highlight.range.clone(), highlight.color))
11865    }
11866
11867    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11868    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11869    /// Allows to ignore certain kinds of highlights.
11870    pub fn highlighted_display_rows(
11871        &mut self,
11872        cx: &mut WindowContext,
11873    ) -> BTreeMap<DisplayRow, Hsla> {
11874        let snapshot = self.snapshot(cx);
11875        let mut used_highlight_orders = HashMap::default();
11876        self.highlighted_rows
11877            .iter()
11878            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11879            .fold(
11880                BTreeMap::<DisplayRow, Hsla>::new(),
11881                |mut unique_rows, highlight| {
11882                    let start = highlight.range.start.to_display_point(&snapshot);
11883                    let end = highlight.range.end.to_display_point(&snapshot);
11884                    let start_row = start.row().0;
11885                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11886                        && end.column() == 0
11887                    {
11888                        end.row().0.saturating_sub(1)
11889                    } else {
11890                        end.row().0
11891                    };
11892                    for row in start_row..=end_row {
11893                        let used_index =
11894                            used_highlight_orders.entry(row).or_insert(highlight.index);
11895                        if highlight.index >= *used_index {
11896                            *used_index = highlight.index;
11897                            unique_rows.insert(DisplayRow(row), highlight.color);
11898                        }
11899                    }
11900                    unique_rows
11901                },
11902            )
11903    }
11904
11905    pub fn highlighted_display_row_for_autoscroll(
11906        &self,
11907        snapshot: &DisplaySnapshot,
11908    ) -> Option<DisplayRow> {
11909        self.highlighted_rows
11910            .values()
11911            .flat_map(|highlighted_rows| highlighted_rows.iter())
11912            .filter_map(|highlight| {
11913                if highlight.should_autoscroll {
11914                    Some(highlight.range.start.to_display_point(snapshot).row())
11915                } else {
11916                    None
11917                }
11918            })
11919            .min()
11920    }
11921
11922    pub fn set_search_within_ranges(
11923        &mut self,
11924        ranges: &[Range<Anchor>],
11925        cx: &mut ViewContext<Self>,
11926    ) {
11927        self.highlight_background::<SearchWithinRange>(
11928            ranges,
11929            |colors| colors.editor_document_highlight_read_background,
11930            cx,
11931        )
11932    }
11933
11934    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11935        self.breadcrumb_header = Some(new_header);
11936    }
11937
11938    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11939        self.clear_background_highlights::<SearchWithinRange>(cx);
11940    }
11941
11942    pub fn highlight_background<T: 'static>(
11943        &mut self,
11944        ranges: &[Range<Anchor>],
11945        color_fetcher: fn(&ThemeColors) -> Hsla,
11946        cx: &mut ViewContext<Self>,
11947    ) {
11948        self.background_highlights
11949            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11950        self.scrollbar_marker_state.dirty = true;
11951        cx.notify();
11952    }
11953
11954    pub fn clear_background_highlights<T: 'static>(
11955        &mut self,
11956        cx: &mut ViewContext<Self>,
11957    ) -> Option<BackgroundHighlight> {
11958        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11959        if !text_highlights.1.is_empty() {
11960            self.scrollbar_marker_state.dirty = true;
11961            cx.notify();
11962        }
11963        Some(text_highlights)
11964    }
11965
11966    pub fn highlight_gutter<T: 'static>(
11967        &mut self,
11968        ranges: &[Range<Anchor>],
11969        color_fetcher: fn(&AppContext) -> Hsla,
11970        cx: &mut ViewContext<Self>,
11971    ) {
11972        self.gutter_highlights
11973            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11974        cx.notify();
11975    }
11976
11977    pub fn clear_gutter_highlights<T: 'static>(
11978        &mut self,
11979        cx: &mut ViewContext<Self>,
11980    ) -> Option<GutterHighlight> {
11981        cx.notify();
11982        self.gutter_highlights.remove(&TypeId::of::<T>())
11983    }
11984
11985    #[cfg(feature = "test-support")]
11986    pub fn all_text_background_highlights(
11987        &mut self,
11988        cx: &mut ViewContext<Self>,
11989    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11990        let snapshot = self.snapshot(cx);
11991        let buffer = &snapshot.buffer_snapshot;
11992        let start = buffer.anchor_before(0);
11993        let end = buffer.anchor_after(buffer.len());
11994        let theme = cx.theme().colors();
11995        self.background_highlights_in_range(start..end, &snapshot, theme)
11996    }
11997
11998    #[cfg(feature = "test-support")]
11999    pub fn search_background_highlights(
12000        &mut self,
12001        cx: &mut ViewContext<Self>,
12002    ) -> Vec<Range<Point>> {
12003        let snapshot = self.buffer().read(cx).snapshot(cx);
12004
12005        let highlights = self
12006            .background_highlights
12007            .get(&TypeId::of::<items::BufferSearchHighlights>());
12008
12009        if let Some((_color, ranges)) = highlights {
12010            ranges
12011                .iter()
12012                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12013                .collect_vec()
12014        } else {
12015            vec![]
12016        }
12017    }
12018
12019    fn document_highlights_for_position<'a>(
12020        &'a self,
12021        position: Anchor,
12022        buffer: &'a MultiBufferSnapshot,
12023    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12024        let read_highlights = self
12025            .background_highlights
12026            .get(&TypeId::of::<DocumentHighlightRead>())
12027            .map(|h| &h.1);
12028        let write_highlights = self
12029            .background_highlights
12030            .get(&TypeId::of::<DocumentHighlightWrite>())
12031            .map(|h| &h.1);
12032        let left_position = position.bias_left(buffer);
12033        let right_position = position.bias_right(buffer);
12034        read_highlights
12035            .into_iter()
12036            .chain(write_highlights)
12037            .flat_map(move |ranges| {
12038                let start_ix = match ranges.binary_search_by(|probe| {
12039                    let cmp = probe.end.cmp(&left_position, buffer);
12040                    if cmp.is_ge() {
12041                        Ordering::Greater
12042                    } else {
12043                        Ordering::Less
12044                    }
12045                }) {
12046                    Ok(i) | Err(i) => i,
12047                };
12048
12049                ranges[start_ix..]
12050                    .iter()
12051                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12052            })
12053    }
12054
12055    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12056        self.background_highlights
12057            .get(&TypeId::of::<T>())
12058            .map_or(false, |(_, highlights)| !highlights.is_empty())
12059    }
12060
12061    pub fn background_highlights_in_range(
12062        &self,
12063        search_range: Range<Anchor>,
12064        display_snapshot: &DisplaySnapshot,
12065        theme: &ThemeColors,
12066    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12067        let mut results = Vec::new();
12068        for (color_fetcher, ranges) in self.background_highlights.values() {
12069            let color = color_fetcher(theme);
12070            let start_ix = match ranges.binary_search_by(|probe| {
12071                let cmp = probe
12072                    .end
12073                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12074                if cmp.is_gt() {
12075                    Ordering::Greater
12076                } else {
12077                    Ordering::Less
12078                }
12079            }) {
12080                Ok(i) | Err(i) => i,
12081            };
12082            for range in &ranges[start_ix..] {
12083                if range
12084                    .start
12085                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12086                    .is_ge()
12087                {
12088                    break;
12089                }
12090
12091                let start = range.start.to_display_point(display_snapshot);
12092                let end = range.end.to_display_point(display_snapshot);
12093                results.push((start..end, color))
12094            }
12095        }
12096        results
12097    }
12098
12099    pub fn background_highlight_row_ranges<T: 'static>(
12100        &self,
12101        search_range: Range<Anchor>,
12102        display_snapshot: &DisplaySnapshot,
12103        count: usize,
12104    ) -> Vec<RangeInclusive<DisplayPoint>> {
12105        let mut results = Vec::new();
12106        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12107            return vec![];
12108        };
12109
12110        let start_ix = match ranges.binary_search_by(|probe| {
12111            let cmp = probe
12112                .end
12113                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12114            if cmp.is_gt() {
12115                Ordering::Greater
12116            } else {
12117                Ordering::Less
12118            }
12119        }) {
12120            Ok(i) | Err(i) => i,
12121        };
12122        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12123            if let (Some(start_display), Some(end_display)) = (start, end) {
12124                results.push(
12125                    start_display.to_display_point(display_snapshot)
12126                        ..=end_display.to_display_point(display_snapshot),
12127                );
12128            }
12129        };
12130        let mut start_row: Option<Point> = None;
12131        let mut end_row: Option<Point> = None;
12132        if ranges.len() > count {
12133            return Vec::new();
12134        }
12135        for range in &ranges[start_ix..] {
12136            if range
12137                .start
12138                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12139                .is_ge()
12140            {
12141                break;
12142            }
12143            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12144            if let Some(current_row) = &end_row {
12145                if end.row == current_row.row {
12146                    continue;
12147                }
12148            }
12149            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12150            if start_row.is_none() {
12151                assert_eq!(end_row, None);
12152                start_row = Some(start);
12153                end_row = Some(end);
12154                continue;
12155            }
12156            if let Some(current_end) = end_row.as_mut() {
12157                if start.row > current_end.row + 1 {
12158                    push_region(start_row, end_row);
12159                    start_row = Some(start);
12160                    end_row = Some(end);
12161                } else {
12162                    // Merge two hunks.
12163                    *current_end = end;
12164                }
12165            } else {
12166                unreachable!();
12167            }
12168        }
12169        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12170        push_region(start_row, end_row);
12171        results
12172    }
12173
12174    pub fn gutter_highlights_in_range(
12175        &self,
12176        search_range: Range<Anchor>,
12177        display_snapshot: &DisplaySnapshot,
12178        cx: &AppContext,
12179    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12180        let mut results = Vec::new();
12181        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12182            let color = color_fetcher(cx);
12183            let start_ix = match ranges.binary_search_by(|probe| {
12184                let cmp = probe
12185                    .end
12186                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12187                if cmp.is_gt() {
12188                    Ordering::Greater
12189                } else {
12190                    Ordering::Less
12191                }
12192            }) {
12193                Ok(i) | Err(i) => i,
12194            };
12195            for range in &ranges[start_ix..] {
12196                if range
12197                    .start
12198                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12199                    .is_ge()
12200                {
12201                    break;
12202                }
12203
12204                let start = range.start.to_display_point(display_snapshot);
12205                let end = range.end.to_display_point(display_snapshot);
12206                results.push((start..end, color))
12207            }
12208        }
12209        results
12210    }
12211
12212    /// Get the text ranges corresponding to the redaction query
12213    pub fn redacted_ranges(
12214        &self,
12215        search_range: Range<Anchor>,
12216        display_snapshot: &DisplaySnapshot,
12217        cx: &WindowContext,
12218    ) -> Vec<Range<DisplayPoint>> {
12219        display_snapshot
12220            .buffer_snapshot
12221            .redacted_ranges(search_range, |file| {
12222                if let Some(file) = file {
12223                    file.is_private()
12224                        && EditorSettings::get(
12225                            Some(SettingsLocation {
12226                                worktree_id: file.worktree_id(cx),
12227                                path: file.path().as_ref(),
12228                            }),
12229                            cx,
12230                        )
12231                        .redact_private_values
12232                } else {
12233                    false
12234                }
12235            })
12236            .map(|range| {
12237                range.start.to_display_point(display_snapshot)
12238                    ..range.end.to_display_point(display_snapshot)
12239            })
12240            .collect()
12241    }
12242
12243    pub fn highlight_text<T: 'static>(
12244        &mut self,
12245        ranges: Vec<Range<Anchor>>,
12246        style: HighlightStyle,
12247        cx: &mut ViewContext<Self>,
12248    ) {
12249        self.display_map.update(cx, |map, _| {
12250            map.highlight_text(TypeId::of::<T>(), ranges, style)
12251        });
12252        cx.notify();
12253    }
12254
12255    pub(crate) fn highlight_inlays<T: 'static>(
12256        &mut self,
12257        highlights: Vec<InlayHighlight>,
12258        style: HighlightStyle,
12259        cx: &mut ViewContext<Self>,
12260    ) {
12261        self.display_map.update(cx, |map, _| {
12262            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12263        });
12264        cx.notify();
12265    }
12266
12267    pub fn text_highlights<'a, T: 'static>(
12268        &'a self,
12269        cx: &'a AppContext,
12270    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12271        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12272    }
12273
12274    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12275        let cleared = self
12276            .display_map
12277            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12278        if cleared {
12279            cx.notify();
12280        }
12281    }
12282
12283    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12284        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12285            && self.focus_handle.is_focused(cx)
12286    }
12287
12288    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12289        self.show_cursor_when_unfocused = is_enabled;
12290        cx.notify();
12291    }
12292
12293    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12294        self.project
12295            .as_ref()
12296            .map(|project| project.read(cx).lsp_store())
12297    }
12298
12299    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12300        cx.notify();
12301    }
12302
12303    fn on_buffer_event(
12304        &mut self,
12305        multibuffer: Model<MultiBuffer>,
12306        event: &multi_buffer::Event,
12307        cx: &mut ViewContext<Self>,
12308    ) {
12309        match event {
12310            multi_buffer::Event::Edited {
12311                singleton_buffer_edited,
12312                edited_buffer: buffer_edited,
12313            } => {
12314                self.scrollbar_marker_state.dirty = true;
12315                self.active_indent_guides_state.dirty = true;
12316                self.refresh_active_diagnostics(cx);
12317                self.refresh_code_actions(cx);
12318                if self.has_active_inline_completion() {
12319                    self.update_visible_inline_completion(cx);
12320                }
12321                if let Some(buffer) = buffer_edited {
12322                    let buffer_id = buffer.read(cx).remote_id();
12323                    if !self.registered_buffers.contains_key(&buffer_id) {
12324                        if let Some(lsp_store) = self.lsp_store(cx) {
12325                            lsp_store.update(cx, |lsp_store, cx| {
12326                                self.registered_buffers.insert(
12327                                    buffer_id,
12328                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12329                                );
12330                            })
12331                        }
12332                    }
12333                }
12334                cx.emit(EditorEvent::BufferEdited);
12335                cx.emit(SearchEvent::MatchesInvalidated);
12336                if *singleton_buffer_edited {
12337                    if let Some(project) = &self.project {
12338                        let project = project.read(cx);
12339                        #[allow(clippy::mutable_key_type)]
12340                        let languages_affected = multibuffer
12341                            .read(cx)
12342                            .all_buffers()
12343                            .into_iter()
12344                            .filter_map(|buffer| {
12345                                let buffer = buffer.read(cx);
12346                                let language = buffer.language()?;
12347                                if project.is_local()
12348                                    && project
12349                                        .language_servers_for_local_buffer(buffer, cx)
12350                                        .count()
12351                                        == 0
12352                                {
12353                                    None
12354                                } else {
12355                                    Some(language)
12356                                }
12357                            })
12358                            .cloned()
12359                            .collect::<HashSet<_>>();
12360                        if !languages_affected.is_empty() {
12361                            self.refresh_inlay_hints(
12362                                InlayHintRefreshReason::BufferEdited(languages_affected),
12363                                cx,
12364                            );
12365                        }
12366                    }
12367                }
12368
12369                let Some(project) = &self.project else { return };
12370                let (telemetry, is_via_ssh) = {
12371                    let project = project.read(cx);
12372                    let telemetry = project.client().telemetry().clone();
12373                    let is_via_ssh = project.is_via_ssh();
12374                    (telemetry, is_via_ssh)
12375                };
12376                refresh_linked_ranges(self, cx);
12377                telemetry.log_edit_event("editor", is_via_ssh);
12378            }
12379            multi_buffer::Event::ExcerptsAdded {
12380                buffer,
12381                predecessor,
12382                excerpts,
12383            } => {
12384                self.tasks_update_task = Some(self.refresh_runnables(cx));
12385                let buffer_id = buffer.read(cx).remote_id();
12386                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12387                    if let Some(project) = &self.project {
12388                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12389                    }
12390                }
12391                cx.emit(EditorEvent::ExcerptsAdded {
12392                    buffer: buffer.clone(),
12393                    predecessor: *predecessor,
12394                    excerpts: excerpts.clone(),
12395                });
12396                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12397            }
12398            multi_buffer::Event::ExcerptsRemoved { ids } => {
12399                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12400                let buffer = self.buffer.read(cx);
12401                self.registered_buffers
12402                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12403                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12404            }
12405            multi_buffer::Event::ExcerptsEdited { ids } => {
12406                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12407            }
12408            multi_buffer::Event::ExcerptsExpanded { ids } => {
12409                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12410            }
12411            multi_buffer::Event::Reparsed(buffer_id) => {
12412                self.tasks_update_task = Some(self.refresh_runnables(cx));
12413
12414                cx.emit(EditorEvent::Reparsed(*buffer_id));
12415            }
12416            multi_buffer::Event::LanguageChanged(buffer_id) => {
12417                linked_editing_ranges::refresh_linked_ranges(self, cx);
12418                cx.emit(EditorEvent::Reparsed(*buffer_id));
12419                cx.notify();
12420            }
12421            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12422            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12423            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12424                cx.emit(EditorEvent::TitleChanged)
12425            }
12426            // multi_buffer::Event::DiffBaseChanged => {
12427            //     self.scrollbar_marker_state.dirty = true;
12428            //     cx.emit(EditorEvent::DiffBaseChanged);
12429            //     cx.notify();
12430            // }
12431            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12432            multi_buffer::Event::DiagnosticsUpdated => {
12433                self.refresh_active_diagnostics(cx);
12434                self.scrollbar_marker_state.dirty = true;
12435                cx.notify();
12436            }
12437            _ => {}
12438        };
12439    }
12440
12441    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12442        cx.notify();
12443    }
12444
12445    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12446        self.tasks_update_task = Some(self.refresh_runnables(cx));
12447        self.refresh_inline_completion(true, false, cx);
12448        self.refresh_inlay_hints(
12449            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12450                self.selections.newest_anchor().head(),
12451                &self.buffer.read(cx).snapshot(cx),
12452                cx,
12453            )),
12454            cx,
12455        );
12456
12457        let old_cursor_shape = self.cursor_shape;
12458
12459        {
12460            let editor_settings = EditorSettings::get_global(cx);
12461            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12462            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12463            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12464        }
12465
12466        if old_cursor_shape != self.cursor_shape {
12467            cx.emit(EditorEvent::CursorShapeChanged);
12468        }
12469
12470        let project_settings = ProjectSettings::get_global(cx);
12471        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12472
12473        if self.mode == EditorMode::Full {
12474            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12475            if self.git_blame_inline_enabled != inline_blame_enabled {
12476                self.toggle_git_blame_inline_internal(false, cx);
12477            }
12478        }
12479
12480        cx.notify();
12481    }
12482
12483    pub fn set_searchable(&mut self, searchable: bool) {
12484        self.searchable = searchable;
12485    }
12486
12487    pub fn searchable(&self) -> bool {
12488        self.searchable
12489    }
12490
12491    fn open_proposed_changes_editor(
12492        &mut self,
12493        _: &OpenProposedChangesEditor,
12494        cx: &mut ViewContext<Self>,
12495    ) {
12496        let Some(workspace) = self.workspace() else {
12497            cx.propagate();
12498            return;
12499        };
12500
12501        let selections = self.selections.all::<usize>(cx);
12502        let multi_buffer = self.buffer.read(cx);
12503        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12504        let mut new_selections_by_buffer = HashMap::default();
12505        for selection in selections {
12506            for (excerpt, range) in
12507                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12508            {
12509                let mut range = range.to_point(excerpt.buffer());
12510                range.start.column = 0;
12511                range.end.column = excerpt.buffer().line_len(range.end.row);
12512                new_selections_by_buffer
12513                    .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12514                    .or_insert(Vec::new())
12515                    .push(range)
12516            }
12517        }
12518
12519        let proposed_changes_buffers = new_selections_by_buffer
12520            .into_iter()
12521            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12522            .collect::<Vec<_>>();
12523        let proposed_changes_editor = cx.new_view(|cx| {
12524            ProposedChangesEditor::new(
12525                "Proposed changes",
12526                proposed_changes_buffers,
12527                self.project.clone(),
12528                cx,
12529            )
12530        });
12531
12532        cx.window_context().defer(move |cx| {
12533            workspace.update(cx, |workspace, cx| {
12534                workspace.active_pane().update(cx, |pane, cx| {
12535                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12536                });
12537            });
12538        });
12539    }
12540
12541    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12542        self.open_excerpts_common(None, true, cx)
12543    }
12544
12545    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12546        self.open_excerpts_common(None, false, cx)
12547    }
12548
12549    fn open_excerpts_common(
12550        &mut self,
12551        jump_data: Option<JumpData>,
12552        split: bool,
12553        cx: &mut ViewContext<Self>,
12554    ) {
12555        let Some(workspace) = self.workspace() else {
12556            cx.propagate();
12557            return;
12558        };
12559
12560        if self.buffer.read(cx).is_singleton() {
12561            cx.propagate();
12562            return;
12563        }
12564
12565        let mut new_selections_by_buffer = HashMap::default();
12566        match &jump_data {
12567            Some(JumpData::MultiBufferPoint {
12568                excerpt_id,
12569                position,
12570                anchor,
12571                line_offset_from_top,
12572            }) => {
12573                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12574                if let Some(buffer) = multi_buffer_snapshot
12575                    .buffer_id_for_excerpt(*excerpt_id)
12576                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12577                {
12578                    let buffer_snapshot = buffer.read(cx).snapshot();
12579                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12580                        language::ToPoint::to_point(anchor, &buffer_snapshot)
12581                    } else {
12582                        buffer_snapshot.clip_point(*position, Bias::Left)
12583                    };
12584                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12585                    new_selections_by_buffer.insert(
12586                        buffer,
12587                        (
12588                            vec![jump_to_offset..jump_to_offset],
12589                            Some(*line_offset_from_top),
12590                        ),
12591                    );
12592                }
12593            }
12594            Some(JumpData::MultiBufferRow {
12595                row,
12596                line_offset_from_top,
12597            }) => {
12598                let point = MultiBufferPoint::new(row.0, 0);
12599                if let Some((buffer, buffer_point, _)) =
12600                    self.buffer.read(cx).point_to_buffer_point(point, cx)
12601                {
12602                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12603                    new_selections_by_buffer
12604                        .entry(buffer)
12605                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
12606                        .0
12607                        .push(buffer_offset..buffer_offset)
12608                }
12609            }
12610            None => {
12611                let selections = self.selections.all::<usize>(cx);
12612                let multi_buffer = self.buffer.read(cx);
12613                for selection in selections {
12614                    for (excerpt, mut range) in multi_buffer
12615                        .snapshot(cx)
12616                        .range_to_buffer_ranges(selection.range())
12617                    {
12618                        // When editing branch buffers, jump to the corresponding location
12619                        // in their base buffer.
12620                        let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12621                        let buffer = buffer_handle.read(cx);
12622                        if let Some(base_buffer) = buffer.base_buffer() {
12623                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12624                            buffer_handle = base_buffer;
12625                        }
12626
12627                        if selection.reversed {
12628                            mem::swap(&mut range.start, &mut range.end);
12629                        }
12630                        new_selections_by_buffer
12631                            .entry(buffer_handle)
12632                            .or_insert((Vec::new(), None))
12633                            .0
12634                            .push(range)
12635                    }
12636                }
12637            }
12638        }
12639
12640        if new_selections_by_buffer.is_empty() {
12641            return;
12642        }
12643
12644        // We defer the pane interaction because we ourselves are a workspace item
12645        // and activating a new item causes the pane to call a method on us reentrantly,
12646        // which panics if we're on the stack.
12647        cx.window_context().defer(move |cx| {
12648            workspace.update(cx, |workspace, cx| {
12649                let pane = if split {
12650                    workspace.adjacent_pane(cx)
12651                } else {
12652                    workspace.active_pane().clone()
12653                };
12654
12655                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12656                    let editor = buffer
12657                        .read(cx)
12658                        .file()
12659                        .is_none()
12660                        .then(|| {
12661                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12662                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12663                            // Instead, we try to activate the existing editor in the pane first.
12664                            let (editor, pane_item_index) =
12665                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12666                                    let editor = item.downcast::<Editor>()?;
12667                                    let singleton_buffer =
12668                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12669                                    if singleton_buffer == buffer {
12670                                        Some((editor, i))
12671                                    } else {
12672                                        None
12673                                    }
12674                                })?;
12675                            pane.update(cx, |pane, cx| {
12676                                pane.activate_item(pane_item_index, true, true, cx)
12677                            });
12678                            Some(editor)
12679                        })
12680                        .flatten()
12681                        .unwrap_or_else(|| {
12682                            workspace.open_project_item::<Self>(
12683                                pane.clone(),
12684                                buffer,
12685                                true,
12686                                true,
12687                                cx,
12688                            )
12689                        });
12690
12691                    editor.update(cx, |editor, cx| {
12692                        let autoscroll = match scroll_offset {
12693                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12694                            None => Autoscroll::newest(),
12695                        };
12696                        let nav_history = editor.nav_history.take();
12697                        editor.change_selections(Some(autoscroll), cx, |s| {
12698                            s.select_ranges(ranges);
12699                        });
12700                        editor.nav_history = nav_history;
12701                    });
12702                }
12703            })
12704        });
12705    }
12706
12707    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12708        let snapshot = self.buffer.read(cx).read(cx);
12709        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12710        Some(
12711            ranges
12712                .iter()
12713                .map(move |range| {
12714                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12715                })
12716                .collect(),
12717        )
12718    }
12719
12720    fn selection_replacement_ranges(
12721        &self,
12722        range: Range<OffsetUtf16>,
12723        cx: &mut AppContext,
12724    ) -> Vec<Range<OffsetUtf16>> {
12725        let selections = self.selections.all::<OffsetUtf16>(cx);
12726        let newest_selection = selections
12727            .iter()
12728            .max_by_key(|selection| selection.id)
12729            .unwrap();
12730        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12731        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12732        let snapshot = self.buffer.read(cx).read(cx);
12733        selections
12734            .into_iter()
12735            .map(|mut selection| {
12736                selection.start.0 =
12737                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12738                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12739                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12740                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12741            })
12742            .collect()
12743    }
12744
12745    fn report_editor_event(
12746        &self,
12747        event_type: &'static str,
12748        file_extension: Option<String>,
12749        cx: &AppContext,
12750    ) {
12751        if cfg!(any(test, feature = "test-support")) {
12752            return;
12753        }
12754
12755        let Some(project) = &self.project else { return };
12756
12757        // If None, we are in a file without an extension
12758        let file = self
12759            .buffer
12760            .read(cx)
12761            .as_singleton()
12762            .and_then(|b| b.read(cx).file());
12763        let file_extension = file_extension.or(file
12764            .as_ref()
12765            .and_then(|file| Path::new(file.file_name(cx)).extension())
12766            .and_then(|e| e.to_str())
12767            .map(|a| a.to_string()));
12768
12769        let vim_mode = cx
12770            .global::<SettingsStore>()
12771            .raw_user_settings()
12772            .get("vim_mode")
12773            == Some(&serde_json::Value::Bool(true));
12774
12775        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12776            == language::language_settings::InlineCompletionProvider::Copilot;
12777        let copilot_enabled_for_language = self
12778            .buffer
12779            .read(cx)
12780            .settings_at(0, cx)
12781            .show_inline_completions;
12782
12783        let project = project.read(cx);
12784        telemetry::event!(
12785            event_type,
12786            file_extension,
12787            vim_mode,
12788            copilot_enabled,
12789            copilot_enabled_for_language,
12790            is_via_ssh = project.is_via_ssh(),
12791        );
12792    }
12793
12794    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12795    /// with each line being an array of {text, highlight} objects.
12796    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12797        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12798            return;
12799        };
12800
12801        #[derive(Serialize)]
12802        struct Chunk<'a> {
12803            text: String,
12804            highlight: Option<&'a str>,
12805        }
12806
12807        let snapshot = buffer.read(cx).snapshot();
12808        let range = self
12809            .selected_text_range(false, cx)
12810            .and_then(|selection| {
12811                if selection.range.is_empty() {
12812                    None
12813                } else {
12814                    Some(selection.range)
12815                }
12816            })
12817            .unwrap_or_else(|| 0..snapshot.len());
12818
12819        let chunks = snapshot.chunks(range, true);
12820        let mut lines = Vec::new();
12821        let mut line: VecDeque<Chunk> = VecDeque::new();
12822
12823        let Some(style) = self.style.as_ref() else {
12824            return;
12825        };
12826
12827        for chunk in chunks {
12828            let highlight = chunk
12829                .syntax_highlight_id
12830                .and_then(|id| id.name(&style.syntax));
12831            let mut chunk_lines = chunk.text.split('\n').peekable();
12832            while let Some(text) = chunk_lines.next() {
12833                let mut merged_with_last_token = false;
12834                if let Some(last_token) = line.back_mut() {
12835                    if last_token.highlight == highlight {
12836                        last_token.text.push_str(text);
12837                        merged_with_last_token = true;
12838                    }
12839                }
12840
12841                if !merged_with_last_token {
12842                    line.push_back(Chunk {
12843                        text: text.into(),
12844                        highlight,
12845                    });
12846                }
12847
12848                if chunk_lines.peek().is_some() {
12849                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12850                        line.pop_front();
12851                    }
12852                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12853                        line.pop_back();
12854                    }
12855
12856                    lines.push(mem::take(&mut line));
12857                }
12858            }
12859        }
12860
12861        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12862            return;
12863        };
12864        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12865    }
12866
12867    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12868        self.request_autoscroll(Autoscroll::newest(), cx);
12869        let position = self.selections.newest_display(cx).start;
12870        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12871    }
12872
12873    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12874        &self.inlay_hint_cache
12875    }
12876
12877    pub fn replay_insert_event(
12878        &mut self,
12879        text: &str,
12880        relative_utf16_range: Option<Range<isize>>,
12881        cx: &mut ViewContext<Self>,
12882    ) {
12883        if !self.input_enabled {
12884            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12885            return;
12886        }
12887        if let Some(relative_utf16_range) = relative_utf16_range {
12888            let selections = self.selections.all::<OffsetUtf16>(cx);
12889            self.change_selections(None, cx, |s| {
12890                let new_ranges = selections.into_iter().map(|range| {
12891                    let start = OffsetUtf16(
12892                        range
12893                            .head()
12894                            .0
12895                            .saturating_add_signed(relative_utf16_range.start),
12896                    );
12897                    let end = OffsetUtf16(
12898                        range
12899                            .head()
12900                            .0
12901                            .saturating_add_signed(relative_utf16_range.end),
12902                    );
12903                    start..end
12904                });
12905                s.select_ranges(new_ranges);
12906            });
12907        }
12908
12909        self.handle_input(text, cx);
12910    }
12911
12912    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12913        let Some(provider) = self.semantics_provider.as_ref() else {
12914            return false;
12915        };
12916
12917        let mut supports = false;
12918        self.buffer().read(cx).for_each_buffer(|buffer| {
12919            supports |= provider.supports_inlay_hints(buffer, cx);
12920        });
12921        supports
12922    }
12923
12924    pub fn focus(&self, cx: &mut WindowContext) {
12925        cx.focus(&self.focus_handle)
12926    }
12927
12928    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12929        self.focus_handle.is_focused(cx)
12930    }
12931
12932    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12933        cx.emit(EditorEvent::Focused);
12934
12935        if let Some(descendant) = self
12936            .last_focused_descendant
12937            .take()
12938            .and_then(|descendant| descendant.upgrade())
12939        {
12940            cx.focus(&descendant);
12941        } else {
12942            if let Some(blame) = self.blame.as_ref() {
12943                blame.update(cx, GitBlame::focus)
12944            }
12945
12946            self.blink_manager.update(cx, BlinkManager::enable);
12947            self.show_cursor_names(cx);
12948            self.buffer.update(cx, |buffer, cx| {
12949                buffer.finalize_last_transaction(cx);
12950                if self.leader_peer_id.is_none() {
12951                    buffer.set_active_selections(
12952                        &self.selections.disjoint_anchors(),
12953                        self.selections.line_mode,
12954                        self.cursor_shape,
12955                        cx,
12956                    );
12957                }
12958            });
12959        }
12960    }
12961
12962    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12963        cx.emit(EditorEvent::FocusedIn)
12964    }
12965
12966    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12967        if event.blurred != self.focus_handle {
12968            self.last_focused_descendant = Some(event.blurred);
12969        }
12970    }
12971
12972    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12973        self.blink_manager.update(cx, BlinkManager::disable);
12974        self.buffer
12975            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12976
12977        if let Some(blame) = self.blame.as_ref() {
12978            blame.update(cx, GitBlame::blur)
12979        }
12980        if !self.hover_state.focused(cx) {
12981            hide_hover(self, cx);
12982        }
12983
12984        self.hide_context_menu(cx);
12985        cx.emit(EditorEvent::Blurred);
12986        cx.notify();
12987    }
12988
12989    pub fn register_action<A: Action>(
12990        &mut self,
12991        listener: impl Fn(&A, &mut WindowContext) + 'static,
12992    ) -> Subscription {
12993        let id = self.next_editor_action_id.post_inc();
12994        let listener = Arc::new(listener);
12995        self.editor_actions.borrow_mut().insert(
12996            id,
12997            Box::new(move |cx| {
12998                let cx = cx.window_context();
12999                let listener = listener.clone();
13000                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13001                    let action = action.downcast_ref().unwrap();
13002                    if phase == DispatchPhase::Bubble {
13003                        listener(action, cx)
13004                    }
13005                })
13006            }),
13007        );
13008
13009        let editor_actions = self.editor_actions.clone();
13010        Subscription::new(move || {
13011            editor_actions.borrow_mut().remove(&id);
13012        })
13013    }
13014
13015    pub fn file_header_size(&self) -> u32 {
13016        FILE_HEADER_HEIGHT
13017    }
13018
13019    pub fn revert(
13020        &mut self,
13021        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13022        cx: &mut ViewContext<Self>,
13023    ) {
13024        self.buffer().update(cx, |multi_buffer, cx| {
13025            for (buffer_id, changes) in revert_changes {
13026                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13027                    buffer.update(cx, |buffer, cx| {
13028                        buffer.edit(
13029                            changes.into_iter().map(|(range, text)| {
13030                                (range, text.to_string().map(Arc::<str>::from))
13031                            }),
13032                            None,
13033                            cx,
13034                        );
13035                    });
13036                }
13037            }
13038        });
13039        self.change_selections(None, cx, |selections| selections.refresh());
13040    }
13041
13042    pub fn to_pixel_point(
13043        &mut self,
13044        source: multi_buffer::Anchor,
13045        editor_snapshot: &EditorSnapshot,
13046        cx: &mut ViewContext<Self>,
13047    ) -> Option<gpui::Point<Pixels>> {
13048        let source_point = source.to_display_point(editor_snapshot);
13049        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13050    }
13051
13052    pub fn display_to_pixel_point(
13053        &self,
13054        source: DisplayPoint,
13055        editor_snapshot: &EditorSnapshot,
13056        cx: &WindowContext,
13057    ) -> Option<gpui::Point<Pixels>> {
13058        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13059        let text_layout_details = self.text_layout_details(cx);
13060        let scroll_top = text_layout_details
13061            .scroll_anchor
13062            .scroll_position(editor_snapshot)
13063            .y;
13064
13065        if source.row().as_f32() < scroll_top.floor() {
13066            return None;
13067        }
13068        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13069        let source_y = line_height * (source.row().as_f32() - scroll_top);
13070        Some(gpui::Point::new(source_x, source_y))
13071    }
13072
13073    pub fn has_active_completions_menu(&self) -> bool {
13074        self.context_menu.borrow().as_ref().map_or(false, |menu| {
13075            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13076        })
13077    }
13078
13079    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13080        self.addons
13081            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13082    }
13083
13084    pub fn unregister_addon<T: Addon>(&mut self) {
13085        self.addons.remove(&std::any::TypeId::of::<T>());
13086    }
13087
13088    pub fn addon<T: Addon>(&self) -> Option<&T> {
13089        let type_id = std::any::TypeId::of::<T>();
13090        self.addons
13091            .get(&type_id)
13092            .and_then(|item| item.to_any().downcast_ref::<T>())
13093    }
13094
13095    pub fn add_change_set(
13096        &mut self,
13097        change_set: Model<BufferChangeSet>,
13098        cx: &mut ViewContext<Self>,
13099    ) {
13100        self.diff_map.add_change_set(change_set, cx);
13101    }
13102
13103    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13104        let text_layout_details = self.text_layout_details(cx);
13105        let style = &text_layout_details.editor_style;
13106        let font_id = cx.text_system().resolve_font(&style.text.font());
13107        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13108        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13109
13110        let em_width = cx
13111            .text_system()
13112            .typographic_bounds(font_id, font_size, 'm')
13113            .unwrap()
13114            .size
13115            .width;
13116
13117        gpui::Point::new(em_width, line_height)
13118    }
13119}
13120
13121fn get_unstaged_changes_for_buffers(
13122    project: &Model<Project>,
13123    buffers: impl IntoIterator<Item = Model<Buffer>>,
13124    cx: &mut ViewContext<Editor>,
13125) {
13126    let mut tasks = Vec::new();
13127    project.update(cx, |project, cx| {
13128        for buffer in buffers {
13129            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13130        }
13131    });
13132    cx.spawn(|this, mut cx| async move {
13133        let change_sets = futures::future::join_all(tasks).await;
13134        this.update(&mut cx, |this, cx| {
13135            for change_set in change_sets {
13136                if let Some(change_set) = change_set.log_err() {
13137                    this.diff_map.add_change_set(change_set, cx);
13138                }
13139            }
13140        })
13141        .ok();
13142    })
13143    .detach();
13144}
13145
13146fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13147    let tab_size = tab_size.get() as usize;
13148    let mut width = offset;
13149
13150    for ch in text.chars() {
13151        width += if ch == '\t' {
13152            tab_size - (width % tab_size)
13153        } else {
13154            1
13155        };
13156    }
13157
13158    width - offset
13159}
13160
13161#[cfg(test)]
13162mod tests {
13163    use super::*;
13164
13165    #[test]
13166    fn test_string_size_with_expanded_tabs() {
13167        let nz = |val| NonZeroU32::new(val).unwrap();
13168        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13169        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13170        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13171        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13172        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13173        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13174        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13175        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13176    }
13177}
13178
13179/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13180struct WordBreakingTokenizer<'a> {
13181    input: &'a str,
13182}
13183
13184impl<'a> WordBreakingTokenizer<'a> {
13185    fn new(input: &'a str) -> Self {
13186        Self { input }
13187    }
13188}
13189
13190fn is_char_ideographic(ch: char) -> bool {
13191    use unicode_script::Script::*;
13192    use unicode_script::UnicodeScript;
13193    matches!(ch.script(), Han | Tangut | Yi)
13194}
13195
13196fn is_grapheme_ideographic(text: &str) -> bool {
13197    text.chars().any(is_char_ideographic)
13198}
13199
13200fn is_grapheme_whitespace(text: &str) -> bool {
13201    text.chars().any(|x| x.is_whitespace())
13202}
13203
13204fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13205    text.chars().next().map_or(false, |ch| {
13206        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13207    })
13208}
13209
13210#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13211struct WordBreakToken<'a> {
13212    token: &'a str,
13213    grapheme_len: usize,
13214    is_whitespace: bool,
13215}
13216
13217impl<'a> Iterator for WordBreakingTokenizer<'a> {
13218    /// Yields a span, the count of graphemes in the token, and whether it was
13219    /// whitespace. Note that it also breaks at word boundaries.
13220    type Item = WordBreakToken<'a>;
13221
13222    fn next(&mut self) -> Option<Self::Item> {
13223        use unicode_segmentation::UnicodeSegmentation;
13224        if self.input.is_empty() {
13225            return None;
13226        }
13227
13228        let mut iter = self.input.graphemes(true).peekable();
13229        let mut offset = 0;
13230        let mut graphemes = 0;
13231        if let Some(first_grapheme) = iter.next() {
13232            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13233            offset += first_grapheme.len();
13234            graphemes += 1;
13235            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13236                if let Some(grapheme) = iter.peek().copied() {
13237                    if should_stay_with_preceding_ideograph(grapheme) {
13238                        offset += grapheme.len();
13239                        graphemes += 1;
13240                    }
13241                }
13242            } else {
13243                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13244                let mut next_word_bound = words.peek().copied();
13245                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13246                    next_word_bound = words.next();
13247                }
13248                while let Some(grapheme) = iter.peek().copied() {
13249                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13250                        break;
13251                    };
13252                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13253                        break;
13254                    };
13255                    offset += grapheme.len();
13256                    graphemes += 1;
13257                    iter.next();
13258                }
13259            }
13260            let token = &self.input[..offset];
13261            self.input = &self.input[offset..];
13262            if is_whitespace {
13263                Some(WordBreakToken {
13264                    token: " ",
13265                    grapheme_len: 1,
13266                    is_whitespace: true,
13267                })
13268            } else {
13269                Some(WordBreakToken {
13270                    token,
13271                    grapheme_len: graphemes,
13272                    is_whitespace: false,
13273                })
13274            }
13275        } else {
13276            None
13277        }
13278    }
13279}
13280
13281#[test]
13282fn test_word_breaking_tokenizer() {
13283    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13284        ("", &[]),
13285        ("  ", &[(" ", 1, true)]),
13286        ("Ʒ", &[("Ʒ", 1, false)]),
13287        ("Ǽ", &[("Ǽ", 1, false)]),
13288        ("", &[("", 1, false)]),
13289        ("⋑⋑", &[("⋑⋑", 2, false)]),
13290        (
13291            "原理,进而",
13292            &[
13293                ("", 1, false),
13294                ("理,", 2, false),
13295                ("", 1, false),
13296                ("", 1, false),
13297            ],
13298        ),
13299        (
13300            "hello world",
13301            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13302        ),
13303        (
13304            "hello, world",
13305            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13306        ),
13307        (
13308            "  hello world",
13309            &[
13310                (" ", 1, true),
13311                ("hello", 5, false),
13312                (" ", 1, true),
13313                ("world", 5, false),
13314            ],
13315        ),
13316        (
13317            "这是什么 \n 钢笔",
13318            &[
13319                ("", 1, false),
13320                ("", 1, false),
13321                ("", 1, false),
13322                ("", 1, false),
13323                (" ", 1, true),
13324                ("", 1, false),
13325                ("", 1, false),
13326            ],
13327        ),
13328        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13329    ];
13330
13331    for (input, result) in tests {
13332        assert_eq!(
13333            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13334            result
13335                .iter()
13336                .copied()
13337                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13338                    token,
13339                    grapheme_len,
13340                    is_whitespace,
13341                })
13342                .collect::<Vec<_>>()
13343        );
13344    }
13345}
13346
13347fn wrap_with_prefix(
13348    line_prefix: String,
13349    unwrapped_text: String,
13350    wrap_column: usize,
13351    tab_size: NonZeroU32,
13352) -> String {
13353    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13354    let mut wrapped_text = String::new();
13355    let mut current_line = line_prefix.clone();
13356
13357    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13358    let mut current_line_len = line_prefix_len;
13359    for WordBreakToken {
13360        token,
13361        grapheme_len,
13362        is_whitespace,
13363    } in tokenizer
13364    {
13365        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13366            wrapped_text.push_str(current_line.trim_end());
13367            wrapped_text.push('\n');
13368            current_line.truncate(line_prefix.len());
13369            current_line_len = line_prefix_len;
13370            if !is_whitespace {
13371                current_line.push_str(token);
13372                current_line_len += grapheme_len;
13373            }
13374        } else if !is_whitespace {
13375            current_line.push_str(token);
13376            current_line_len += grapheme_len;
13377        } else if current_line_len != line_prefix_len {
13378            current_line.push(' ');
13379            current_line_len += 1;
13380        }
13381    }
13382
13383    if !current_line.is_empty() {
13384        wrapped_text.push_str(&current_line);
13385    }
13386    wrapped_text
13387}
13388
13389#[test]
13390fn test_wrap_with_prefix() {
13391    assert_eq!(
13392        wrap_with_prefix(
13393            "# ".to_string(),
13394            "abcdefg".to_string(),
13395            4,
13396            NonZeroU32::new(4).unwrap()
13397        ),
13398        "# abcdefg"
13399    );
13400    assert_eq!(
13401        wrap_with_prefix(
13402            "".to_string(),
13403            "\thello world".to_string(),
13404            8,
13405            NonZeroU32::new(4).unwrap()
13406        ),
13407        "hello\nworld"
13408    );
13409    assert_eq!(
13410        wrap_with_prefix(
13411            "// ".to_string(),
13412            "xx \nyy zz aa bb cc".to_string(),
13413            12,
13414            NonZeroU32::new(4).unwrap()
13415        ),
13416        "// xx yy zz\n// aa bb cc"
13417    );
13418    assert_eq!(
13419        wrap_with_prefix(
13420            String::new(),
13421            "这是什么 \n 钢笔".to_string(),
13422            3,
13423            NonZeroU32::new(4).unwrap()
13424        ),
13425        "这是什\n么 钢\n"
13426    );
13427}
13428
13429fn hunks_for_selections(
13430    snapshot: &EditorSnapshot,
13431    selections: &[Selection<Point>],
13432) -> Vec<MultiBufferDiffHunk> {
13433    hunks_for_ranges(
13434        selections.iter().map(|selection| selection.range()),
13435        snapshot,
13436    )
13437}
13438
13439pub fn hunks_for_ranges(
13440    ranges: impl Iterator<Item = Range<Point>>,
13441    snapshot: &EditorSnapshot,
13442) -> Vec<MultiBufferDiffHunk> {
13443    let mut hunks = Vec::new();
13444    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13445        HashMap::default();
13446    for query_range in ranges {
13447        let query_rows =
13448            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13449        for hunk in snapshot.diff_map.diff_hunks_in_range(
13450            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13451            &snapshot.buffer_snapshot,
13452        ) {
13453            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13454            // when the caret is just above or just below the deleted hunk.
13455            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13456            let related_to_selection = if allow_adjacent {
13457                hunk.row_range.overlaps(&query_rows)
13458                    || hunk.row_range.start == query_rows.end
13459                    || hunk.row_range.end == query_rows.start
13460            } else {
13461                hunk.row_range.overlaps(&query_rows)
13462            };
13463            if related_to_selection {
13464                if !processed_buffer_rows
13465                    .entry(hunk.buffer_id)
13466                    .or_default()
13467                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13468                {
13469                    continue;
13470                }
13471                hunks.push(hunk);
13472            }
13473        }
13474    }
13475
13476    hunks
13477}
13478
13479pub trait CollaborationHub {
13480    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13481    fn user_participant_indices<'a>(
13482        &self,
13483        cx: &'a AppContext,
13484    ) -> &'a HashMap<u64, ParticipantIndex>;
13485    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13486}
13487
13488impl CollaborationHub for Model<Project> {
13489    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13490        self.read(cx).collaborators()
13491    }
13492
13493    fn user_participant_indices<'a>(
13494        &self,
13495        cx: &'a AppContext,
13496    ) -> &'a HashMap<u64, ParticipantIndex> {
13497        self.read(cx).user_store().read(cx).participant_indices()
13498    }
13499
13500    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13501        let this = self.read(cx);
13502        let user_ids = this.collaborators().values().map(|c| c.user_id);
13503        this.user_store().read_with(cx, |user_store, cx| {
13504            user_store.participant_names(user_ids, cx)
13505        })
13506    }
13507}
13508
13509pub trait SemanticsProvider {
13510    fn hover(
13511        &self,
13512        buffer: &Model<Buffer>,
13513        position: text::Anchor,
13514        cx: &mut AppContext,
13515    ) -> Option<Task<Vec<project::Hover>>>;
13516
13517    fn inlay_hints(
13518        &self,
13519        buffer_handle: Model<Buffer>,
13520        range: Range<text::Anchor>,
13521        cx: &mut AppContext,
13522    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13523
13524    fn resolve_inlay_hint(
13525        &self,
13526        hint: InlayHint,
13527        buffer_handle: Model<Buffer>,
13528        server_id: LanguageServerId,
13529        cx: &mut AppContext,
13530    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13531
13532    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13533
13534    fn document_highlights(
13535        &self,
13536        buffer: &Model<Buffer>,
13537        position: text::Anchor,
13538        cx: &mut AppContext,
13539    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13540
13541    fn definitions(
13542        &self,
13543        buffer: &Model<Buffer>,
13544        position: text::Anchor,
13545        kind: GotoDefinitionKind,
13546        cx: &mut AppContext,
13547    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13548
13549    fn range_for_rename(
13550        &self,
13551        buffer: &Model<Buffer>,
13552        position: text::Anchor,
13553        cx: &mut AppContext,
13554    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13555
13556    fn perform_rename(
13557        &self,
13558        buffer: &Model<Buffer>,
13559        position: text::Anchor,
13560        new_name: String,
13561        cx: &mut AppContext,
13562    ) -> Option<Task<Result<ProjectTransaction>>>;
13563}
13564
13565pub trait CompletionProvider {
13566    fn completions(
13567        &self,
13568        buffer: &Model<Buffer>,
13569        buffer_position: text::Anchor,
13570        trigger: CompletionContext,
13571        cx: &mut ViewContext<Editor>,
13572    ) -> Task<Result<Vec<Completion>>>;
13573
13574    fn resolve_completions(
13575        &self,
13576        buffer: Model<Buffer>,
13577        completion_indices: Vec<usize>,
13578        completions: Rc<RefCell<Box<[Completion]>>>,
13579        cx: &mut ViewContext<Editor>,
13580    ) -> Task<Result<bool>>;
13581
13582    fn apply_additional_edits_for_completion(
13583        &self,
13584        _buffer: Model<Buffer>,
13585        _completions: Rc<RefCell<Box<[Completion]>>>,
13586        _completion_index: usize,
13587        _push_to_history: bool,
13588        _cx: &mut ViewContext<Editor>,
13589    ) -> Task<Result<Option<language::Transaction>>> {
13590        Task::ready(Ok(None))
13591    }
13592
13593    fn is_completion_trigger(
13594        &self,
13595        buffer: &Model<Buffer>,
13596        position: language::Anchor,
13597        text: &str,
13598        trigger_in_words: bool,
13599        cx: &mut ViewContext<Editor>,
13600    ) -> bool;
13601
13602    fn sort_completions(&self) -> bool {
13603        true
13604    }
13605}
13606
13607pub trait CodeActionProvider {
13608    fn id(&self) -> Arc<str>;
13609
13610    fn code_actions(
13611        &self,
13612        buffer: &Model<Buffer>,
13613        range: Range<text::Anchor>,
13614        cx: &mut WindowContext,
13615    ) -> Task<Result<Vec<CodeAction>>>;
13616
13617    fn apply_code_action(
13618        &self,
13619        buffer_handle: Model<Buffer>,
13620        action: CodeAction,
13621        excerpt_id: ExcerptId,
13622        push_to_history: bool,
13623        cx: &mut WindowContext,
13624    ) -> Task<Result<ProjectTransaction>>;
13625}
13626
13627impl CodeActionProvider for Model<Project> {
13628    fn id(&self) -> Arc<str> {
13629        "project".into()
13630    }
13631
13632    fn code_actions(
13633        &self,
13634        buffer: &Model<Buffer>,
13635        range: Range<text::Anchor>,
13636        cx: &mut WindowContext,
13637    ) -> Task<Result<Vec<CodeAction>>> {
13638        self.update(cx, |project, cx| {
13639            project.code_actions(buffer, range, None, cx)
13640        })
13641    }
13642
13643    fn apply_code_action(
13644        &self,
13645        buffer_handle: Model<Buffer>,
13646        action: CodeAction,
13647        _excerpt_id: ExcerptId,
13648        push_to_history: bool,
13649        cx: &mut WindowContext,
13650    ) -> Task<Result<ProjectTransaction>> {
13651        self.update(cx, |project, cx| {
13652            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13653        })
13654    }
13655}
13656
13657fn snippet_completions(
13658    project: &Project,
13659    buffer: &Model<Buffer>,
13660    buffer_position: text::Anchor,
13661    cx: &mut AppContext,
13662) -> Task<Result<Vec<Completion>>> {
13663    let language = buffer.read(cx).language_at(buffer_position);
13664    let language_name = language.as_ref().map(|language| language.lsp_id());
13665    let snippet_store = project.snippets().read(cx);
13666    let snippets = snippet_store.snippets_for(language_name, cx);
13667
13668    if snippets.is_empty() {
13669        return Task::ready(Ok(vec![]));
13670    }
13671    let snapshot = buffer.read(cx).text_snapshot();
13672    let chars: String = snapshot
13673        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13674        .collect();
13675
13676    let scope = language.map(|language| language.default_scope());
13677    let executor = cx.background_executor().clone();
13678
13679    cx.background_executor().spawn(async move {
13680        let classifier = CharClassifier::new(scope).for_completion(true);
13681        let mut last_word = chars
13682            .chars()
13683            .take_while(|c| classifier.is_word(*c))
13684            .collect::<String>();
13685        last_word = last_word.chars().rev().collect();
13686
13687        if last_word.is_empty() {
13688            return Ok(vec![]);
13689        }
13690
13691        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13692        let to_lsp = |point: &text::Anchor| {
13693            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13694            point_to_lsp(end)
13695        };
13696        let lsp_end = to_lsp(&buffer_position);
13697
13698        let candidates = snippets
13699            .iter()
13700            .enumerate()
13701            .flat_map(|(ix, snippet)| {
13702                snippet
13703                    .prefix
13704                    .iter()
13705                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13706            })
13707            .collect::<Vec<StringMatchCandidate>>();
13708
13709        let mut matches = fuzzy::match_strings(
13710            &candidates,
13711            &last_word,
13712            last_word.chars().any(|c| c.is_uppercase()),
13713            100,
13714            &Default::default(),
13715            executor,
13716        )
13717        .await;
13718
13719        // Remove all candidates where the query's start does not match the start of any word in the candidate
13720        if let Some(query_start) = last_word.chars().next() {
13721            matches.retain(|string_match| {
13722                split_words(&string_match.string).any(|word| {
13723                    // Check that the first codepoint of the word as lowercase matches the first
13724                    // codepoint of the query as lowercase
13725                    word.chars()
13726                        .flat_map(|codepoint| codepoint.to_lowercase())
13727                        .zip(query_start.to_lowercase())
13728                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13729                })
13730            });
13731        }
13732
13733        let matched_strings = matches
13734            .into_iter()
13735            .map(|m| m.string)
13736            .collect::<HashSet<_>>();
13737
13738        let result: Vec<Completion> = snippets
13739            .into_iter()
13740            .filter_map(|snippet| {
13741                let matching_prefix = snippet
13742                    .prefix
13743                    .iter()
13744                    .find(|prefix| matched_strings.contains(*prefix))?;
13745                let start = as_offset - last_word.len();
13746                let start = snapshot.anchor_before(start);
13747                let range = start..buffer_position;
13748                let lsp_start = to_lsp(&start);
13749                let lsp_range = lsp::Range {
13750                    start: lsp_start,
13751                    end: lsp_end,
13752                };
13753                Some(Completion {
13754                    old_range: range,
13755                    new_text: snippet.body.clone(),
13756                    resolved: false,
13757                    label: CodeLabel {
13758                        text: matching_prefix.clone(),
13759                        runs: vec![],
13760                        filter_range: 0..matching_prefix.len(),
13761                    },
13762                    server_id: LanguageServerId(usize::MAX),
13763                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13764                    lsp_completion: lsp::CompletionItem {
13765                        label: snippet.prefix.first().unwrap().clone(),
13766                        kind: Some(CompletionItemKind::SNIPPET),
13767                        label_details: snippet.description.as_ref().map(|description| {
13768                            lsp::CompletionItemLabelDetails {
13769                                detail: Some(description.clone()),
13770                                description: None,
13771                            }
13772                        }),
13773                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13774                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13775                            lsp::InsertReplaceEdit {
13776                                new_text: snippet.body.clone(),
13777                                insert: lsp_range,
13778                                replace: lsp_range,
13779                            },
13780                        )),
13781                        filter_text: Some(snippet.body.clone()),
13782                        sort_text: Some(char::MAX.to_string()),
13783                        ..Default::default()
13784                    },
13785                    confirm: None,
13786                })
13787            })
13788            .collect();
13789
13790        Ok(result)
13791    })
13792}
13793
13794impl CompletionProvider for Model<Project> {
13795    fn completions(
13796        &self,
13797        buffer: &Model<Buffer>,
13798        buffer_position: text::Anchor,
13799        options: CompletionContext,
13800        cx: &mut ViewContext<Editor>,
13801    ) -> Task<Result<Vec<Completion>>> {
13802        self.update(cx, |project, cx| {
13803            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13804            let project_completions = project.completions(buffer, buffer_position, options, cx);
13805            cx.background_executor().spawn(async move {
13806                let mut completions = project_completions.await?;
13807                let snippets_completions = snippets.await?;
13808                completions.extend(snippets_completions);
13809                Ok(completions)
13810            })
13811        })
13812    }
13813
13814    fn resolve_completions(
13815        &self,
13816        buffer: Model<Buffer>,
13817        completion_indices: Vec<usize>,
13818        completions: Rc<RefCell<Box<[Completion]>>>,
13819        cx: &mut ViewContext<Editor>,
13820    ) -> Task<Result<bool>> {
13821        self.update(cx, |project, cx| {
13822            project.lsp_store().update(cx, |lsp_store, cx| {
13823                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13824            })
13825        })
13826    }
13827
13828    fn apply_additional_edits_for_completion(
13829        &self,
13830        buffer: Model<Buffer>,
13831        completions: Rc<RefCell<Box<[Completion]>>>,
13832        completion_index: usize,
13833        push_to_history: bool,
13834        cx: &mut ViewContext<Editor>,
13835    ) -> Task<Result<Option<language::Transaction>>> {
13836        self.update(cx, |project, cx| {
13837            project.lsp_store().update(cx, |lsp_store, cx| {
13838                lsp_store.apply_additional_edits_for_completion(
13839                    buffer,
13840                    completions,
13841                    completion_index,
13842                    push_to_history,
13843                    cx,
13844                )
13845            })
13846        })
13847    }
13848
13849    fn is_completion_trigger(
13850        &self,
13851        buffer: &Model<Buffer>,
13852        position: language::Anchor,
13853        text: &str,
13854        trigger_in_words: bool,
13855        cx: &mut ViewContext<Editor>,
13856    ) -> bool {
13857        let mut chars = text.chars();
13858        let char = if let Some(char) = chars.next() {
13859            char
13860        } else {
13861            return false;
13862        };
13863        if chars.next().is_some() {
13864            return false;
13865        }
13866
13867        let buffer = buffer.read(cx);
13868        let snapshot = buffer.snapshot();
13869        if !snapshot.settings_at(position, cx).show_completions_on_input {
13870            return false;
13871        }
13872        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13873        if trigger_in_words && classifier.is_word(char) {
13874            return true;
13875        }
13876
13877        buffer.completion_triggers().contains(text)
13878    }
13879}
13880
13881impl SemanticsProvider for Model<Project> {
13882    fn hover(
13883        &self,
13884        buffer: &Model<Buffer>,
13885        position: text::Anchor,
13886        cx: &mut AppContext,
13887    ) -> Option<Task<Vec<project::Hover>>> {
13888        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13889    }
13890
13891    fn document_highlights(
13892        &self,
13893        buffer: &Model<Buffer>,
13894        position: text::Anchor,
13895        cx: &mut AppContext,
13896    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13897        Some(self.update(cx, |project, cx| {
13898            project.document_highlights(buffer, position, cx)
13899        }))
13900    }
13901
13902    fn definitions(
13903        &self,
13904        buffer: &Model<Buffer>,
13905        position: text::Anchor,
13906        kind: GotoDefinitionKind,
13907        cx: &mut AppContext,
13908    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13909        Some(self.update(cx, |project, cx| match kind {
13910            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13911            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13912            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13913            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13914        }))
13915    }
13916
13917    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13918        // TODO: make this work for remote projects
13919        self.read(cx)
13920            .language_servers_for_local_buffer(buffer.read(cx), cx)
13921            .any(
13922                |(_, server)| match server.capabilities().inlay_hint_provider {
13923                    Some(lsp::OneOf::Left(enabled)) => enabled,
13924                    Some(lsp::OneOf::Right(_)) => true,
13925                    None => false,
13926                },
13927            )
13928    }
13929
13930    fn inlay_hints(
13931        &self,
13932        buffer_handle: Model<Buffer>,
13933        range: Range<text::Anchor>,
13934        cx: &mut AppContext,
13935    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13936        Some(self.update(cx, |project, cx| {
13937            project.inlay_hints(buffer_handle, range, cx)
13938        }))
13939    }
13940
13941    fn resolve_inlay_hint(
13942        &self,
13943        hint: InlayHint,
13944        buffer_handle: Model<Buffer>,
13945        server_id: LanguageServerId,
13946        cx: &mut AppContext,
13947    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13948        Some(self.update(cx, |project, cx| {
13949            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13950        }))
13951    }
13952
13953    fn range_for_rename(
13954        &self,
13955        buffer: &Model<Buffer>,
13956        position: text::Anchor,
13957        cx: &mut AppContext,
13958    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13959        Some(self.update(cx, |project, cx| {
13960            let buffer = buffer.clone();
13961            let task = project.prepare_rename(buffer.clone(), position, cx);
13962            cx.spawn(|_, mut cx| async move {
13963                Ok(match task.await? {
13964                    PrepareRenameResponse::Success(range) => Some(range),
13965                    PrepareRenameResponse::InvalidPosition => None,
13966                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
13967                        // Fallback on using TreeSitter info to determine identifier range
13968                        buffer.update(&mut cx, |buffer, _| {
13969                            let snapshot = buffer.snapshot();
13970                            let (range, kind) = snapshot.surrounding_word(position);
13971                            if kind != Some(CharKind::Word) {
13972                                return None;
13973                            }
13974                            Some(
13975                                snapshot.anchor_before(range.start)
13976                                    ..snapshot.anchor_after(range.end),
13977                            )
13978                        })?
13979                    }
13980                })
13981            })
13982        }))
13983    }
13984
13985    fn perform_rename(
13986        &self,
13987        buffer: &Model<Buffer>,
13988        position: text::Anchor,
13989        new_name: String,
13990        cx: &mut AppContext,
13991    ) -> Option<Task<Result<ProjectTransaction>>> {
13992        Some(self.update(cx, |project, cx| {
13993            project.perform_rename(buffer.clone(), position, new_name, cx)
13994        }))
13995    }
13996}
13997
13998fn inlay_hint_settings(
13999    location: Anchor,
14000    snapshot: &MultiBufferSnapshot,
14001    cx: &mut ViewContext<Editor>,
14002) -> InlayHintSettings {
14003    let file = snapshot.file_at(location);
14004    let language = snapshot.language_at(location).map(|l| l.name());
14005    language_settings(language, file, cx).inlay_hints
14006}
14007
14008fn consume_contiguous_rows(
14009    contiguous_row_selections: &mut Vec<Selection<Point>>,
14010    selection: &Selection<Point>,
14011    display_map: &DisplaySnapshot,
14012    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14013) -> (MultiBufferRow, MultiBufferRow) {
14014    contiguous_row_selections.push(selection.clone());
14015    let start_row = MultiBufferRow(selection.start.row);
14016    let mut end_row = ending_row(selection, display_map);
14017
14018    while let Some(next_selection) = selections.peek() {
14019        if next_selection.start.row <= end_row.0 {
14020            end_row = ending_row(next_selection, display_map);
14021            contiguous_row_selections.push(selections.next().unwrap().clone());
14022        } else {
14023            break;
14024        }
14025    }
14026    (start_row, end_row)
14027}
14028
14029fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14030    if next_selection.end.column > 0 || next_selection.is_empty() {
14031        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14032    } else {
14033        MultiBufferRow(next_selection.end.row)
14034    }
14035}
14036
14037impl EditorSnapshot {
14038    pub fn remote_selections_in_range<'a>(
14039        &'a self,
14040        range: &'a Range<Anchor>,
14041        collaboration_hub: &dyn CollaborationHub,
14042        cx: &'a AppContext,
14043    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14044        let participant_names = collaboration_hub.user_names(cx);
14045        let participant_indices = collaboration_hub.user_participant_indices(cx);
14046        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14047        let collaborators_by_replica_id = collaborators_by_peer_id
14048            .iter()
14049            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14050            .collect::<HashMap<_, _>>();
14051        self.buffer_snapshot
14052            .selections_in_range(range, false)
14053            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14054                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14055                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14056                let user_name = participant_names.get(&collaborator.user_id).cloned();
14057                Some(RemoteSelection {
14058                    replica_id,
14059                    selection,
14060                    cursor_shape,
14061                    line_mode,
14062                    participant_index,
14063                    peer_id: collaborator.peer_id,
14064                    user_name,
14065                })
14066            })
14067    }
14068
14069    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14070        self.display_snapshot.buffer_snapshot.language_at(position)
14071    }
14072
14073    pub fn is_focused(&self) -> bool {
14074        self.is_focused
14075    }
14076
14077    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14078        self.placeholder_text.as_ref()
14079    }
14080
14081    pub fn scroll_position(&self) -> gpui::Point<f32> {
14082        self.scroll_anchor.scroll_position(&self.display_snapshot)
14083    }
14084
14085    fn gutter_dimensions(
14086        &self,
14087        font_id: FontId,
14088        font_size: Pixels,
14089        em_width: Pixels,
14090        em_advance: Pixels,
14091        max_line_number_width: Pixels,
14092        cx: &AppContext,
14093    ) -> GutterDimensions {
14094        if !self.show_gutter {
14095            return GutterDimensions::default();
14096        }
14097        let descent = cx.text_system().descent(font_id, font_size);
14098
14099        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14100            matches!(
14101                ProjectSettings::get_global(cx).git.git_gutter,
14102                Some(GitGutterSetting::TrackedFiles)
14103            )
14104        });
14105        let gutter_settings = EditorSettings::get_global(cx).gutter;
14106        let show_line_numbers = self
14107            .show_line_numbers
14108            .unwrap_or(gutter_settings.line_numbers);
14109        let line_gutter_width = if show_line_numbers {
14110            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14111            let min_width_for_number_on_gutter = em_advance * 4.0;
14112            max_line_number_width.max(min_width_for_number_on_gutter)
14113        } else {
14114            0.0.into()
14115        };
14116
14117        let show_code_actions = self
14118            .show_code_actions
14119            .unwrap_or(gutter_settings.code_actions);
14120
14121        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14122
14123        let git_blame_entries_width =
14124            self.git_blame_gutter_max_author_length
14125                .map(|max_author_length| {
14126                    // Length of the author name, but also space for the commit hash,
14127                    // the spacing and the timestamp.
14128                    let max_char_count = max_author_length
14129                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14130                        + 7 // length of commit sha
14131                        + 14 // length of max relative timestamp ("60 minutes ago")
14132                        + 4; // gaps and margins
14133
14134                    em_advance * max_char_count
14135                });
14136
14137        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14138        left_padding += if show_code_actions || show_runnables {
14139            em_width * 3.0
14140        } else if show_git_gutter && show_line_numbers {
14141            em_width * 2.0
14142        } else if show_git_gutter || show_line_numbers {
14143            em_width
14144        } else {
14145            px(0.)
14146        };
14147
14148        let right_padding = if gutter_settings.folds && show_line_numbers {
14149            em_width * 4.0
14150        } else if gutter_settings.folds {
14151            em_width * 3.0
14152        } else if show_line_numbers {
14153            em_width
14154        } else {
14155            px(0.)
14156        };
14157
14158        GutterDimensions {
14159            left_padding,
14160            right_padding,
14161            width: line_gutter_width + left_padding + right_padding,
14162            margin: -descent,
14163            git_blame_entries_width,
14164        }
14165    }
14166
14167    pub fn render_crease_toggle(
14168        &self,
14169        buffer_row: MultiBufferRow,
14170        row_contains_cursor: bool,
14171        editor: View<Editor>,
14172        cx: &mut WindowContext,
14173    ) -> Option<AnyElement> {
14174        let folded = self.is_line_folded(buffer_row);
14175        let mut is_foldable = false;
14176
14177        if let Some(crease) = self
14178            .crease_snapshot
14179            .query_row(buffer_row, &self.buffer_snapshot)
14180        {
14181            is_foldable = true;
14182            match crease {
14183                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14184                    if let Some(render_toggle) = render_toggle {
14185                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14186                            if folded {
14187                                editor.update(cx, |editor, cx| {
14188                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14189                                });
14190                            } else {
14191                                editor.update(cx, |editor, cx| {
14192                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14193                                });
14194                            }
14195                        });
14196                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14197                    }
14198                }
14199            }
14200        }
14201
14202        is_foldable |= self.starts_indent(buffer_row);
14203
14204        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14205            Some(
14206                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14207                    .toggle_state(folded)
14208                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14209                        if folded {
14210                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14211                        } else {
14212                            this.fold_at(&FoldAt { buffer_row }, cx);
14213                        }
14214                    }))
14215                    .into_any_element(),
14216            )
14217        } else {
14218            None
14219        }
14220    }
14221
14222    pub fn render_crease_trailer(
14223        &self,
14224        buffer_row: MultiBufferRow,
14225        cx: &mut WindowContext,
14226    ) -> Option<AnyElement> {
14227        let folded = self.is_line_folded(buffer_row);
14228        if let Crease::Inline { render_trailer, .. } = self
14229            .crease_snapshot
14230            .query_row(buffer_row, &self.buffer_snapshot)?
14231        {
14232            let render_trailer = render_trailer.as_ref()?;
14233            Some(render_trailer(buffer_row, folded, cx))
14234        } else {
14235            None
14236        }
14237    }
14238}
14239
14240impl Deref for EditorSnapshot {
14241    type Target = DisplaySnapshot;
14242
14243    fn deref(&self) -> &Self::Target {
14244        &self.display_snapshot
14245    }
14246}
14247
14248#[derive(Clone, Debug, PartialEq, Eq)]
14249pub enum EditorEvent {
14250    InputIgnored {
14251        text: Arc<str>,
14252    },
14253    InputHandled {
14254        utf16_range_to_replace: Option<Range<isize>>,
14255        text: Arc<str>,
14256    },
14257    ExcerptsAdded {
14258        buffer: Model<Buffer>,
14259        predecessor: ExcerptId,
14260        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14261    },
14262    ExcerptsRemoved {
14263        ids: Vec<ExcerptId>,
14264    },
14265    BufferFoldToggled {
14266        ids: Vec<ExcerptId>,
14267        folded: bool,
14268    },
14269    ExcerptsEdited {
14270        ids: Vec<ExcerptId>,
14271    },
14272    ExcerptsExpanded {
14273        ids: Vec<ExcerptId>,
14274    },
14275    BufferEdited,
14276    Edited {
14277        transaction_id: clock::Lamport,
14278    },
14279    Reparsed(BufferId),
14280    Focused,
14281    FocusedIn,
14282    Blurred,
14283    DirtyChanged,
14284    Saved,
14285    TitleChanged,
14286    DiffBaseChanged,
14287    SelectionsChanged {
14288        local: bool,
14289    },
14290    ScrollPositionChanged {
14291        local: bool,
14292        autoscroll: bool,
14293    },
14294    Closed,
14295    TransactionUndone {
14296        transaction_id: clock::Lamport,
14297    },
14298    TransactionBegun {
14299        transaction_id: clock::Lamport,
14300    },
14301    Reloaded,
14302    CursorShapeChanged,
14303}
14304
14305impl EventEmitter<EditorEvent> for Editor {}
14306
14307impl FocusableView for Editor {
14308    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14309        self.focus_handle.clone()
14310    }
14311}
14312
14313impl Render for Editor {
14314    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14315        let settings = ThemeSettings::get_global(cx);
14316
14317        let mut text_style = match self.mode {
14318            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14319                color: cx.theme().colors().editor_foreground,
14320                font_family: settings.ui_font.family.clone(),
14321                font_features: settings.ui_font.features.clone(),
14322                font_fallbacks: settings.ui_font.fallbacks.clone(),
14323                font_size: rems(0.875).into(),
14324                font_weight: settings.ui_font.weight,
14325                line_height: relative(settings.buffer_line_height.value()),
14326                ..Default::default()
14327            },
14328            EditorMode::Full => TextStyle {
14329                color: cx.theme().colors().editor_foreground,
14330                font_family: settings.buffer_font.family.clone(),
14331                font_features: settings.buffer_font.features.clone(),
14332                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14333                font_size: settings.buffer_font_size(cx).into(),
14334                font_weight: settings.buffer_font.weight,
14335                line_height: relative(settings.buffer_line_height.value()),
14336                ..Default::default()
14337            },
14338        };
14339        if let Some(text_style_refinement) = &self.text_style_refinement {
14340            text_style.refine(text_style_refinement)
14341        }
14342
14343        let background = match self.mode {
14344            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14345            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14346            EditorMode::Full => cx.theme().colors().editor_background,
14347        };
14348
14349        EditorElement::new(
14350            cx.view(),
14351            EditorStyle {
14352                background,
14353                local_player: cx.theme().players().local(),
14354                text: text_style,
14355                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14356                syntax: cx.theme().syntax().clone(),
14357                status: cx.theme().status().clone(),
14358                inlay_hints_style: make_inlay_hints_style(cx),
14359                inline_completion_styles: make_suggestion_styles(cx),
14360                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14361            },
14362        )
14363    }
14364}
14365
14366impl ViewInputHandler for Editor {
14367    fn text_for_range(
14368        &mut self,
14369        range_utf16: Range<usize>,
14370        adjusted_range: &mut Option<Range<usize>>,
14371        cx: &mut ViewContext<Self>,
14372    ) -> Option<String> {
14373        let snapshot = self.buffer.read(cx).read(cx);
14374        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14375        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14376        if (start.0..end.0) != range_utf16 {
14377            adjusted_range.replace(start.0..end.0);
14378        }
14379        Some(snapshot.text_for_range(start..end).collect())
14380    }
14381
14382    fn selected_text_range(
14383        &mut self,
14384        ignore_disabled_input: bool,
14385        cx: &mut ViewContext<Self>,
14386    ) -> Option<UTF16Selection> {
14387        // Prevent the IME menu from appearing when holding down an alphabetic key
14388        // while input is disabled.
14389        if !ignore_disabled_input && !self.input_enabled {
14390            return None;
14391        }
14392
14393        let selection = self.selections.newest::<OffsetUtf16>(cx);
14394        let range = selection.range();
14395
14396        Some(UTF16Selection {
14397            range: range.start.0..range.end.0,
14398            reversed: selection.reversed,
14399        })
14400    }
14401
14402    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14403        let snapshot = self.buffer.read(cx).read(cx);
14404        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14405        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14406    }
14407
14408    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14409        self.clear_highlights::<InputComposition>(cx);
14410        self.ime_transaction.take();
14411    }
14412
14413    fn replace_text_in_range(
14414        &mut self,
14415        range_utf16: Option<Range<usize>>,
14416        text: &str,
14417        cx: &mut ViewContext<Self>,
14418    ) {
14419        if !self.input_enabled {
14420            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14421            return;
14422        }
14423
14424        self.transact(cx, |this, cx| {
14425            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14426                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14427                Some(this.selection_replacement_ranges(range_utf16, cx))
14428            } else {
14429                this.marked_text_ranges(cx)
14430            };
14431
14432            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14433                let newest_selection_id = this.selections.newest_anchor().id;
14434                this.selections
14435                    .all::<OffsetUtf16>(cx)
14436                    .iter()
14437                    .zip(ranges_to_replace.iter())
14438                    .find_map(|(selection, range)| {
14439                        if selection.id == newest_selection_id {
14440                            Some(
14441                                (range.start.0 as isize - selection.head().0 as isize)
14442                                    ..(range.end.0 as isize - selection.head().0 as isize),
14443                            )
14444                        } else {
14445                            None
14446                        }
14447                    })
14448            });
14449
14450            cx.emit(EditorEvent::InputHandled {
14451                utf16_range_to_replace: range_to_replace,
14452                text: text.into(),
14453            });
14454
14455            if let Some(new_selected_ranges) = new_selected_ranges {
14456                this.change_selections(None, cx, |selections| {
14457                    selections.select_ranges(new_selected_ranges)
14458                });
14459                this.backspace(&Default::default(), cx);
14460            }
14461
14462            this.handle_input(text, cx);
14463        });
14464
14465        if let Some(transaction) = self.ime_transaction {
14466            self.buffer.update(cx, |buffer, cx| {
14467                buffer.group_until_transaction(transaction, cx);
14468            });
14469        }
14470
14471        self.unmark_text(cx);
14472    }
14473
14474    fn replace_and_mark_text_in_range(
14475        &mut self,
14476        range_utf16: Option<Range<usize>>,
14477        text: &str,
14478        new_selected_range_utf16: Option<Range<usize>>,
14479        cx: &mut ViewContext<Self>,
14480    ) {
14481        if !self.input_enabled {
14482            return;
14483        }
14484
14485        let transaction = self.transact(cx, |this, cx| {
14486            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14487                let snapshot = this.buffer.read(cx).read(cx);
14488                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14489                    for marked_range in &mut marked_ranges {
14490                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14491                        marked_range.start.0 += relative_range_utf16.start;
14492                        marked_range.start =
14493                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14494                        marked_range.end =
14495                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14496                    }
14497                }
14498                Some(marked_ranges)
14499            } else if let Some(range_utf16) = range_utf16 {
14500                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14501                Some(this.selection_replacement_ranges(range_utf16, cx))
14502            } else {
14503                None
14504            };
14505
14506            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14507                let newest_selection_id = this.selections.newest_anchor().id;
14508                this.selections
14509                    .all::<OffsetUtf16>(cx)
14510                    .iter()
14511                    .zip(ranges_to_replace.iter())
14512                    .find_map(|(selection, range)| {
14513                        if selection.id == newest_selection_id {
14514                            Some(
14515                                (range.start.0 as isize - selection.head().0 as isize)
14516                                    ..(range.end.0 as isize - selection.head().0 as isize),
14517                            )
14518                        } else {
14519                            None
14520                        }
14521                    })
14522            });
14523
14524            cx.emit(EditorEvent::InputHandled {
14525                utf16_range_to_replace: range_to_replace,
14526                text: text.into(),
14527            });
14528
14529            if let Some(ranges) = ranges_to_replace {
14530                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14531            }
14532
14533            let marked_ranges = {
14534                let snapshot = this.buffer.read(cx).read(cx);
14535                this.selections
14536                    .disjoint_anchors()
14537                    .iter()
14538                    .map(|selection| {
14539                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14540                    })
14541                    .collect::<Vec<_>>()
14542            };
14543
14544            if text.is_empty() {
14545                this.unmark_text(cx);
14546            } else {
14547                this.highlight_text::<InputComposition>(
14548                    marked_ranges.clone(),
14549                    HighlightStyle {
14550                        underline: Some(UnderlineStyle {
14551                            thickness: px(1.),
14552                            color: None,
14553                            wavy: false,
14554                        }),
14555                        ..Default::default()
14556                    },
14557                    cx,
14558                );
14559            }
14560
14561            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14562            let use_autoclose = this.use_autoclose;
14563            let use_auto_surround = this.use_auto_surround;
14564            this.set_use_autoclose(false);
14565            this.set_use_auto_surround(false);
14566            this.handle_input(text, cx);
14567            this.set_use_autoclose(use_autoclose);
14568            this.set_use_auto_surround(use_auto_surround);
14569
14570            if let Some(new_selected_range) = new_selected_range_utf16 {
14571                let snapshot = this.buffer.read(cx).read(cx);
14572                let new_selected_ranges = marked_ranges
14573                    .into_iter()
14574                    .map(|marked_range| {
14575                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14576                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14577                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14578                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14579                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14580                    })
14581                    .collect::<Vec<_>>();
14582
14583                drop(snapshot);
14584                this.change_selections(None, cx, |selections| {
14585                    selections.select_ranges(new_selected_ranges)
14586                });
14587            }
14588        });
14589
14590        self.ime_transaction = self.ime_transaction.or(transaction);
14591        if let Some(transaction) = self.ime_transaction {
14592            self.buffer.update(cx, |buffer, cx| {
14593                buffer.group_until_transaction(transaction, cx);
14594            });
14595        }
14596
14597        if self.text_highlights::<InputComposition>(cx).is_none() {
14598            self.ime_transaction.take();
14599        }
14600    }
14601
14602    fn bounds_for_range(
14603        &mut self,
14604        range_utf16: Range<usize>,
14605        element_bounds: gpui::Bounds<Pixels>,
14606        cx: &mut ViewContext<Self>,
14607    ) -> Option<gpui::Bounds<Pixels>> {
14608        let text_layout_details = self.text_layout_details(cx);
14609        let gpui::Point {
14610            x: em_width,
14611            y: line_height,
14612        } = self.character_size(cx);
14613
14614        let snapshot = self.snapshot(cx);
14615        let scroll_position = snapshot.scroll_position();
14616        let scroll_left = scroll_position.x * em_width;
14617
14618        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14619        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14620            + self.gutter_dimensions.width
14621            + self.gutter_dimensions.margin;
14622        let y = line_height * (start.row().as_f32() - scroll_position.y);
14623
14624        Some(Bounds {
14625            origin: element_bounds.origin + point(x, y),
14626            size: size(em_width, line_height),
14627        })
14628    }
14629}
14630
14631trait SelectionExt {
14632    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14633    fn spanned_rows(
14634        &self,
14635        include_end_if_at_line_start: bool,
14636        map: &DisplaySnapshot,
14637    ) -> Range<MultiBufferRow>;
14638}
14639
14640impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14641    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14642        let start = self
14643            .start
14644            .to_point(&map.buffer_snapshot)
14645            .to_display_point(map);
14646        let end = self
14647            .end
14648            .to_point(&map.buffer_snapshot)
14649            .to_display_point(map);
14650        if self.reversed {
14651            end..start
14652        } else {
14653            start..end
14654        }
14655    }
14656
14657    fn spanned_rows(
14658        &self,
14659        include_end_if_at_line_start: bool,
14660        map: &DisplaySnapshot,
14661    ) -> Range<MultiBufferRow> {
14662        let start = self.start.to_point(&map.buffer_snapshot);
14663        let mut end = self.end.to_point(&map.buffer_snapshot);
14664        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14665            end.row -= 1;
14666        }
14667
14668        let buffer_start = map.prev_line_boundary(start).0;
14669        let buffer_end = map.next_line_boundary(end).0;
14670        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14671    }
14672}
14673
14674impl<T: InvalidationRegion> InvalidationStack<T> {
14675    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14676    where
14677        S: Clone + ToOffset,
14678    {
14679        while let Some(region) = self.last() {
14680            let all_selections_inside_invalidation_ranges =
14681                if selections.len() == region.ranges().len() {
14682                    selections
14683                        .iter()
14684                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14685                        .all(|(selection, invalidation_range)| {
14686                            let head = selection.head().to_offset(buffer);
14687                            invalidation_range.start <= head && invalidation_range.end >= head
14688                        })
14689                } else {
14690                    false
14691                };
14692
14693            if all_selections_inside_invalidation_ranges {
14694                break;
14695            } else {
14696                self.pop();
14697            }
14698        }
14699    }
14700}
14701
14702impl<T> Default for InvalidationStack<T> {
14703    fn default() -> Self {
14704        Self(Default::default())
14705    }
14706}
14707
14708impl<T> Deref for InvalidationStack<T> {
14709    type Target = Vec<T>;
14710
14711    fn deref(&self) -> &Self::Target {
14712        &self.0
14713    }
14714}
14715
14716impl<T> DerefMut for InvalidationStack<T> {
14717    fn deref_mut(&mut self) -> &mut Self::Target {
14718        &mut self.0
14719    }
14720}
14721
14722impl InvalidationRegion for SnippetState {
14723    fn ranges(&self) -> &[Range<Anchor>] {
14724        &self.ranges[self.active_index]
14725    }
14726}
14727
14728pub fn diagnostic_block_renderer(
14729    diagnostic: Diagnostic,
14730    max_message_rows: Option<u8>,
14731    allow_closing: bool,
14732    _is_valid: bool,
14733) -> RenderBlock {
14734    let (text_without_backticks, code_ranges) =
14735        highlight_diagnostic_message(&diagnostic, max_message_rows);
14736
14737    Arc::new(move |cx: &mut BlockContext| {
14738        let group_id: SharedString = cx.block_id.to_string().into();
14739
14740        let mut text_style = cx.text_style().clone();
14741        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14742        let theme_settings = ThemeSettings::get_global(cx);
14743        text_style.font_family = theme_settings.buffer_font.family.clone();
14744        text_style.font_style = theme_settings.buffer_font.style;
14745        text_style.font_features = theme_settings.buffer_font.features.clone();
14746        text_style.font_weight = theme_settings.buffer_font.weight;
14747
14748        let multi_line_diagnostic = diagnostic.message.contains('\n');
14749
14750        let buttons = |diagnostic: &Diagnostic| {
14751            if multi_line_diagnostic {
14752                v_flex()
14753            } else {
14754                h_flex()
14755            }
14756            .when(allow_closing, |div| {
14757                div.children(diagnostic.is_primary.then(|| {
14758                    IconButton::new("close-block", IconName::XCircle)
14759                        .icon_color(Color::Muted)
14760                        .size(ButtonSize::Compact)
14761                        .style(ButtonStyle::Transparent)
14762                        .visible_on_hover(group_id.clone())
14763                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14764                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14765                }))
14766            })
14767            .child(
14768                IconButton::new("copy-block", IconName::Copy)
14769                    .icon_color(Color::Muted)
14770                    .size(ButtonSize::Compact)
14771                    .style(ButtonStyle::Transparent)
14772                    .visible_on_hover(group_id.clone())
14773                    .on_click({
14774                        let message = diagnostic.message.clone();
14775                        move |_click, cx| {
14776                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14777                        }
14778                    })
14779                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14780            )
14781        };
14782
14783        let icon_size = buttons(&diagnostic)
14784            .into_any_element()
14785            .layout_as_root(AvailableSpace::min_size(), cx);
14786
14787        h_flex()
14788            .id(cx.block_id)
14789            .group(group_id.clone())
14790            .relative()
14791            .size_full()
14792            .block_mouse_down()
14793            .pl(cx.gutter_dimensions.width)
14794            .w(cx.max_width - cx.gutter_dimensions.full_width())
14795            .child(
14796                div()
14797                    .flex()
14798                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14799                    .flex_shrink(),
14800            )
14801            .child(buttons(&diagnostic))
14802            .child(div().flex().flex_shrink_0().child(
14803                StyledText::new(text_without_backticks.clone()).with_highlights(
14804                    &text_style,
14805                    code_ranges.iter().map(|range| {
14806                        (
14807                            range.clone(),
14808                            HighlightStyle {
14809                                font_weight: Some(FontWeight::BOLD),
14810                                ..Default::default()
14811                            },
14812                        )
14813                    }),
14814                ),
14815            ))
14816            .into_any_element()
14817    })
14818}
14819
14820fn inline_completion_edit_text(
14821    editor_snapshot: &EditorSnapshot,
14822    edits: &Vec<(Range<Anchor>, String)>,
14823    include_deletions: bool,
14824    cx: &WindowContext,
14825) -> InlineCompletionText {
14826    let edit_start = edits
14827        .first()
14828        .unwrap()
14829        .0
14830        .start
14831        .to_display_point(editor_snapshot);
14832
14833    let mut text = String::new();
14834    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14835    let mut highlights = Vec::new();
14836    for (old_range, new_text) in edits {
14837        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14838        text.extend(
14839            editor_snapshot
14840                .buffer_snapshot
14841                .chunks(offset..old_offset_range.start, false)
14842                .map(|chunk| chunk.text),
14843        );
14844        offset = old_offset_range.end;
14845
14846        let start = text.len();
14847        let color = if include_deletions && new_text.is_empty() {
14848            text.extend(
14849                editor_snapshot
14850                    .buffer_snapshot
14851                    .chunks(old_offset_range.start..offset, false)
14852                    .map(|chunk| chunk.text),
14853            );
14854            cx.theme().status().deleted_background
14855        } else {
14856            text.push_str(new_text);
14857            cx.theme().status().created_background
14858        };
14859        let end = text.len();
14860
14861        highlights.push((
14862            start..end,
14863            HighlightStyle {
14864                background_color: Some(color),
14865                ..Default::default()
14866            },
14867        ));
14868    }
14869
14870    let edit_end = edits
14871        .last()
14872        .unwrap()
14873        .0
14874        .end
14875        .to_display_point(editor_snapshot);
14876    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14877        .to_offset(editor_snapshot, Bias::Right);
14878    text.extend(
14879        editor_snapshot
14880            .buffer_snapshot
14881            .chunks(offset..end_of_line, false)
14882            .map(|chunk| chunk.text),
14883    );
14884
14885    InlineCompletionText::Edit {
14886        text: text.into(),
14887        highlights,
14888    }
14889}
14890
14891pub fn highlight_diagnostic_message(
14892    diagnostic: &Diagnostic,
14893    mut max_message_rows: Option<u8>,
14894) -> (SharedString, Vec<Range<usize>>) {
14895    let mut text_without_backticks = String::new();
14896    let mut code_ranges = Vec::new();
14897
14898    if let Some(source) = &diagnostic.source {
14899        text_without_backticks.push_str(source);
14900        code_ranges.push(0..source.len());
14901        text_without_backticks.push_str(": ");
14902    }
14903
14904    let mut prev_offset = 0;
14905    let mut in_code_block = false;
14906    let has_row_limit = max_message_rows.is_some();
14907    let mut newline_indices = diagnostic
14908        .message
14909        .match_indices('\n')
14910        .filter(|_| has_row_limit)
14911        .map(|(ix, _)| ix)
14912        .fuse()
14913        .peekable();
14914
14915    for (quote_ix, _) in diagnostic
14916        .message
14917        .match_indices('`')
14918        .chain([(diagnostic.message.len(), "")])
14919    {
14920        let mut first_newline_ix = None;
14921        let mut last_newline_ix = None;
14922        while let Some(newline_ix) = newline_indices.peek() {
14923            if *newline_ix < quote_ix {
14924                if first_newline_ix.is_none() {
14925                    first_newline_ix = Some(*newline_ix);
14926                }
14927                last_newline_ix = Some(*newline_ix);
14928
14929                if let Some(rows_left) = &mut max_message_rows {
14930                    if *rows_left == 0 {
14931                        break;
14932                    } else {
14933                        *rows_left -= 1;
14934                    }
14935                }
14936                let _ = newline_indices.next();
14937            } else {
14938                break;
14939            }
14940        }
14941        let prev_len = text_without_backticks.len();
14942        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14943        text_without_backticks.push_str(new_text);
14944        if in_code_block {
14945            code_ranges.push(prev_len..text_without_backticks.len());
14946        }
14947        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14948        in_code_block = !in_code_block;
14949        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14950            text_without_backticks.push_str("...");
14951            break;
14952        }
14953    }
14954
14955    (text_without_backticks.into(), code_ranges)
14956}
14957
14958fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14959    match severity {
14960        DiagnosticSeverity::ERROR => colors.error,
14961        DiagnosticSeverity::WARNING => colors.warning,
14962        DiagnosticSeverity::INFORMATION => colors.info,
14963        DiagnosticSeverity::HINT => colors.info,
14964        _ => colors.ignored,
14965    }
14966}
14967
14968pub fn styled_runs_for_code_label<'a>(
14969    label: &'a CodeLabel,
14970    syntax_theme: &'a theme::SyntaxTheme,
14971) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14972    let fade_out = HighlightStyle {
14973        fade_out: Some(0.35),
14974        ..Default::default()
14975    };
14976
14977    let mut prev_end = label.filter_range.end;
14978    label
14979        .runs
14980        .iter()
14981        .enumerate()
14982        .flat_map(move |(ix, (range, highlight_id))| {
14983            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14984                style
14985            } else {
14986                return Default::default();
14987            };
14988            let mut muted_style = style;
14989            muted_style.highlight(fade_out);
14990
14991            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14992            if range.start >= label.filter_range.end {
14993                if range.start > prev_end {
14994                    runs.push((prev_end..range.start, fade_out));
14995                }
14996                runs.push((range.clone(), muted_style));
14997            } else if range.end <= label.filter_range.end {
14998                runs.push((range.clone(), style));
14999            } else {
15000                runs.push((range.start..label.filter_range.end, style));
15001                runs.push((label.filter_range.end..range.end, muted_style));
15002            }
15003            prev_end = cmp::max(prev_end, range.end);
15004
15005            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15006                runs.push((prev_end..label.text.len(), fade_out));
15007            }
15008
15009            runs
15010        })
15011}
15012
15013pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15014    let mut prev_index = 0;
15015    let mut prev_codepoint: Option<char> = None;
15016    text.char_indices()
15017        .chain([(text.len(), '\0')])
15018        .filter_map(move |(index, codepoint)| {
15019            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15020            let is_boundary = index == text.len()
15021                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15022                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15023            if is_boundary {
15024                let chunk = &text[prev_index..index];
15025                prev_index = index;
15026                Some(chunk)
15027            } else {
15028                None
15029            }
15030        })
15031}
15032
15033pub trait RangeToAnchorExt: Sized {
15034    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15035
15036    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15037        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15038        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15039    }
15040}
15041
15042impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15043    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15044        let start_offset = self.start.to_offset(snapshot);
15045        let end_offset = self.end.to_offset(snapshot);
15046        if start_offset == end_offset {
15047            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15048        } else {
15049            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15050        }
15051    }
15052}
15053
15054pub trait RowExt {
15055    fn as_f32(&self) -> f32;
15056
15057    fn next_row(&self) -> Self;
15058
15059    fn previous_row(&self) -> Self;
15060
15061    fn minus(&self, other: Self) -> u32;
15062}
15063
15064impl RowExt for DisplayRow {
15065    fn as_f32(&self) -> f32 {
15066        self.0 as f32
15067    }
15068
15069    fn next_row(&self) -> Self {
15070        Self(self.0 + 1)
15071    }
15072
15073    fn previous_row(&self) -> Self {
15074        Self(self.0.saturating_sub(1))
15075    }
15076
15077    fn minus(&self, other: Self) -> u32 {
15078        self.0 - other.0
15079    }
15080}
15081
15082impl RowExt for MultiBufferRow {
15083    fn as_f32(&self) -> f32 {
15084        self.0 as f32
15085    }
15086
15087    fn next_row(&self) -> Self {
15088        Self(self.0 + 1)
15089    }
15090
15091    fn previous_row(&self) -> Self {
15092        Self(self.0.saturating_sub(1))
15093    }
15094
15095    fn minus(&self, other: Self) -> u32 {
15096        self.0 - other.0
15097    }
15098}
15099
15100trait RowRangeExt {
15101    type Row;
15102
15103    fn len(&self) -> usize;
15104
15105    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15106}
15107
15108impl RowRangeExt for Range<MultiBufferRow> {
15109    type Row = MultiBufferRow;
15110
15111    fn len(&self) -> usize {
15112        (self.end.0 - self.start.0) as usize
15113    }
15114
15115    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15116        (self.start.0..self.end.0).map(MultiBufferRow)
15117    }
15118}
15119
15120impl RowRangeExt for Range<DisplayRow> {
15121    type Row = DisplayRow;
15122
15123    fn len(&self) -> usize {
15124        (self.end.0 - self.start.0) as usize
15125    }
15126
15127    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15128        (self.start.0..self.end.0).map(DisplayRow)
15129    }
15130}
15131
15132fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15133    if hunk.diff_base_byte_range.is_empty() {
15134        DiffHunkStatus::Added
15135    } else if hunk.row_range.is_empty() {
15136        DiffHunkStatus::Removed
15137    } else {
15138        DiffHunkStatus::Modified
15139    }
15140}
15141
15142/// If select range has more than one line, we
15143/// just point the cursor to range.start.
15144fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15145    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15146        range
15147    } else {
15148        range.start..range.start
15149    }
15150}
15151
15152pub struct KillRing(ClipboardItem);
15153impl Global for KillRing {}
15154
15155const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);