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, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
  103    Point, Selection, SelectionGoal, TransactionId,
  104};
  105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  106use linked_editing_ranges::refresh_linked_ranges;
  107use mouse_context_menu::MouseContextMenu;
  108pub use proposed_changes_editor::{
  109    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  110};
  111use similar::{ChangeTag, TextDiff};
  112use std::iter::Peekable;
  113use task::{ResolvedTask, TaskTemplate, TaskVariables};
  114
  115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  116pub use lsp::CompletionContext;
  117use lsp::{
  118    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  119    LanguageServerId, LanguageServerName,
  120};
  121
  122use movement::TextLayoutDetails;
  123pub use multi_buffer::{
  124    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  125    ToPoint,
  126};
  127use multi_buffer::{
  128    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  129};
  130use project::{
  131    buffer_store::BufferChangeSet,
  132    lsp_store::{FormatTarget, FormatTrigger, OpenLspBufferHandle},
  133    project_settings::{GitGutterSetting, ProjectSettings},
  134    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  135    LspStore, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  136};
  137use rand::prelude::*;
  138use rpc::{proto::*, ErrorExt};
  139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  140use selections_collection::{
  141    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  142};
  143use serde::{Deserialize, Serialize};
  144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  145use smallvec::SmallVec;
  146use snippet::Snippet;
  147use std::{
  148    any::TypeId,
  149    borrow::Cow,
  150    cell::RefCell,
  151    cmp::{self, Ordering, Reverse},
  152    mem,
  153    num::NonZeroU32,
  154    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  155    path::{Path, PathBuf},
  156    rc::Rc,
  157    sync::Arc,
  158    time::{Duration, Instant},
  159};
  160pub use sum_tree::Bias;
  161use sum_tree::TreeMap;
  162use text::{BufferId, OffsetUtf16, Rope};
  163use theme::{
  164    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  165    ThemeColors, ThemeSettings,
  166};
  167use ui::{
  168    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  169    PopoverMenuHandle, Tooltip,
  170};
  171use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  172use workspace::item::{ItemHandle, PreviewTabsSettings};
  173use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  174use workspace::{
  175    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  176};
  177use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  178
  179use crate::hover_links::{find_url, find_url_from_range};
  180use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  181
  182pub const FILE_HEADER_HEIGHT: u32 = 2;
  183pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  184pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  185pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  186const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  187const MAX_LINE_LEN: usize = 1024;
  188const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  189const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  190pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  191#[doc(hidden)]
  192pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  193
  194pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  195pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  196
  197pub fn render_parsed_markdown(
  198    element_id: impl Into<ElementId>,
  199    parsed: &language::ParsedMarkdown,
  200    editor_style: &EditorStyle,
  201    workspace: Option<WeakView<Workspace>>,
  202    cx: &mut WindowContext,
  203) -> InteractiveText {
  204    let code_span_background_color = cx
  205        .theme()
  206        .colors()
  207        .editor_document_highlight_read_background;
  208
  209    let highlights = gpui::combine_highlights(
  210        parsed.highlights.iter().filter_map(|(range, highlight)| {
  211            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  212            Some((range.clone(), highlight))
  213        }),
  214        parsed
  215            .regions
  216            .iter()
  217            .zip(&parsed.region_ranges)
  218            .filter_map(|(region, range)| {
  219                if region.code {
  220                    Some((
  221                        range.clone(),
  222                        HighlightStyle {
  223                            background_color: Some(code_span_background_color),
  224                            ..Default::default()
  225                        },
  226                    ))
  227                } else {
  228                    None
  229                }
  230            }),
  231    );
  232
  233    let mut links = Vec::new();
  234    let mut link_ranges = Vec::new();
  235    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  236        if let Some(link) = region.link.clone() {
  237            links.push(link);
  238            link_ranges.push(range.clone());
  239        }
  240    }
  241
  242    InteractiveText::new(
  243        element_id,
  244        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  245    )
  246    .on_click(link_ranges, move |clicked_range_ix, cx| {
  247        match &links[clicked_range_ix] {
  248            markdown::Link::Web { url } => cx.open_url(url),
  249            markdown::Link::Path { path } => {
  250                if let Some(workspace) = &workspace {
  251                    _ = workspace.update(cx, |workspace, cx| {
  252                        workspace.open_abs_path(path.clone(), false, cx).detach();
  253                    });
  254                }
  255            }
  256        }
  257    })
  258}
  259
  260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  261pub(crate) enum InlayId {
  262    InlineCompletion(usize),
  263    Hint(usize),
  264}
  265
  266impl InlayId {
  267    fn id(&self) -> usize {
  268        match self {
  269            Self::InlineCompletion(id) => *id,
  270            Self::Hint(id) => *id,
  271        }
  272    }
  273}
  274
  275enum DiffRowHighlight {}
  276enum DocumentHighlightRead {}
  277enum DocumentHighlightWrite {}
  278enum InputComposition {}
  279
  280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  281pub enum Navigated {
  282    Yes,
  283    No,
  284}
  285
  286impl Navigated {
  287    pub fn from_bool(yes: bool) -> Navigated {
  288        if yes {
  289            Navigated::Yes
  290        } else {
  291            Navigated::No
  292        }
  293    }
  294}
  295
  296pub fn init_settings(cx: &mut AppContext) {
  297    EditorSettings::register(cx);
  298}
  299
  300pub fn init(cx: &mut AppContext) {
  301    init_settings(cx);
  302
  303    workspace::register_project_item::<Editor>(cx);
  304    workspace::FollowableViewRegistry::register::<Editor>(cx);
  305    workspace::register_serializable_item::<Editor>(cx);
  306
  307    cx.observe_new_views(
  308        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  309            workspace.register_action(Editor::new_file);
  310            workspace.register_action(Editor::new_file_vertical);
  311            workspace.register_action(Editor::new_file_horizontal);
  312        },
  313    )
  314    .detach();
  315
  316    cx.on_action(move |_: &workspace::NewFile, cx| {
  317        let app_state = workspace::AppState::global(cx);
  318        if let Some(app_state) = app_state.upgrade() {
  319            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  320                Editor::new_file(workspace, &Default::default(), cx)
  321            })
  322            .detach();
  323        }
  324    });
  325    cx.on_action(move |_: &workspace::NewWindow, cx| {
  326        let app_state = workspace::AppState::global(cx);
  327        if let Some(app_state) = app_state.upgrade() {
  328            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  329                Editor::new_file(workspace, &Default::default(), cx)
  330            })
  331            .detach();
  332        }
  333    });
  334    git::project_diff::init(cx);
  335}
  336
  337pub struct SearchWithinRange;
  338
  339trait InvalidationRegion {
  340    fn ranges(&self) -> &[Range<Anchor>];
  341}
  342
  343#[derive(Clone, Debug, PartialEq)]
  344pub enum SelectPhase {
  345    Begin {
  346        position: DisplayPoint,
  347        add: bool,
  348        click_count: usize,
  349    },
  350    BeginColumnar {
  351        position: DisplayPoint,
  352        reset: bool,
  353        goal_column: u32,
  354    },
  355    Extend {
  356        position: DisplayPoint,
  357        click_count: usize,
  358    },
  359    Update {
  360        position: DisplayPoint,
  361        goal_column: u32,
  362        scroll_delta: gpui::Point<f32>,
  363    },
  364    End,
  365}
  366
  367#[derive(Clone, Debug)]
  368pub enum SelectMode {
  369    Character,
  370    Word(Range<Anchor>),
  371    Line(Range<Anchor>),
  372    All,
  373}
  374
  375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  376pub enum EditorMode {
  377    SingleLine { auto_width: bool },
  378    AutoHeight { max_lines: usize },
  379    Full,
  380}
  381
  382#[derive(Copy, Clone, Debug)]
  383pub enum SoftWrap {
  384    /// Prefer not to wrap at all.
  385    ///
  386    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  387    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  388    GitDiff,
  389    /// Prefer a single line generally, unless an overly long line is encountered.
  390    None,
  391    /// Soft wrap lines that exceed the editor width.
  392    EditorWidth,
  393    /// Soft wrap lines at the preferred line length.
  394    Column(u32),
  395    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  396    Bounded(u32),
  397}
  398
  399#[derive(Clone)]
  400pub struct EditorStyle {
  401    pub background: Hsla,
  402    pub local_player: PlayerColor,
  403    pub text: TextStyle,
  404    pub scrollbar_width: Pixels,
  405    pub syntax: Arc<SyntaxTheme>,
  406    pub status: StatusColors,
  407    pub inlay_hints_style: HighlightStyle,
  408    pub inline_completion_styles: InlineCompletionStyles,
  409    pub unnecessary_code_fade: f32,
  410}
  411
  412impl Default for EditorStyle {
  413    fn default() -> Self {
  414        Self {
  415            background: Hsla::default(),
  416            local_player: PlayerColor::default(),
  417            text: TextStyle::default(),
  418            scrollbar_width: Pixels::default(),
  419            syntax: Default::default(),
  420            // HACK: Status colors don't have a real default.
  421            // We should look into removing the status colors from the editor
  422            // style and retrieve them directly from the theme.
  423            status: StatusColors::dark(),
  424            inlay_hints_style: HighlightStyle::default(),
  425            inline_completion_styles: InlineCompletionStyles {
  426                insertion: HighlightStyle::default(),
  427                whitespace: HighlightStyle::default(),
  428            },
  429            unnecessary_code_fade: Default::default(),
  430        }
  431    }
  432}
  433
  434pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  435    let show_background = language_settings::language_settings(None, None, cx)
  436        .inlay_hints
  437        .show_background;
  438
  439    HighlightStyle {
  440        color: Some(cx.theme().status().hint),
  441        background_color: show_background.then(|| cx.theme().status().hint_background),
  442        ..HighlightStyle::default()
  443    }
  444}
  445
  446pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
  447    InlineCompletionStyles {
  448        insertion: HighlightStyle {
  449            color: Some(cx.theme().status().predictive),
  450            ..HighlightStyle::default()
  451        },
  452        whitespace: HighlightStyle {
  453            background_color: Some(cx.theme().status().created_background),
  454            ..HighlightStyle::default()
  455        },
  456    }
  457}
  458
  459type CompletionId = usize;
  460
  461#[derive(Debug, Clone)]
  462struct InlineCompletionMenuHint {
  463    provider_name: &'static str,
  464    text: InlineCompletionText,
  465}
  466
  467#[derive(Clone, Debug)]
  468enum InlineCompletionText {
  469    Move(SharedString),
  470    Edit {
  471        text: SharedString,
  472        highlights: Vec<(Range<usize>, HighlightStyle)>,
  473    },
  474}
  475
  476enum InlineCompletion {
  477    Edit(Vec<(Range<Anchor>, String)>),
  478    Move(Anchor),
  479}
  480
  481struct InlineCompletionState {
  482    inlay_ids: Vec<InlayId>,
  483    completion: InlineCompletion,
  484    invalidation_range: Range<Anchor>,
  485}
  486
  487enum InlineCompletionHighlight {}
  488
  489#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  490struct EditorActionId(usize);
  491
  492impl EditorActionId {
  493    pub fn post_inc(&mut self) -> Self {
  494        let answer = self.0;
  495
  496        *self = Self(answer + 1);
  497
  498        Self(answer)
  499    }
  500}
  501
  502// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  503// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  504
  505type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  506type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  507
  508#[derive(Default)]
  509struct ScrollbarMarkerState {
  510    scrollbar_size: Size<Pixels>,
  511    dirty: bool,
  512    markers: Arc<[PaintQuad]>,
  513    pending_refresh: Option<Task<Result<()>>>,
  514}
  515
  516impl ScrollbarMarkerState {
  517    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  518        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  519    }
  520}
  521
  522#[derive(Clone, Debug)]
  523struct RunnableTasks {
  524    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  525    offset: MultiBufferOffset,
  526    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  527    column: u32,
  528    // Values of all named captures, including those starting with '_'
  529    extra_variables: HashMap<String, String>,
  530    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  531    context_range: Range<BufferOffset>,
  532}
  533
  534impl RunnableTasks {
  535    fn resolve<'a>(
  536        &'a self,
  537        cx: &'a task::TaskContext,
  538    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  539        self.templates.iter().filter_map(|(kind, template)| {
  540            template
  541                .resolve_task(&kind.to_id_base(), cx)
  542                .map(|task| (kind.clone(), task))
  543        })
  544    }
  545}
  546
  547#[derive(Clone)]
  548struct ResolvedTasks {
  549    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  550    position: Anchor,
  551}
  552#[derive(Copy, Clone, Debug)]
  553struct MultiBufferOffset(usize);
  554#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  555struct BufferOffset(usize);
  556
  557// Addons allow storing per-editor state in other crates (e.g. Vim)
  558pub trait Addon: 'static {
  559    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  560
  561    fn to_any(&self) -> &dyn std::any::Any;
  562}
  563
  564#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  565pub enum IsVimMode {
  566    Yes,
  567    No,
  568}
  569
  570/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  571///
  572/// See the [module level documentation](self) for more information.
  573pub struct Editor {
  574    focus_handle: FocusHandle,
  575    last_focused_descendant: Option<WeakFocusHandle>,
  576    /// The text buffer being edited
  577    buffer: Model<MultiBuffer>,
  578    /// Map of how text in the buffer should be displayed.
  579    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  580    pub display_map: Model<DisplayMap>,
  581    pub selections: SelectionsCollection,
  582    pub scroll_manager: ScrollManager,
  583    /// When inline assist editors are linked, they all render cursors because
  584    /// typing enters text into each of them, even the ones that aren't focused.
  585    pub(crate) show_cursor_when_unfocused: bool,
  586    columnar_selection_tail: Option<Anchor>,
  587    add_selections_state: Option<AddSelectionsState>,
  588    select_next_state: Option<SelectNextState>,
  589    select_prev_state: Option<SelectNextState>,
  590    selection_history: SelectionHistory,
  591    autoclose_regions: Vec<AutocloseRegion>,
  592    snippet_stack: InvalidationStack<SnippetState>,
  593    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  594    ime_transaction: Option<TransactionId>,
  595    active_diagnostics: Option<ActiveDiagnosticGroup>,
  596    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  597
  598    project: Option<Model<Project>>,
  599    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  600    completion_provider: Option<Box<dyn CompletionProvider>>,
  601    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  602    blink_manager: Model<BlinkManager>,
  603    show_cursor_names: bool,
  604    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  605    pub show_local_selections: bool,
  606    mode: EditorMode,
  607    show_breadcrumbs: bool,
  608    show_gutter: bool,
  609    show_scrollbars: bool,
  610    show_line_numbers: Option<bool>,
  611    use_relative_line_numbers: Option<bool>,
  612    show_git_diff_gutter: Option<bool>,
  613    show_code_actions: Option<bool>,
  614    show_runnables: Option<bool>,
  615    show_wrap_guides: Option<bool>,
  616    show_indent_guides: Option<bool>,
  617    placeholder_text: Option<Arc<str>>,
  618    highlight_order: usize,
  619    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  620    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  621    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  622    scrollbar_marker_state: ScrollbarMarkerState,
  623    active_indent_guides_state: ActiveIndentGuidesState,
  624    nav_history: Option<ItemNavHistory>,
  625    context_menu: RefCell<Option<CodeContextMenu>>,
  626    mouse_context_menu: Option<MouseContextMenu>,
  627    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  628    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  629    signature_help_state: SignatureHelpState,
  630    auto_signature_help: Option<bool>,
  631    find_all_references_task_sources: Vec<Anchor>,
  632    next_completion_id: CompletionId,
  633    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  634    code_actions_task: Option<Task<Result<()>>>,
  635    document_highlights_task: Option<Task<()>>,
  636    linked_editing_range_task: Option<Task<Option<()>>>,
  637    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  638    pending_rename: Option<RenameState>,
  639    searchable: bool,
  640    cursor_shape: CursorShape,
  641    current_line_highlight: Option<CurrentLineHighlight>,
  642    collapse_matches: bool,
  643    autoindent_mode: Option<AutoindentMode>,
  644    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  645    input_enabled: bool,
  646    use_modal_editing: bool,
  647    read_only: bool,
  648    leader_peer_id: Option<PeerId>,
  649    remote_id: Option<ViewId>,
  650    hover_state: HoverState,
  651    gutter_hovered: bool,
  652    hovered_link_state: Option<HoveredLinkState>,
  653    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  654    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  655    active_inline_completion: Option<InlineCompletionState>,
  656    // enable_inline_completions is a switch that Vim can use to disable
  657    // inline completions based on its mode.
  658    enable_inline_completions: bool,
  659    show_inline_completions_override: Option<bool>,
  660    inlay_hint_cache: InlayHintCache,
  661    diff_map: DiffMap,
  662    next_inlay_id: usize,
  663    _subscriptions: Vec<Subscription>,
  664    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  665    gutter_dimensions: GutterDimensions,
  666    style: Option<EditorStyle>,
  667    text_style_refinement: Option<TextStyleRefinement>,
  668    next_editor_action_id: EditorActionId,
  669    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  670    use_autoclose: bool,
  671    use_auto_surround: bool,
  672    auto_replace_emoji_shortcode: bool,
  673    show_git_blame_gutter: bool,
  674    show_git_blame_inline: bool,
  675    show_git_blame_inline_delay_task: Option<Task<()>>,
  676    git_blame_inline_enabled: bool,
  677    serialize_dirty_buffers: bool,
  678    show_selection_menu: Option<bool>,
  679    blame: Option<Model<GitBlame>>,
  680    blame_subscription: Option<Subscription>,
  681    custom_context_menu: Option<
  682        Box<
  683            dyn 'static
  684                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  685        >,
  686    >,
  687    last_bounds: Option<Bounds<Pixels>>,
  688    expect_bounds_change: Option<Bounds<Pixels>>,
  689    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  690    tasks_update_task: Option<Task<()>>,
  691    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  692    breadcrumb_header: Option<String>,
  693    focused_block: Option<FocusedBlock>,
  694    next_scroll_position: NextScrollCursorCenterTopBottom,
  695    addons: HashMap<TypeId, Box<dyn Addon>>,
  696    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  697    toggle_fold_multiple_buffers: Task<()>,
  698    _scroll_cursor_center_top_bottom_task: Task<()>,
  699}
  700
  701#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  702enum NextScrollCursorCenterTopBottom {
  703    #[default]
  704    Center,
  705    Top,
  706    Bottom,
  707}
  708
  709impl NextScrollCursorCenterTopBottom {
  710    fn next(&self) -> Self {
  711        match self {
  712            Self::Center => Self::Top,
  713            Self::Top => Self::Bottom,
  714            Self::Bottom => Self::Center,
  715        }
  716    }
  717}
  718
  719#[derive(Clone)]
  720pub struct EditorSnapshot {
  721    pub mode: EditorMode,
  722    show_gutter: bool,
  723    show_line_numbers: Option<bool>,
  724    show_git_diff_gutter: Option<bool>,
  725    show_code_actions: Option<bool>,
  726    show_runnables: Option<bool>,
  727    git_blame_gutter_max_author_length: Option<usize>,
  728    pub display_snapshot: DisplaySnapshot,
  729    pub placeholder_text: Option<Arc<str>>,
  730    diff_map: DiffMapSnapshot,
  731    is_focused: bool,
  732    scroll_anchor: ScrollAnchor,
  733    ongoing_scroll: OngoingScroll,
  734    current_line_highlight: CurrentLineHighlight,
  735    gutter_hovered: bool,
  736}
  737
  738const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  739
  740#[derive(Default, Debug, Clone, Copy)]
  741pub struct GutterDimensions {
  742    pub left_padding: Pixels,
  743    pub right_padding: Pixels,
  744    pub width: Pixels,
  745    pub margin: Pixels,
  746    pub git_blame_entries_width: Option<Pixels>,
  747}
  748
  749impl GutterDimensions {
  750    /// The full width of the space taken up by the gutter.
  751    pub fn full_width(&self) -> Pixels {
  752        self.margin + self.width
  753    }
  754
  755    /// The width of the space reserved for the fold indicators,
  756    /// use alongside 'justify_end' and `gutter_width` to
  757    /// right align content with the line numbers
  758    pub fn fold_area_width(&self) -> Pixels {
  759        self.margin + self.right_padding
  760    }
  761}
  762
  763#[derive(Debug)]
  764pub struct RemoteSelection {
  765    pub replica_id: ReplicaId,
  766    pub selection: Selection<Anchor>,
  767    pub cursor_shape: CursorShape,
  768    pub peer_id: PeerId,
  769    pub line_mode: bool,
  770    pub participant_index: Option<ParticipantIndex>,
  771    pub user_name: Option<SharedString>,
  772}
  773
  774#[derive(Clone, Debug)]
  775struct SelectionHistoryEntry {
  776    selections: Arc<[Selection<Anchor>]>,
  777    select_next_state: Option<SelectNextState>,
  778    select_prev_state: Option<SelectNextState>,
  779    add_selections_state: Option<AddSelectionsState>,
  780}
  781
  782enum SelectionHistoryMode {
  783    Normal,
  784    Undoing,
  785    Redoing,
  786}
  787
  788#[derive(Clone, PartialEq, Eq, Hash)]
  789struct HoveredCursor {
  790    replica_id: u16,
  791    selection_id: usize,
  792}
  793
  794impl Default for SelectionHistoryMode {
  795    fn default() -> Self {
  796        Self::Normal
  797    }
  798}
  799
  800#[derive(Default)]
  801struct SelectionHistory {
  802    #[allow(clippy::type_complexity)]
  803    selections_by_transaction:
  804        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  805    mode: SelectionHistoryMode,
  806    undo_stack: VecDeque<SelectionHistoryEntry>,
  807    redo_stack: VecDeque<SelectionHistoryEntry>,
  808}
  809
  810impl SelectionHistory {
  811    fn insert_transaction(
  812        &mut self,
  813        transaction_id: TransactionId,
  814        selections: Arc<[Selection<Anchor>]>,
  815    ) {
  816        self.selections_by_transaction
  817            .insert(transaction_id, (selections, None));
  818    }
  819
  820    #[allow(clippy::type_complexity)]
  821    fn transaction(
  822        &self,
  823        transaction_id: TransactionId,
  824    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  825        self.selections_by_transaction.get(&transaction_id)
  826    }
  827
  828    #[allow(clippy::type_complexity)]
  829    fn transaction_mut(
  830        &mut self,
  831        transaction_id: TransactionId,
  832    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  833        self.selections_by_transaction.get_mut(&transaction_id)
  834    }
  835
  836    fn push(&mut self, entry: SelectionHistoryEntry) {
  837        if !entry.selections.is_empty() {
  838            match self.mode {
  839                SelectionHistoryMode::Normal => {
  840                    self.push_undo(entry);
  841                    self.redo_stack.clear();
  842                }
  843                SelectionHistoryMode::Undoing => self.push_redo(entry),
  844                SelectionHistoryMode::Redoing => self.push_undo(entry),
  845            }
  846        }
  847    }
  848
  849    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  850        if self
  851            .undo_stack
  852            .back()
  853            .map_or(true, |e| e.selections != entry.selections)
  854        {
  855            self.undo_stack.push_back(entry);
  856            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  857                self.undo_stack.pop_front();
  858            }
  859        }
  860    }
  861
  862    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  863        if self
  864            .redo_stack
  865            .back()
  866            .map_or(true, |e| e.selections != entry.selections)
  867        {
  868            self.redo_stack.push_back(entry);
  869            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  870                self.redo_stack.pop_front();
  871            }
  872        }
  873    }
  874}
  875
  876struct RowHighlight {
  877    index: usize,
  878    range: Range<Anchor>,
  879    color: Hsla,
  880    should_autoscroll: bool,
  881}
  882
  883#[derive(Clone, Debug)]
  884struct AddSelectionsState {
  885    above: bool,
  886    stack: Vec<usize>,
  887}
  888
  889#[derive(Clone)]
  890struct SelectNextState {
  891    query: AhoCorasick,
  892    wordwise: bool,
  893    done: bool,
  894}
  895
  896impl std::fmt::Debug for SelectNextState {
  897    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  898        f.debug_struct(std::any::type_name::<Self>())
  899            .field("wordwise", &self.wordwise)
  900            .field("done", &self.done)
  901            .finish()
  902    }
  903}
  904
  905#[derive(Debug)]
  906struct AutocloseRegion {
  907    selection_id: usize,
  908    range: Range<Anchor>,
  909    pair: BracketPair,
  910}
  911
  912#[derive(Debug)]
  913struct SnippetState {
  914    ranges: Vec<Vec<Range<Anchor>>>,
  915    active_index: usize,
  916    choices: Vec<Option<Vec<String>>>,
  917}
  918
  919#[doc(hidden)]
  920pub struct RenameState {
  921    pub range: Range<Anchor>,
  922    pub old_name: Arc<str>,
  923    pub editor: View<Editor>,
  924    block_id: CustomBlockId,
  925}
  926
  927struct InvalidationStack<T>(Vec<T>);
  928
  929struct RegisteredInlineCompletionProvider {
  930    provider: Arc<dyn InlineCompletionProviderHandle>,
  931    _subscription: Subscription,
  932}
  933
  934#[derive(Debug)]
  935struct ActiveDiagnosticGroup {
  936    primary_range: Range<Anchor>,
  937    primary_message: String,
  938    group_id: usize,
  939    blocks: HashMap<CustomBlockId, Diagnostic>,
  940    is_valid: bool,
  941}
  942
  943#[derive(Serialize, Deserialize, Clone, Debug)]
  944pub struct ClipboardSelection {
  945    pub len: usize,
  946    pub is_entire_line: bool,
  947    pub first_line_indent: u32,
  948}
  949
  950#[derive(Debug)]
  951pub(crate) struct NavigationData {
  952    cursor_anchor: Anchor,
  953    cursor_position: Point,
  954    scroll_anchor: ScrollAnchor,
  955    scroll_top_row: u32,
  956}
  957
  958#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  959pub enum GotoDefinitionKind {
  960    Symbol,
  961    Declaration,
  962    Type,
  963    Implementation,
  964}
  965
  966#[derive(Debug, Clone)]
  967enum InlayHintRefreshReason {
  968    Toggle(bool),
  969    SettingsChange(InlayHintSettings),
  970    NewLinesShown,
  971    BufferEdited(HashSet<Arc<Language>>),
  972    RefreshRequested,
  973    ExcerptsRemoved(Vec<ExcerptId>),
  974}
  975
  976impl InlayHintRefreshReason {
  977    fn description(&self) -> &'static str {
  978        match self {
  979            Self::Toggle(_) => "toggle",
  980            Self::SettingsChange(_) => "settings change",
  981            Self::NewLinesShown => "new lines shown",
  982            Self::BufferEdited(_) => "buffer edited",
  983            Self::RefreshRequested => "refresh requested",
  984            Self::ExcerptsRemoved(_) => "excerpts removed",
  985        }
  986    }
  987}
  988
  989pub(crate) struct FocusedBlock {
  990    id: BlockId,
  991    focus_handle: WeakFocusHandle,
  992}
  993
  994#[derive(Clone)]
  995struct JumpData {
  996    excerpt_id: ExcerptId,
  997    position: Point,
  998    anchor: text::Anchor,
  999    path: Option<project::ProjectPath>,
 1000    line_offset_from_top: u32,
 1001}
 1002
 1003impl Editor {
 1004    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1005        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1006        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1007        Self::new(
 1008            EditorMode::SingleLine { auto_width: false },
 1009            buffer,
 1010            None,
 1011            false,
 1012            cx,
 1013        )
 1014    }
 1015
 1016    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1017        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1018        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1019        Self::new(EditorMode::Full, buffer, None, false, cx)
 1020    }
 1021
 1022    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1023        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1024        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1025        Self::new(
 1026            EditorMode::SingleLine { auto_width: true },
 1027            buffer,
 1028            None,
 1029            false,
 1030            cx,
 1031        )
 1032    }
 1033
 1034    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1035        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1036        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1037        Self::new(
 1038            EditorMode::AutoHeight { max_lines },
 1039            buffer,
 1040            None,
 1041            false,
 1042            cx,
 1043        )
 1044    }
 1045
 1046    pub fn for_buffer(
 1047        buffer: Model<Buffer>,
 1048        project: Option<Model<Project>>,
 1049        cx: &mut ViewContext<Self>,
 1050    ) -> Self {
 1051        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1052        Self::new(EditorMode::Full, buffer, project, false, cx)
 1053    }
 1054
 1055    pub fn for_multibuffer(
 1056        buffer: Model<MultiBuffer>,
 1057        project: Option<Model<Project>>,
 1058        show_excerpt_controls: bool,
 1059        cx: &mut ViewContext<Self>,
 1060    ) -> Self {
 1061        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1062    }
 1063
 1064    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1065        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1066        let mut clone = Self::new(
 1067            self.mode,
 1068            self.buffer.clone(),
 1069            self.project.clone(),
 1070            show_excerpt_controls,
 1071            cx,
 1072        );
 1073        self.display_map.update(cx, |display_map, cx| {
 1074            let snapshot = display_map.snapshot(cx);
 1075            clone.display_map.update(cx, |display_map, cx| {
 1076                display_map.set_state(&snapshot, cx);
 1077            });
 1078        });
 1079        clone.selections.clone_state(&self.selections);
 1080        clone.scroll_manager.clone_state(&self.scroll_manager);
 1081        clone.searchable = self.searchable;
 1082        clone
 1083    }
 1084
 1085    pub fn new(
 1086        mode: EditorMode,
 1087        buffer: Model<MultiBuffer>,
 1088        project: Option<Model<Project>>,
 1089        show_excerpt_controls: bool,
 1090        cx: &mut ViewContext<Self>,
 1091    ) -> Self {
 1092        let style = cx.text_style();
 1093        let font_size = style.font_size.to_pixels(cx.rem_size());
 1094        let editor = cx.view().downgrade();
 1095        let fold_placeholder = FoldPlaceholder {
 1096            constrain_width: true,
 1097            render: Arc::new(move |fold_id, fold_range, cx| {
 1098                let editor = editor.clone();
 1099                div()
 1100                    .id(fold_id)
 1101                    .bg(cx.theme().colors().ghost_element_background)
 1102                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1103                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1104                    .rounded_sm()
 1105                    .size_full()
 1106                    .cursor_pointer()
 1107                    .child("")
 1108                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1109                    .on_click(move |_, cx| {
 1110                        editor
 1111                            .update(cx, |editor, cx| {
 1112                                editor.unfold_ranges(
 1113                                    &[fold_range.start..fold_range.end],
 1114                                    true,
 1115                                    false,
 1116                                    cx,
 1117                                );
 1118                                cx.stop_propagation();
 1119                            })
 1120                            .ok();
 1121                    })
 1122                    .into_any()
 1123            }),
 1124            merge_adjacent: true,
 1125            ..Default::default()
 1126        };
 1127        let display_map = cx.new_model(|cx| {
 1128            DisplayMap::new(
 1129                buffer.clone(),
 1130                style.font(),
 1131                font_size,
 1132                None,
 1133                show_excerpt_controls,
 1134                FILE_HEADER_HEIGHT,
 1135                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1136                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1137                fold_placeholder,
 1138                cx,
 1139            )
 1140        });
 1141
 1142        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1143
 1144        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1145
 1146        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1147            .then(|| language_settings::SoftWrap::None);
 1148
 1149        let mut project_subscriptions = Vec::new();
 1150        if mode == EditorMode::Full {
 1151            if let Some(project) = project.as_ref() {
 1152                if buffer.read(cx).is_singleton() {
 1153                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1154                        cx.emit(EditorEvent::TitleChanged);
 1155                    }));
 1156                }
 1157                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1158                    if let project::Event::RefreshInlayHints = event {
 1159                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1160                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1161                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1162                            let focus_handle = editor.focus_handle(cx);
 1163                            if focus_handle.is_focused(cx) {
 1164                                let snapshot = buffer.read(cx).snapshot();
 1165                                for (range, snippet) in snippet_edits {
 1166                                    let editor_range =
 1167                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1168                                    editor
 1169                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1170                                        .ok();
 1171                                }
 1172                            }
 1173                        }
 1174                    }
 1175                }));
 1176                if let Some(task_inventory) = project
 1177                    .read(cx)
 1178                    .task_store()
 1179                    .read(cx)
 1180                    .task_inventory()
 1181                    .cloned()
 1182                {
 1183                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1184                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1185                    }));
 1186                }
 1187            }
 1188        }
 1189
 1190        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1191
 1192        let inlay_hint_settings =
 1193            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1194        let focus_handle = cx.focus_handle();
 1195        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1196        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1197            .detach();
 1198        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1199            .detach();
 1200        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1201
 1202        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1203            Some(false)
 1204        } else {
 1205            None
 1206        };
 1207
 1208        let mut code_action_providers = Vec::new();
 1209        if let Some(project) = project.clone() {
 1210            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1211            code_action_providers.push(Rc::new(project) as Rc<_>);
 1212        }
 1213
 1214        let mut this = Self {
 1215            focus_handle,
 1216            show_cursor_when_unfocused: false,
 1217            last_focused_descendant: None,
 1218            buffer: buffer.clone(),
 1219            display_map: display_map.clone(),
 1220            selections,
 1221            scroll_manager: ScrollManager::new(cx),
 1222            columnar_selection_tail: None,
 1223            add_selections_state: None,
 1224            select_next_state: None,
 1225            select_prev_state: None,
 1226            selection_history: Default::default(),
 1227            autoclose_regions: Default::default(),
 1228            snippet_stack: Default::default(),
 1229            select_larger_syntax_node_stack: Vec::new(),
 1230            ime_transaction: Default::default(),
 1231            active_diagnostics: None,
 1232            soft_wrap_mode_override,
 1233            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1234            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1235            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1236            project,
 1237            blink_manager: blink_manager.clone(),
 1238            show_local_selections: true,
 1239            show_scrollbars: true,
 1240            mode,
 1241            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1242            show_gutter: mode == EditorMode::Full,
 1243            show_line_numbers: None,
 1244            use_relative_line_numbers: None,
 1245            show_git_diff_gutter: None,
 1246            show_code_actions: None,
 1247            show_runnables: None,
 1248            show_wrap_guides: None,
 1249            show_indent_guides,
 1250            placeholder_text: None,
 1251            highlight_order: 0,
 1252            highlighted_rows: HashMap::default(),
 1253            background_highlights: Default::default(),
 1254            gutter_highlights: TreeMap::default(),
 1255            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1256            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1257            nav_history: None,
 1258            context_menu: RefCell::new(None),
 1259            mouse_context_menu: None,
 1260            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1261            completion_tasks: Default::default(),
 1262            signature_help_state: SignatureHelpState::default(),
 1263            auto_signature_help: None,
 1264            find_all_references_task_sources: Vec::new(),
 1265            next_completion_id: 0,
 1266            next_inlay_id: 0,
 1267            code_action_providers,
 1268            available_code_actions: Default::default(),
 1269            code_actions_task: Default::default(),
 1270            document_highlights_task: Default::default(),
 1271            linked_editing_range_task: Default::default(),
 1272            pending_rename: Default::default(),
 1273            searchable: true,
 1274            cursor_shape: EditorSettings::get_global(cx)
 1275                .cursor_shape
 1276                .unwrap_or_default(),
 1277            current_line_highlight: None,
 1278            autoindent_mode: Some(AutoindentMode::EachLine),
 1279            collapse_matches: false,
 1280            workspace: None,
 1281            input_enabled: true,
 1282            use_modal_editing: mode == EditorMode::Full,
 1283            read_only: false,
 1284            use_autoclose: true,
 1285            use_auto_surround: true,
 1286            auto_replace_emoji_shortcode: false,
 1287            leader_peer_id: None,
 1288            remote_id: None,
 1289            hover_state: Default::default(),
 1290            hovered_link_state: Default::default(),
 1291            inline_completion_provider: None,
 1292            active_inline_completion: None,
 1293            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1294            diff_map: DiffMap::default(),
 1295            gutter_hovered: false,
 1296            pixel_position_of_newest_cursor: None,
 1297            last_bounds: None,
 1298            expect_bounds_change: None,
 1299            gutter_dimensions: GutterDimensions::default(),
 1300            style: None,
 1301            show_cursor_names: false,
 1302            hovered_cursors: Default::default(),
 1303            next_editor_action_id: EditorActionId::default(),
 1304            editor_actions: Rc::default(),
 1305            show_inline_completions_override: None,
 1306            enable_inline_completions: true,
 1307            custom_context_menu: None,
 1308            show_git_blame_gutter: false,
 1309            show_git_blame_inline: false,
 1310            show_selection_menu: None,
 1311            show_git_blame_inline_delay_task: None,
 1312            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1313            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1314                .session
 1315                .restore_unsaved_buffers,
 1316            blame: None,
 1317            blame_subscription: None,
 1318            tasks: Default::default(),
 1319            _subscriptions: vec![
 1320                cx.observe(&buffer, Self::on_buffer_changed),
 1321                cx.subscribe(&buffer, Self::on_buffer_event),
 1322                cx.observe(&display_map, Self::on_display_map_changed),
 1323                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1324                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1325                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1326                cx.observe_window_activation(|editor, cx| {
 1327                    let active = cx.is_window_active();
 1328                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1329                        if active {
 1330                            blink_manager.enable(cx);
 1331                        } else {
 1332                            blink_manager.disable(cx);
 1333                        }
 1334                    });
 1335                }),
 1336            ],
 1337            tasks_update_task: None,
 1338            linked_edit_ranges: Default::default(),
 1339            previous_search_ranges: None,
 1340            breadcrumb_header: None,
 1341            focused_block: None,
 1342            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1343            addons: HashMap::default(),
 1344            registered_buffers: HashMap::default(),
 1345            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1346            toggle_fold_multiple_buffers: Task::ready(()),
 1347            text_style_refinement: None,
 1348        };
 1349        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1350        this._subscriptions.extend(project_subscriptions);
 1351
 1352        this.end_selection(cx);
 1353        this.scroll_manager.show_scrollbar(cx);
 1354
 1355        if mode == EditorMode::Full {
 1356            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1357            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1358
 1359            if this.git_blame_inline_enabled {
 1360                this.git_blame_inline_enabled = true;
 1361                this.start_git_blame_inline(false, cx);
 1362            }
 1363
 1364            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1365                if let Some(project) = this.project.as_ref() {
 1366                    let lsp_store = project.read(cx).lsp_store();
 1367                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1368                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1369                    });
 1370                    this.registered_buffers
 1371                        .insert(buffer.read(cx).remote_id(), handle);
 1372                }
 1373            }
 1374        }
 1375
 1376        this.report_editor_event("Editor Opened", None, cx);
 1377        this
 1378    }
 1379
 1380    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1381        self.mouse_context_menu
 1382            .as_ref()
 1383            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1384    }
 1385
 1386    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1387        let mut key_context = KeyContext::new_with_defaults();
 1388        key_context.add("Editor");
 1389        let mode = match self.mode {
 1390            EditorMode::SingleLine { .. } => "single_line",
 1391            EditorMode::AutoHeight { .. } => "auto_height",
 1392            EditorMode::Full => "full",
 1393        };
 1394
 1395        if EditorSettings::jupyter_enabled(cx) {
 1396            key_context.add("jupyter");
 1397        }
 1398
 1399        key_context.set("mode", mode);
 1400        if self.pending_rename.is_some() {
 1401            key_context.add("renaming");
 1402        }
 1403        match self.context_menu.borrow().as_ref() {
 1404            Some(CodeContextMenu::Completions(_)) => {
 1405                key_context.add("menu");
 1406                key_context.add("showing_completions")
 1407            }
 1408            Some(CodeContextMenu::CodeActions(_)) => {
 1409                key_context.add("menu");
 1410                key_context.add("showing_code_actions")
 1411            }
 1412            None => {}
 1413        }
 1414
 1415        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1416        if !self.focus_handle(cx).contains_focused(cx)
 1417            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1418        {
 1419            for addon in self.addons.values() {
 1420                addon.extend_key_context(&mut key_context, cx)
 1421            }
 1422        }
 1423
 1424        if let Some(extension) = self
 1425            .buffer
 1426            .read(cx)
 1427            .as_singleton()
 1428            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1429        {
 1430            key_context.set("extension", extension.to_string());
 1431        }
 1432
 1433        if self.has_active_inline_completion() {
 1434            key_context.add("copilot_suggestion");
 1435            key_context.add("inline_completion");
 1436        }
 1437
 1438        if !self
 1439            .selections
 1440            .disjoint
 1441            .iter()
 1442            .all(|selection| selection.start == selection.end)
 1443        {
 1444            key_context.add("selection");
 1445        }
 1446
 1447        key_context
 1448    }
 1449
 1450    pub fn new_file(
 1451        workspace: &mut Workspace,
 1452        _: &workspace::NewFile,
 1453        cx: &mut ViewContext<Workspace>,
 1454    ) {
 1455        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1456            "Failed to create buffer",
 1457            cx,
 1458            |e, _| match e.error_code() {
 1459                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1460                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1461                e.error_tag("required").unwrap_or("the latest version")
 1462            )),
 1463                _ => None,
 1464            },
 1465        );
 1466    }
 1467
 1468    pub fn new_in_workspace(
 1469        workspace: &mut Workspace,
 1470        cx: &mut ViewContext<Workspace>,
 1471    ) -> Task<Result<View<Editor>>> {
 1472        let project = workspace.project().clone();
 1473        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1474
 1475        cx.spawn(|workspace, mut cx| async move {
 1476            let buffer = create.await?;
 1477            workspace.update(&mut cx, |workspace, cx| {
 1478                let editor =
 1479                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1480                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1481                editor
 1482            })
 1483        })
 1484    }
 1485
 1486    fn new_file_vertical(
 1487        workspace: &mut Workspace,
 1488        _: &workspace::NewFileSplitVertical,
 1489        cx: &mut ViewContext<Workspace>,
 1490    ) {
 1491        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1492    }
 1493
 1494    fn new_file_horizontal(
 1495        workspace: &mut Workspace,
 1496        _: &workspace::NewFileSplitHorizontal,
 1497        cx: &mut ViewContext<Workspace>,
 1498    ) {
 1499        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1500    }
 1501
 1502    fn new_file_in_direction(
 1503        workspace: &mut Workspace,
 1504        direction: SplitDirection,
 1505        cx: &mut ViewContext<Workspace>,
 1506    ) {
 1507        let project = workspace.project().clone();
 1508        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1509
 1510        cx.spawn(|workspace, mut cx| async move {
 1511            let buffer = create.await?;
 1512            workspace.update(&mut cx, move |workspace, cx| {
 1513                workspace.split_item(
 1514                    direction,
 1515                    Box::new(
 1516                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1517                    ),
 1518                    cx,
 1519                )
 1520            })?;
 1521            anyhow::Ok(())
 1522        })
 1523        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1524            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1525                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1526                e.error_tag("required").unwrap_or("the latest version")
 1527            )),
 1528            _ => None,
 1529        });
 1530    }
 1531
 1532    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1533        self.leader_peer_id
 1534    }
 1535
 1536    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1537        &self.buffer
 1538    }
 1539
 1540    pub fn workspace(&self) -> Option<View<Workspace>> {
 1541        self.workspace.as_ref()?.0.upgrade()
 1542    }
 1543
 1544    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1545        self.buffer().read(cx).title(cx)
 1546    }
 1547
 1548    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1549        let git_blame_gutter_max_author_length = self
 1550            .render_git_blame_gutter(cx)
 1551            .then(|| {
 1552                if let Some(blame) = self.blame.as_ref() {
 1553                    let max_author_length =
 1554                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1555                    Some(max_author_length)
 1556                } else {
 1557                    None
 1558                }
 1559            })
 1560            .flatten();
 1561
 1562        EditorSnapshot {
 1563            mode: self.mode,
 1564            show_gutter: self.show_gutter,
 1565            show_line_numbers: self.show_line_numbers,
 1566            show_git_diff_gutter: self.show_git_diff_gutter,
 1567            show_code_actions: self.show_code_actions,
 1568            show_runnables: self.show_runnables,
 1569            git_blame_gutter_max_author_length,
 1570            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1571            scroll_anchor: self.scroll_manager.anchor(),
 1572            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1573            placeholder_text: self.placeholder_text.clone(),
 1574            diff_map: self.diff_map.snapshot(),
 1575            is_focused: self.focus_handle.is_focused(cx),
 1576            current_line_highlight: self
 1577                .current_line_highlight
 1578                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1579            gutter_hovered: self.gutter_hovered,
 1580        }
 1581    }
 1582
 1583    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1584        self.buffer.read(cx).language_at(point, cx)
 1585    }
 1586
 1587    pub fn file_at<T: ToOffset>(
 1588        &self,
 1589        point: T,
 1590        cx: &AppContext,
 1591    ) -> Option<Arc<dyn language::File>> {
 1592        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1593    }
 1594
 1595    pub fn active_excerpt(
 1596        &self,
 1597        cx: &AppContext,
 1598    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1599        self.buffer
 1600            .read(cx)
 1601            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1602    }
 1603
 1604    pub fn mode(&self) -> EditorMode {
 1605        self.mode
 1606    }
 1607
 1608    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1609        self.collaboration_hub.as_deref()
 1610    }
 1611
 1612    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1613        self.collaboration_hub = Some(hub);
 1614    }
 1615
 1616    pub fn set_custom_context_menu(
 1617        &mut self,
 1618        f: impl 'static
 1619            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1620    ) {
 1621        self.custom_context_menu = Some(Box::new(f))
 1622    }
 1623
 1624    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1625        self.completion_provider = provider;
 1626    }
 1627
 1628    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1629        self.semantics_provider.clone()
 1630    }
 1631
 1632    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1633        self.semantics_provider = provider;
 1634    }
 1635
 1636    pub fn set_inline_completion_provider<T>(
 1637        &mut self,
 1638        provider: Option<Model<T>>,
 1639        cx: &mut ViewContext<Self>,
 1640    ) where
 1641        T: InlineCompletionProvider,
 1642    {
 1643        self.inline_completion_provider =
 1644            provider.map(|provider| RegisteredInlineCompletionProvider {
 1645                _subscription: cx.observe(&provider, |this, _, cx| {
 1646                    if this.focus_handle.is_focused(cx) {
 1647                        this.update_visible_inline_completion(cx);
 1648                    }
 1649                }),
 1650                provider: Arc::new(provider),
 1651            });
 1652        self.refresh_inline_completion(false, false, cx);
 1653    }
 1654
 1655    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1656        self.placeholder_text.as_deref()
 1657    }
 1658
 1659    pub fn set_placeholder_text(
 1660        &mut self,
 1661        placeholder_text: impl Into<Arc<str>>,
 1662        cx: &mut ViewContext<Self>,
 1663    ) {
 1664        let placeholder_text = Some(placeholder_text.into());
 1665        if self.placeholder_text != placeholder_text {
 1666            self.placeholder_text = placeholder_text;
 1667            cx.notify();
 1668        }
 1669    }
 1670
 1671    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1672        self.cursor_shape = cursor_shape;
 1673
 1674        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1675        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1676
 1677        cx.notify();
 1678    }
 1679
 1680    pub fn set_current_line_highlight(
 1681        &mut self,
 1682        current_line_highlight: Option<CurrentLineHighlight>,
 1683    ) {
 1684        self.current_line_highlight = current_line_highlight;
 1685    }
 1686
 1687    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1688        self.collapse_matches = collapse_matches;
 1689    }
 1690
 1691    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1692        let buffers = self.buffer.read(cx).all_buffers();
 1693        let Some(lsp_store) = self.lsp_store(cx) else {
 1694            return;
 1695        };
 1696        lsp_store.update(cx, |lsp_store, cx| {
 1697            for buffer in buffers {
 1698                self.registered_buffers
 1699                    .entry(buffer.read(cx).remote_id())
 1700                    .or_insert_with(|| {
 1701                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1702                    });
 1703            }
 1704        })
 1705    }
 1706
 1707    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1708        if self.collapse_matches {
 1709            return range.start..range.start;
 1710        }
 1711        range.clone()
 1712    }
 1713
 1714    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1715        if self.display_map.read(cx).clip_at_line_ends != clip {
 1716            self.display_map
 1717                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1718        }
 1719    }
 1720
 1721    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1722        self.input_enabled = input_enabled;
 1723    }
 1724
 1725    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 1726        self.enable_inline_completions = enabled;
 1727    }
 1728
 1729    pub fn set_autoindent(&mut self, autoindent: bool) {
 1730        if autoindent {
 1731            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1732        } else {
 1733            self.autoindent_mode = None;
 1734        }
 1735    }
 1736
 1737    pub fn read_only(&self, cx: &AppContext) -> bool {
 1738        self.read_only || self.buffer.read(cx).read_only()
 1739    }
 1740
 1741    pub fn set_read_only(&mut self, read_only: bool) {
 1742        self.read_only = read_only;
 1743    }
 1744
 1745    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1746        self.use_autoclose = autoclose;
 1747    }
 1748
 1749    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1750        self.use_auto_surround = auto_surround;
 1751    }
 1752
 1753    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1754        self.auto_replace_emoji_shortcode = auto_replace;
 1755    }
 1756
 1757    pub fn toggle_inline_completions(
 1758        &mut self,
 1759        _: &ToggleInlineCompletions,
 1760        cx: &mut ViewContext<Self>,
 1761    ) {
 1762        if self.show_inline_completions_override.is_some() {
 1763            self.set_show_inline_completions(None, cx);
 1764        } else {
 1765            let cursor = self.selections.newest_anchor().head();
 1766            if let Some((buffer, cursor_buffer_position)) =
 1767                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1768            {
 1769                let show_inline_completions =
 1770                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1771                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1772            }
 1773        }
 1774    }
 1775
 1776    pub fn set_show_inline_completions(
 1777        &mut self,
 1778        show_inline_completions: Option<bool>,
 1779        cx: &mut ViewContext<Self>,
 1780    ) {
 1781        self.show_inline_completions_override = show_inline_completions;
 1782        self.refresh_inline_completion(false, true, cx);
 1783    }
 1784
 1785    fn should_show_inline_completions(
 1786        &self,
 1787        buffer: &Model<Buffer>,
 1788        buffer_position: language::Anchor,
 1789        cx: &AppContext,
 1790    ) -> bool {
 1791        if !self.snippet_stack.is_empty() {
 1792            return false;
 1793        }
 1794
 1795        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1796            return false;
 1797        }
 1798
 1799        if let Some(provider) = self.inline_completion_provider() {
 1800            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1801                show_inline_completions
 1802            } else {
 1803                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1804            }
 1805        } else {
 1806            false
 1807        }
 1808    }
 1809
 1810    fn inline_completions_disabled_in_scope(
 1811        &self,
 1812        buffer: &Model<Buffer>,
 1813        buffer_position: language::Anchor,
 1814        cx: &AppContext,
 1815    ) -> bool {
 1816        let snapshot = buffer.read(cx).snapshot();
 1817        let settings = snapshot.settings_at(buffer_position, cx);
 1818
 1819        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1820            return false;
 1821        };
 1822
 1823        scope.override_name().map_or(false, |scope_name| {
 1824            settings
 1825                .inline_completions_disabled_in
 1826                .iter()
 1827                .any(|s| s == scope_name)
 1828        })
 1829    }
 1830
 1831    pub fn set_use_modal_editing(&mut self, to: bool) {
 1832        self.use_modal_editing = to;
 1833    }
 1834
 1835    pub fn use_modal_editing(&self) -> bool {
 1836        self.use_modal_editing
 1837    }
 1838
 1839    fn selections_did_change(
 1840        &mut self,
 1841        local: bool,
 1842        old_cursor_position: &Anchor,
 1843        show_completions: bool,
 1844        cx: &mut ViewContext<Self>,
 1845    ) {
 1846        cx.invalidate_character_coordinates();
 1847
 1848        // Copy selections to primary selection buffer
 1849        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1850        if local {
 1851            let selections = self.selections.all::<usize>(cx);
 1852            let buffer_handle = self.buffer.read(cx).read(cx);
 1853
 1854            let mut text = String::new();
 1855            for (index, selection) in selections.iter().enumerate() {
 1856                let text_for_selection = buffer_handle
 1857                    .text_for_range(selection.start..selection.end)
 1858                    .collect::<String>();
 1859
 1860                text.push_str(&text_for_selection);
 1861                if index != selections.len() - 1 {
 1862                    text.push('\n');
 1863                }
 1864            }
 1865
 1866            if !text.is_empty() {
 1867                cx.write_to_primary(ClipboardItem::new_string(text));
 1868            }
 1869        }
 1870
 1871        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1872            self.buffer.update(cx, |buffer, cx| {
 1873                buffer.set_active_selections(
 1874                    &self.selections.disjoint_anchors(),
 1875                    self.selections.line_mode,
 1876                    self.cursor_shape,
 1877                    cx,
 1878                )
 1879            });
 1880        }
 1881        let display_map = self
 1882            .display_map
 1883            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1884        let buffer = &display_map.buffer_snapshot;
 1885        self.add_selections_state = None;
 1886        self.select_next_state = None;
 1887        self.select_prev_state = None;
 1888        self.select_larger_syntax_node_stack.clear();
 1889        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1890        self.snippet_stack
 1891            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1892        self.take_rename(false, cx);
 1893
 1894        let new_cursor_position = self.selections.newest_anchor().head();
 1895
 1896        self.push_to_nav_history(
 1897            *old_cursor_position,
 1898            Some(new_cursor_position.to_point(buffer)),
 1899            cx,
 1900        );
 1901
 1902        if local {
 1903            let new_cursor_position = self.selections.newest_anchor().head();
 1904            let mut context_menu = self.context_menu.borrow_mut();
 1905            let completion_menu = match context_menu.as_ref() {
 1906                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1907                _ => {
 1908                    *context_menu = None;
 1909                    None
 1910                }
 1911            };
 1912
 1913            if let Some(completion_menu) = completion_menu {
 1914                let cursor_position = new_cursor_position.to_offset(buffer);
 1915                let (word_range, kind) =
 1916                    buffer.surrounding_word(completion_menu.initial_position, true);
 1917                if kind == Some(CharKind::Word)
 1918                    && word_range.to_inclusive().contains(&cursor_position)
 1919                {
 1920                    let mut completion_menu = completion_menu.clone();
 1921                    drop(context_menu);
 1922
 1923                    let query = Self::completion_query(buffer, cursor_position);
 1924                    cx.spawn(move |this, mut cx| async move {
 1925                        completion_menu
 1926                            .filter(query.as_deref(), cx.background_executor().clone())
 1927                            .await;
 1928
 1929                        this.update(&mut cx, |this, cx| {
 1930                            let mut context_menu = this.context_menu.borrow_mut();
 1931                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1932                            else {
 1933                                return;
 1934                            };
 1935
 1936                            if menu.id > completion_menu.id {
 1937                                return;
 1938                            }
 1939
 1940                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1941                            drop(context_menu);
 1942                            cx.notify();
 1943                        })
 1944                    })
 1945                    .detach();
 1946
 1947                    if show_completions {
 1948                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1949                    }
 1950                } else {
 1951                    drop(context_menu);
 1952                    self.hide_context_menu(cx);
 1953                }
 1954            } else {
 1955                drop(context_menu);
 1956            }
 1957
 1958            hide_hover(self, cx);
 1959
 1960            if old_cursor_position.to_display_point(&display_map).row()
 1961                != new_cursor_position.to_display_point(&display_map).row()
 1962            {
 1963                self.available_code_actions.take();
 1964            }
 1965            self.refresh_code_actions(cx);
 1966            self.refresh_document_highlights(cx);
 1967            refresh_matching_bracket_highlights(self, cx);
 1968            self.update_visible_inline_completion(cx);
 1969            linked_editing_ranges::refresh_linked_ranges(self, cx);
 1970            if self.git_blame_inline_enabled {
 1971                self.start_inline_blame_timer(cx);
 1972            }
 1973        }
 1974
 1975        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 1976        cx.emit(EditorEvent::SelectionsChanged { local });
 1977
 1978        if self.selections.disjoint_anchors().len() == 1 {
 1979            cx.emit(SearchEvent::ActiveMatchChanged)
 1980        }
 1981        cx.notify();
 1982    }
 1983
 1984    pub fn change_selections<R>(
 1985        &mut self,
 1986        autoscroll: Option<Autoscroll>,
 1987        cx: &mut ViewContext<Self>,
 1988        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1989    ) -> R {
 1990        self.change_selections_inner(autoscroll, true, cx, change)
 1991    }
 1992
 1993    pub fn change_selections_inner<R>(
 1994        &mut self,
 1995        autoscroll: Option<Autoscroll>,
 1996        request_completions: bool,
 1997        cx: &mut ViewContext<Self>,
 1998        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1999    ) -> R {
 2000        let old_cursor_position = self.selections.newest_anchor().head();
 2001        self.push_to_selection_history();
 2002
 2003        let (changed, result) = self.selections.change_with(cx, change);
 2004
 2005        if changed {
 2006            if let Some(autoscroll) = autoscroll {
 2007                self.request_autoscroll(autoscroll, cx);
 2008            }
 2009            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2010
 2011            if self.should_open_signature_help_automatically(
 2012                &old_cursor_position,
 2013                self.signature_help_state.backspace_pressed(),
 2014                cx,
 2015            ) {
 2016                self.show_signature_help(&ShowSignatureHelp, cx);
 2017            }
 2018            self.signature_help_state.set_backspace_pressed(false);
 2019        }
 2020
 2021        result
 2022    }
 2023
 2024    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2025    where
 2026        I: IntoIterator<Item = (Range<S>, T)>,
 2027        S: ToOffset,
 2028        T: Into<Arc<str>>,
 2029    {
 2030        if self.read_only(cx) {
 2031            return;
 2032        }
 2033
 2034        self.buffer
 2035            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2036    }
 2037
 2038    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2039    where
 2040        I: IntoIterator<Item = (Range<S>, T)>,
 2041        S: ToOffset,
 2042        T: Into<Arc<str>>,
 2043    {
 2044        if self.read_only(cx) {
 2045            return;
 2046        }
 2047
 2048        self.buffer.update(cx, |buffer, cx| {
 2049            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2050        });
 2051    }
 2052
 2053    pub fn edit_with_block_indent<I, S, T>(
 2054        &mut self,
 2055        edits: I,
 2056        original_indent_columns: Vec<u32>,
 2057        cx: &mut ViewContext<Self>,
 2058    ) where
 2059        I: IntoIterator<Item = (Range<S>, T)>,
 2060        S: ToOffset,
 2061        T: Into<Arc<str>>,
 2062    {
 2063        if self.read_only(cx) {
 2064            return;
 2065        }
 2066
 2067        self.buffer.update(cx, |buffer, cx| {
 2068            buffer.edit(
 2069                edits,
 2070                Some(AutoindentMode::Block {
 2071                    original_indent_columns,
 2072                }),
 2073                cx,
 2074            )
 2075        });
 2076    }
 2077
 2078    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2079        self.hide_context_menu(cx);
 2080
 2081        match phase {
 2082            SelectPhase::Begin {
 2083                position,
 2084                add,
 2085                click_count,
 2086            } => self.begin_selection(position, add, click_count, cx),
 2087            SelectPhase::BeginColumnar {
 2088                position,
 2089                goal_column,
 2090                reset,
 2091            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2092            SelectPhase::Extend {
 2093                position,
 2094                click_count,
 2095            } => self.extend_selection(position, click_count, cx),
 2096            SelectPhase::Update {
 2097                position,
 2098                goal_column,
 2099                scroll_delta,
 2100            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2101            SelectPhase::End => self.end_selection(cx),
 2102        }
 2103    }
 2104
 2105    fn extend_selection(
 2106        &mut self,
 2107        position: DisplayPoint,
 2108        click_count: usize,
 2109        cx: &mut ViewContext<Self>,
 2110    ) {
 2111        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2112        let tail = self.selections.newest::<usize>(cx).tail();
 2113        self.begin_selection(position, false, click_count, cx);
 2114
 2115        let position = position.to_offset(&display_map, Bias::Left);
 2116        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2117
 2118        let mut pending_selection = self
 2119            .selections
 2120            .pending_anchor()
 2121            .expect("extend_selection not called with pending selection");
 2122        if position >= tail {
 2123            pending_selection.start = tail_anchor;
 2124        } else {
 2125            pending_selection.end = tail_anchor;
 2126            pending_selection.reversed = true;
 2127        }
 2128
 2129        let mut pending_mode = self.selections.pending_mode().unwrap();
 2130        match &mut pending_mode {
 2131            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2132            _ => {}
 2133        }
 2134
 2135        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2136            s.set_pending(pending_selection, pending_mode)
 2137        });
 2138    }
 2139
 2140    fn begin_selection(
 2141        &mut self,
 2142        position: DisplayPoint,
 2143        add: bool,
 2144        click_count: usize,
 2145        cx: &mut ViewContext<Self>,
 2146    ) {
 2147        if !self.focus_handle.is_focused(cx) {
 2148            self.last_focused_descendant = None;
 2149            cx.focus(&self.focus_handle);
 2150        }
 2151
 2152        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2153        let buffer = &display_map.buffer_snapshot;
 2154        let newest_selection = self.selections.newest_anchor().clone();
 2155        let position = display_map.clip_point(position, Bias::Left);
 2156
 2157        let start;
 2158        let end;
 2159        let mode;
 2160        let mut auto_scroll;
 2161        match click_count {
 2162            1 => {
 2163                start = buffer.anchor_before(position.to_point(&display_map));
 2164                end = start;
 2165                mode = SelectMode::Character;
 2166                auto_scroll = true;
 2167            }
 2168            2 => {
 2169                let range = movement::surrounding_word(&display_map, position);
 2170                start = buffer.anchor_before(range.start.to_point(&display_map));
 2171                end = buffer.anchor_before(range.end.to_point(&display_map));
 2172                mode = SelectMode::Word(start..end);
 2173                auto_scroll = true;
 2174            }
 2175            3 => {
 2176                let position = display_map
 2177                    .clip_point(position, Bias::Left)
 2178                    .to_point(&display_map);
 2179                let line_start = display_map.prev_line_boundary(position).0;
 2180                let next_line_start = buffer.clip_point(
 2181                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2182                    Bias::Left,
 2183                );
 2184                start = buffer.anchor_before(line_start);
 2185                end = buffer.anchor_before(next_line_start);
 2186                mode = SelectMode::Line(start..end);
 2187                auto_scroll = true;
 2188            }
 2189            _ => {
 2190                start = buffer.anchor_before(0);
 2191                end = buffer.anchor_before(buffer.len());
 2192                mode = SelectMode::All;
 2193                auto_scroll = false;
 2194            }
 2195        }
 2196        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2197
 2198        let point_to_delete: Option<usize> = {
 2199            let selected_points: Vec<Selection<Point>> =
 2200                self.selections.disjoint_in_range(start..end, cx);
 2201
 2202            if !add || click_count > 1 {
 2203                None
 2204            } else if !selected_points.is_empty() {
 2205                Some(selected_points[0].id)
 2206            } else {
 2207                let clicked_point_already_selected =
 2208                    self.selections.disjoint.iter().find(|selection| {
 2209                        selection.start.to_point(buffer) == start.to_point(buffer)
 2210                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2211                    });
 2212
 2213                clicked_point_already_selected.map(|selection| selection.id)
 2214            }
 2215        };
 2216
 2217        let selections_count = self.selections.count();
 2218
 2219        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2220            if let Some(point_to_delete) = point_to_delete {
 2221                s.delete(point_to_delete);
 2222
 2223                if selections_count == 1 {
 2224                    s.set_pending_anchor_range(start..end, mode);
 2225                }
 2226            } else {
 2227                if !add {
 2228                    s.clear_disjoint();
 2229                } else if click_count > 1 {
 2230                    s.delete(newest_selection.id)
 2231                }
 2232
 2233                s.set_pending_anchor_range(start..end, mode);
 2234            }
 2235        });
 2236    }
 2237
 2238    fn begin_columnar_selection(
 2239        &mut self,
 2240        position: DisplayPoint,
 2241        goal_column: u32,
 2242        reset: bool,
 2243        cx: &mut ViewContext<Self>,
 2244    ) {
 2245        if !self.focus_handle.is_focused(cx) {
 2246            self.last_focused_descendant = None;
 2247            cx.focus(&self.focus_handle);
 2248        }
 2249
 2250        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2251
 2252        if reset {
 2253            let pointer_position = display_map
 2254                .buffer_snapshot
 2255                .anchor_before(position.to_point(&display_map));
 2256
 2257            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2258                s.clear_disjoint();
 2259                s.set_pending_anchor_range(
 2260                    pointer_position..pointer_position,
 2261                    SelectMode::Character,
 2262                );
 2263            });
 2264        }
 2265
 2266        let tail = self.selections.newest::<Point>(cx).tail();
 2267        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2268
 2269        if !reset {
 2270            self.select_columns(
 2271                tail.to_display_point(&display_map),
 2272                position,
 2273                goal_column,
 2274                &display_map,
 2275                cx,
 2276            );
 2277        }
 2278    }
 2279
 2280    fn update_selection(
 2281        &mut self,
 2282        position: DisplayPoint,
 2283        goal_column: u32,
 2284        scroll_delta: gpui::Point<f32>,
 2285        cx: &mut ViewContext<Self>,
 2286    ) {
 2287        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2288
 2289        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2290            let tail = tail.to_display_point(&display_map);
 2291            self.select_columns(tail, position, goal_column, &display_map, cx);
 2292        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2293            let buffer = self.buffer.read(cx).snapshot(cx);
 2294            let head;
 2295            let tail;
 2296            let mode = self.selections.pending_mode().unwrap();
 2297            match &mode {
 2298                SelectMode::Character => {
 2299                    head = position.to_point(&display_map);
 2300                    tail = pending.tail().to_point(&buffer);
 2301                }
 2302                SelectMode::Word(original_range) => {
 2303                    let original_display_range = original_range.start.to_display_point(&display_map)
 2304                        ..original_range.end.to_display_point(&display_map);
 2305                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2306                        ..original_display_range.end.to_point(&display_map);
 2307                    if movement::is_inside_word(&display_map, position)
 2308                        || original_display_range.contains(&position)
 2309                    {
 2310                        let word_range = movement::surrounding_word(&display_map, position);
 2311                        if word_range.start < original_display_range.start {
 2312                            head = word_range.start.to_point(&display_map);
 2313                        } else {
 2314                            head = word_range.end.to_point(&display_map);
 2315                        }
 2316                    } else {
 2317                        head = position.to_point(&display_map);
 2318                    }
 2319
 2320                    if head <= original_buffer_range.start {
 2321                        tail = original_buffer_range.end;
 2322                    } else {
 2323                        tail = original_buffer_range.start;
 2324                    }
 2325                }
 2326                SelectMode::Line(original_range) => {
 2327                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2328
 2329                    let position = display_map
 2330                        .clip_point(position, Bias::Left)
 2331                        .to_point(&display_map);
 2332                    let line_start = display_map.prev_line_boundary(position).0;
 2333                    let next_line_start = buffer.clip_point(
 2334                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2335                        Bias::Left,
 2336                    );
 2337
 2338                    if line_start < original_range.start {
 2339                        head = line_start
 2340                    } else {
 2341                        head = next_line_start
 2342                    }
 2343
 2344                    if head <= original_range.start {
 2345                        tail = original_range.end;
 2346                    } else {
 2347                        tail = original_range.start;
 2348                    }
 2349                }
 2350                SelectMode::All => {
 2351                    return;
 2352                }
 2353            };
 2354
 2355            if head < tail {
 2356                pending.start = buffer.anchor_before(head);
 2357                pending.end = buffer.anchor_before(tail);
 2358                pending.reversed = true;
 2359            } else {
 2360                pending.start = buffer.anchor_before(tail);
 2361                pending.end = buffer.anchor_before(head);
 2362                pending.reversed = false;
 2363            }
 2364
 2365            self.change_selections(None, cx, |s| {
 2366                s.set_pending(pending, mode);
 2367            });
 2368        } else {
 2369            log::error!("update_selection dispatched with no pending selection");
 2370            return;
 2371        }
 2372
 2373        self.apply_scroll_delta(scroll_delta, cx);
 2374        cx.notify();
 2375    }
 2376
 2377    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2378        self.columnar_selection_tail.take();
 2379        if self.selections.pending_anchor().is_some() {
 2380            let selections = self.selections.all::<usize>(cx);
 2381            self.change_selections(None, cx, |s| {
 2382                s.select(selections);
 2383                s.clear_pending();
 2384            });
 2385        }
 2386    }
 2387
 2388    fn select_columns(
 2389        &mut self,
 2390        tail: DisplayPoint,
 2391        head: DisplayPoint,
 2392        goal_column: u32,
 2393        display_map: &DisplaySnapshot,
 2394        cx: &mut ViewContext<Self>,
 2395    ) {
 2396        let start_row = cmp::min(tail.row(), head.row());
 2397        let end_row = cmp::max(tail.row(), head.row());
 2398        let start_column = cmp::min(tail.column(), goal_column);
 2399        let end_column = cmp::max(tail.column(), goal_column);
 2400        let reversed = start_column < tail.column();
 2401
 2402        let selection_ranges = (start_row.0..=end_row.0)
 2403            .map(DisplayRow)
 2404            .filter_map(|row| {
 2405                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2406                    let start = display_map
 2407                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2408                        .to_point(display_map);
 2409                    let end = display_map
 2410                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2411                        .to_point(display_map);
 2412                    if reversed {
 2413                        Some(end..start)
 2414                    } else {
 2415                        Some(start..end)
 2416                    }
 2417                } else {
 2418                    None
 2419                }
 2420            })
 2421            .collect::<Vec<_>>();
 2422
 2423        self.change_selections(None, cx, |s| {
 2424            s.select_ranges(selection_ranges);
 2425        });
 2426        cx.notify();
 2427    }
 2428
 2429    pub fn has_pending_nonempty_selection(&self) -> bool {
 2430        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2431            Some(Selection { start, end, .. }) => start != end,
 2432            None => false,
 2433        };
 2434
 2435        pending_nonempty_selection
 2436            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2437    }
 2438
 2439    pub fn has_pending_selection(&self) -> bool {
 2440        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2441    }
 2442
 2443    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2444        if self.clear_expanded_diff_hunks(cx) {
 2445            cx.notify();
 2446            return;
 2447        }
 2448        if self.dismiss_menus_and_popups(true, cx) {
 2449            return;
 2450        }
 2451
 2452        if self.mode == EditorMode::Full
 2453            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2454        {
 2455            return;
 2456        }
 2457
 2458        cx.propagate();
 2459    }
 2460
 2461    pub fn dismiss_menus_and_popups(
 2462        &mut self,
 2463        should_report_inline_completion_event: bool,
 2464        cx: &mut ViewContext<Self>,
 2465    ) -> bool {
 2466        if self.take_rename(false, cx).is_some() {
 2467            return true;
 2468        }
 2469
 2470        if hide_hover(self, cx) {
 2471            return true;
 2472        }
 2473
 2474        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2475            return true;
 2476        }
 2477
 2478        if self.hide_context_menu(cx).is_some() {
 2479            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2480                self.update_visible_inline_completion(cx);
 2481            }
 2482            return true;
 2483        }
 2484
 2485        if self.mouse_context_menu.take().is_some() {
 2486            return true;
 2487        }
 2488
 2489        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2490            return true;
 2491        }
 2492
 2493        if self.snippet_stack.pop().is_some() {
 2494            return true;
 2495        }
 2496
 2497        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2498            self.dismiss_diagnostics(cx);
 2499            return true;
 2500        }
 2501
 2502        false
 2503    }
 2504
 2505    fn linked_editing_ranges_for(
 2506        &self,
 2507        selection: Range<text::Anchor>,
 2508        cx: &AppContext,
 2509    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2510        if self.linked_edit_ranges.is_empty() {
 2511            return None;
 2512        }
 2513        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2514            selection.end.buffer_id.and_then(|end_buffer_id| {
 2515                if selection.start.buffer_id != Some(end_buffer_id) {
 2516                    return None;
 2517                }
 2518                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2519                let snapshot = buffer.read(cx).snapshot();
 2520                self.linked_edit_ranges
 2521                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2522                    .map(|ranges| (ranges, snapshot, buffer))
 2523            })?;
 2524        use text::ToOffset as TO;
 2525        // find offset from the start of current range to current cursor position
 2526        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2527
 2528        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2529        let start_difference = start_offset - start_byte_offset;
 2530        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2531        let end_difference = end_offset - start_byte_offset;
 2532        // Current range has associated linked ranges.
 2533        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2534        for range in linked_ranges.iter() {
 2535            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2536            let end_offset = start_offset + end_difference;
 2537            let start_offset = start_offset + start_difference;
 2538            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2539                continue;
 2540            }
 2541            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 2542                if s.start.buffer_id != selection.start.buffer_id
 2543                    || s.end.buffer_id != selection.end.buffer_id
 2544                {
 2545                    return false;
 2546                }
 2547                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2548                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2549            }) {
 2550                continue;
 2551            }
 2552            let start = buffer_snapshot.anchor_after(start_offset);
 2553            let end = buffer_snapshot.anchor_after(end_offset);
 2554            linked_edits
 2555                .entry(buffer.clone())
 2556                .or_default()
 2557                .push(start..end);
 2558        }
 2559        Some(linked_edits)
 2560    }
 2561
 2562    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2563        let text: Arc<str> = text.into();
 2564
 2565        if self.read_only(cx) {
 2566            return;
 2567        }
 2568
 2569        let selections = self.selections.all_adjusted(cx);
 2570        let mut bracket_inserted = false;
 2571        let mut edits = Vec::new();
 2572        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2573        let mut new_selections = Vec::with_capacity(selections.len());
 2574        let mut new_autoclose_regions = Vec::new();
 2575        let snapshot = self.buffer.read(cx).read(cx);
 2576
 2577        for (selection, autoclose_region) in
 2578            self.selections_with_autoclose_regions(selections, &snapshot)
 2579        {
 2580            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2581                // Determine if the inserted text matches the opening or closing
 2582                // bracket of any of this language's bracket pairs.
 2583                let mut bracket_pair = None;
 2584                let mut is_bracket_pair_start = false;
 2585                let mut is_bracket_pair_end = false;
 2586                if !text.is_empty() {
 2587                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2588                    //  and they are removing the character that triggered IME popup.
 2589                    for (pair, enabled) in scope.brackets() {
 2590                        if !pair.close && !pair.surround {
 2591                            continue;
 2592                        }
 2593
 2594                        if enabled && pair.start.ends_with(text.as_ref()) {
 2595                            let prefix_len = pair.start.len() - text.len();
 2596                            let preceding_text_matches_prefix = prefix_len == 0
 2597                                || (selection.start.column >= (prefix_len as u32)
 2598                                    && snapshot.contains_str_at(
 2599                                        Point::new(
 2600                                            selection.start.row,
 2601                                            selection.start.column - (prefix_len as u32),
 2602                                        ),
 2603                                        &pair.start[..prefix_len],
 2604                                    ));
 2605                            if preceding_text_matches_prefix {
 2606                                bracket_pair = Some(pair.clone());
 2607                                is_bracket_pair_start = true;
 2608                                break;
 2609                            }
 2610                        }
 2611                        if pair.end.as_str() == text.as_ref() {
 2612                            bracket_pair = Some(pair.clone());
 2613                            is_bracket_pair_end = true;
 2614                            break;
 2615                        }
 2616                    }
 2617                }
 2618
 2619                if let Some(bracket_pair) = bracket_pair {
 2620                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2621                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2622                    let auto_surround =
 2623                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2624                    if selection.is_empty() {
 2625                        if is_bracket_pair_start {
 2626                            // If the inserted text is a suffix of an opening bracket and the
 2627                            // selection is preceded by the rest of the opening bracket, then
 2628                            // insert the closing bracket.
 2629                            let following_text_allows_autoclose = snapshot
 2630                                .chars_at(selection.start)
 2631                                .next()
 2632                                .map_or(true, |c| scope.should_autoclose_before(c));
 2633
 2634                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2635                                && bracket_pair.start.len() == 1
 2636                            {
 2637                                let target = bracket_pair.start.chars().next().unwrap();
 2638                                let current_line_count = snapshot
 2639                                    .reversed_chars_at(selection.start)
 2640                                    .take_while(|&c| c != '\n')
 2641                                    .filter(|&c| c == target)
 2642                                    .count();
 2643                                current_line_count % 2 == 1
 2644                            } else {
 2645                                false
 2646                            };
 2647
 2648                            if autoclose
 2649                                && bracket_pair.close
 2650                                && following_text_allows_autoclose
 2651                                && !is_closing_quote
 2652                            {
 2653                                let anchor = snapshot.anchor_before(selection.end);
 2654                                new_selections.push((selection.map(|_| anchor), text.len()));
 2655                                new_autoclose_regions.push((
 2656                                    anchor,
 2657                                    text.len(),
 2658                                    selection.id,
 2659                                    bracket_pair.clone(),
 2660                                ));
 2661                                edits.push((
 2662                                    selection.range(),
 2663                                    format!("{}{}", text, bracket_pair.end).into(),
 2664                                ));
 2665                                bracket_inserted = true;
 2666                                continue;
 2667                            }
 2668                        }
 2669
 2670                        if let Some(region) = autoclose_region {
 2671                            // If the selection is followed by an auto-inserted closing bracket,
 2672                            // then don't insert that closing bracket again; just move the selection
 2673                            // past the closing bracket.
 2674                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2675                                && text.as_ref() == region.pair.end.as_str();
 2676                            if should_skip {
 2677                                let anchor = snapshot.anchor_after(selection.end);
 2678                                new_selections
 2679                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2680                                continue;
 2681                            }
 2682                        }
 2683
 2684                        let always_treat_brackets_as_autoclosed = snapshot
 2685                            .settings_at(selection.start, cx)
 2686                            .always_treat_brackets_as_autoclosed;
 2687                        if always_treat_brackets_as_autoclosed
 2688                            && is_bracket_pair_end
 2689                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2690                        {
 2691                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2692                            // and the inserted text is a closing bracket and the selection is followed
 2693                            // by the closing bracket then move the selection past the closing bracket.
 2694                            let anchor = snapshot.anchor_after(selection.end);
 2695                            new_selections.push((selection.map(|_| anchor), text.len()));
 2696                            continue;
 2697                        }
 2698                    }
 2699                    // If an opening bracket is 1 character long and is typed while
 2700                    // text is selected, then surround that text with the bracket pair.
 2701                    else if auto_surround
 2702                        && bracket_pair.surround
 2703                        && is_bracket_pair_start
 2704                        && bracket_pair.start.chars().count() == 1
 2705                    {
 2706                        edits.push((selection.start..selection.start, text.clone()));
 2707                        edits.push((
 2708                            selection.end..selection.end,
 2709                            bracket_pair.end.as_str().into(),
 2710                        ));
 2711                        bracket_inserted = true;
 2712                        new_selections.push((
 2713                            Selection {
 2714                                id: selection.id,
 2715                                start: snapshot.anchor_after(selection.start),
 2716                                end: snapshot.anchor_before(selection.end),
 2717                                reversed: selection.reversed,
 2718                                goal: selection.goal,
 2719                            },
 2720                            0,
 2721                        ));
 2722                        continue;
 2723                    }
 2724                }
 2725            }
 2726
 2727            if self.auto_replace_emoji_shortcode
 2728                && selection.is_empty()
 2729                && text.as_ref().ends_with(':')
 2730            {
 2731                if let Some(possible_emoji_short_code) =
 2732                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2733                {
 2734                    if !possible_emoji_short_code.is_empty() {
 2735                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2736                            let emoji_shortcode_start = Point::new(
 2737                                selection.start.row,
 2738                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2739                            );
 2740
 2741                            // Remove shortcode from buffer
 2742                            edits.push((
 2743                                emoji_shortcode_start..selection.start,
 2744                                "".to_string().into(),
 2745                            ));
 2746                            new_selections.push((
 2747                                Selection {
 2748                                    id: selection.id,
 2749                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2750                                    end: snapshot.anchor_before(selection.start),
 2751                                    reversed: selection.reversed,
 2752                                    goal: selection.goal,
 2753                                },
 2754                                0,
 2755                            ));
 2756
 2757                            // Insert emoji
 2758                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2759                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2760                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2761
 2762                            continue;
 2763                        }
 2764                    }
 2765                }
 2766            }
 2767
 2768            // If not handling any auto-close operation, then just replace the selected
 2769            // text with the given input and move the selection to the end of the
 2770            // newly inserted text.
 2771            let anchor = snapshot.anchor_after(selection.end);
 2772            if !self.linked_edit_ranges.is_empty() {
 2773                let start_anchor = snapshot.anchor_before(selection.start);
 2774
 2775                let is_word_char = text.chars().next().map_or(true, |char| {
 2776                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2777                    classifier.is_word(char)
 2778                });
 2779
 2780                if is_word_char {
 2781                    if let Some(ranges) = self
 2782                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2783                    {
 2784                        for (buffer, edits) in ranges {
 2785                            linked_edits
 2786                                .entry(buffer.clone())
 2787                                .or_default()
 2788                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2789                        }
 2790                    }
 2791                }
 2792            }
 2793
 2794            new_selections.push((selection.map(|_| anchor), 0));
 2795            edits.push((selection.start..selection.end, text.clone()));
 2796        }
 2797
 2798        drop(snapshot);
 2799
 2800        self.transact(cx, |this, cx| {
 2801            this.buffer.update(cx, |buffer, cx| {
 2802                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2803            });
 2804            for (buffer, edits) in linked_edits {
 2805                buffer.update(cx, |buffer, cx| {
 2806                    let snapshot = buffer.snapshot();
 2807                    let edits = edits
 2808                        .into_iter()
 2809                        .map(|(range, text)| {
 2810                            use text::ToPoint as TP;
 2811                            let end_point = TP::to_point(&range.end, &snapshot);
 2812                            let start_point = TP::to_point(&range.start, &snapshot);
 2813                            (start_point..end_point, text)
 2814                        })
 2815                        .sorted_by_key(|(range, _)| range.start)
 2816                        .collect::<Vec<_>>();
 2817                    buffer.edit(edits, None, cx);
 2818                })
 2819            }
 2820            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2821            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2822            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2823            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2824                .zip(new_selection_deltas)
 2825                .map(|(selection, delta)| Selection {
 2826                    id: selection.id,
 2827                    start: selection.start + delta,
 2828                    end: selection.end + delta,
 2829                    reversed: selection.reversed,
 2830                    goal: SelectionGoal::None,
 2831                })
 2832                .collect::<Vec<_>>();
 2833
 2834            let mut i = 0;
 2835            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2836                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2837                let start = map.buffer_snapshot.anchor_before(position);
 2838                let end = map.buffer_snapshot.anchor_after(position);
 2839                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2840                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2841                        Ordering::Less => i += 1,
 2842                        Ordering::Greater => break,
 2843                        Ordering::Equal => {
 2844                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2845                                Ordering::Less => i += 1,
 2846                                Ordering::Equal => break,
 2847                                Ordering::Greater => break,
 2848                            }
 2849                        }
 2850                    }
 2851                }
 2852                this.autoclose_regions.insert(
 2853                    i,
 2854                    AutocloseRegion {
 2855                        selection_id,
 2856                        range: start..end,
 2857                        pair,
 2858                    },
 2859                );
 2860            }
 2861
 2862            let had_active_inline_completion = this.has_active_inline_completion();
 2863            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2864                s.select(new_selections)
 2865            });
 2866
 2867            if !bracket_inserted {
 2868                if let Some(on_type_format_task) =
 2869                    this.trigger_on_type_formatting(text.to_string(), cx)
 2870                {
 2871                    on_type_format_task.detach_and_log_err(cx);
 2872                }
 2873            }
 2874
 2875            let editor_settings = EditorSettings::get_global(cx);
 2876            if bracket_inserted
 2877                && (editor_settings.auto_signature_help
 2878                    || editor_settings.show_signature_help_after_edits)
 2879            {
 2880                this.show_signature_help(&ShowSignatureHelp, cx);
 2881            }
 2882
 2883            let trigger_in_words =
 2884                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2885            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2886            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2887            this.refresh_inline_completion(true, false, cx);
 2888        });
 2889    }
 2890
 2891    fn find_possible_emoji_shortcode_at_position(
 2892        snapshot: &MultiBufferSnapshot,
 2893        position: Point,
 2894    ) -> Option<String> {
 2895        let mut chars = Vec::new();
 2896        let mut found_colon = false;
 2897        for char in snapshot.reversed_chars_at(position).take(100) {
 2898            // Found a possible emoji shortcode in the middle of the buffer
 2899            if found_colon {
 2900                if char.is_whitespace() {
 2901                    chars.reverse();
 2902                    return Some(chars.iter().collect());
 2903                }
 2904                // If the previous character is not a whitespace, we are in the middle of a word
 2905                // and we only want to complete the shortcode if the word is made up of other emojis
 2906                let mut containing_word = String::new();
 2907                for ch in snapshot
 2908                    .reversed_chars_at(position)
 2909                    .skip(chars.len() + 1)
 2910                    .take(100)
 2911                {
 2912                    if ch.is_whitespace() {
 2913                        break;
 2914                    }
 2915                    containing_word.push(ch);
 2916                }
 2917                let containing_word = containing_word.chars().rev().collect::<String>();
 2918                if util::word_consists_of_emojis(containing_word.as_str()) {
 2919                    chars.reverse();
 2920                    return Some(chars.iter().collect());
 2921                }
 2922            }
 2923
 2924            if char.is_whitespace() || !char.is_ascii() {
 2925                return None;
 2926            }
 2927            if char == ':' {
 2928                found_colon = true;
 2929            } else {
 2930                chars.push(char);
 2931            }
 2932        }
 2933        // Found a possible emoji shortcode at the beginning of the buffer
 2934        chars.reverse();
 2935        Some(chars.iter().collect())
 2936    }
 2937
 2938    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2939        self.transact(cx, |this, cx| {
 2940            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2941                let selections = this.selections.all::<usize>(cx);
 2942                let multi_buffer = this.buffer.read(cx);
 2943                let buffer = multi_buffer.snapshot(cx);
 2944                selections
 2945                    .iter()
 2946                    .map(|selection| {
 2947                        let start_point = selection.start.to_point(&buffer);
 2948                        let mut indent =
 2949                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2950                        indent.len = cmp::min(indent.len, start_point.column);
 2951                        let start = selection.start;
 2952                        let end = selection.end;
 2953                        let selection_is_empty = start == end;
 2954                        let language_scope = buffer.language_scope_at(start);
 2955                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2956                            &language_scope
 2957                        {
 2958                            let leading_whitespace_len = buffer
 2959                                .reversed_chars_at(start)
 2960                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2961                                .map(|c| c.len_utf8())
 2962                                .sum::<usize>();
 2963
 2964                            let trailing_whitespace_len = buffer
 2965                                .chars_at(end)
 2966                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2967                                .map(|c| c.len_utf8())
 2968                                .sum::<usize>();
 2969
 2970                            let insert_extra_newline =
 2971                                language.brackets().any(|(pair, enabled)| {
 2972                                    let pair_start = pair.start.trim_end();
 2973                                    let pair_end = pair.end.trim_start();
 2974
 2975                                    enabled
 2976                                        && pair.newline
 2977                                        && buffer.contains_str_at(
 2978                                            end + trailing_whitespace_len,
 2979                                            pair_end,
 2980                                        )
 2981                                        && buffer.contains_str_at(
 2982                                            (start - leading_whitespace_len)
 2983                                                .saturating_sub(pair_start.len()),
 2984                                            pair_start,
 2985                                        )
 2986                                });
 2987
 2988                            // Comment extension on newline is allowed only for cursor selections
 2989                            let comment_delimiter = maybe!({
 2990                                if !selection_is_empty {
 2991                                    return None;
 2992                                }
 2993
 2994                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 2995                                    return None;
 2996                                }
 2997
 2998                                let delimiters = language.line_comment_prefixes();
 2999                                let max_len_of_delimiter =
 3000                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3001                                let (snapshot, range) =
 3002                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3003
 3004                                let mut index_of_first_non_whitespace = 0;
 3005                                let comment_candidate = snapshot
 3006                                    .chars_for_range(range)
 3007                                    .skip_while(|c| {
 3008                                        let should_skip = c.is_whitespace();
 3009                                        if should_skip {
 3010                                            index_of_first_non_whitespace += 1;
 3011                                        }
 3012                                        should_skip
 3013                                    })
 3014                                    .take(max_len_of_delimiter)
 3015                                    .collect::<String>();
 3016                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3017                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3018                                })?;
 3019                                let cursor_is_placed_after_comment_marker =
 3020                                    index_of_first_non_whitespace + comment_prefix.len()
 3021                                        <= start_point.column as usize;
 3022                                if cursor_is_placed_after_comment_marker {
 3023                                    Some(comment_prefix.clone())
 3024                                } else {
 3025                                    None
 3026                                }
 3027                            });
 3028                            (comment_delimiter, insert_extra_newline)
 3029                        } else {
 3030                            (None, false)
 3031                        };
 3032
 3033                        let capacity_for_delimiter = comment_delimiter
 3034                            .as_deref()
 3035                            .map(str::len)
 3036                            .unwrap_or_default();
 3037                        let mut new_text =
 3038                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3039                        new_text.push('\n');
 3040                        new_text.extend(indent.chars());
 3041                        if let Some(delimiter) = &comment_delimiter {
 3042                            new_text.push_str(delimiter);
 3043                        }
 3044                        if insert_extra_newline {
 3045                            new_text = new_text.repeat(2);
 3046                        }
 3047
 3048                        let anchor = buffer.anchor_after(end);
 3049                        let new_selection = selection.map(|_| anchor);
 3050                        (
 3051                            (start..end, new_text),
 3052                            (insert_extra_newline, new_selection),
 3053                        )
 3054                    })
 3055                    .unzip()
 3056            };
 3057
 3058            this.edit_with_autoindent(edits, cx);
 3059            let buffer = this.buffer.read(cx).snapshot(cx);
 3060            let new_selections = selection_fixup_info
 3061                .into_iter()
 3062                .map(|(extra_newline_inserted, new_selection)| {
 3063                    let mut cursor = new_selection.end.to_point(&buffer);
 3064                    if extra_newline_inserted {
 3065                        cursor.row -= 1;
 3066                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3067                    }
 3068                    new_selection.map(|_| cursor)
 3069                })
 3070                .collect();
 3071
 3072            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3073            this.refresh_inline_completion(true, false, cx);
 3074        });
 3075    }
 3076
 3077    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3078        let buffer = self.buffer.read(cx);
 3079        let snapshot = buffer.snapshot(cx);
 3080
 3081        let mut edits = Vec::new();
 3082        let mut rows = Vec::new();
 3083
 3084        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3085            let cursor = selection.head();
 3086            let row = cursor.row;
 3087
 3088            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3089
 3090            let newline = "\n".to_string();
 3091            edits.push((start_of_line..start_of_line, newline));
 3092
 3093            rows.push(row + rows_inserted as u32);
 3094        }
 3095
 3096        self.transact(cx, |editor, cx| {
 3097            editor.edit(edits, cx);
 3098
 3099            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3100                let mut index = 0;
 3101                s.move_cursors_with(|map, _, _| {
 3102                    let row = rows[index];
 3103                    index += 1;
 3104
 3105                    let point = Point::new(row, 0);
 3106                    let boundary = map.next_line_boundary(point).1;
 3107                    let clipped = map.clip_point(boundary, Bias::Left);
 3108
 3109                    (clipped, SelectionGoal::None)
 3110                });
 3111            });
 3112
 3113            let mut indent_edits = Vec::new();
 3114            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3115            for row in rows {
 3116                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3117                for (row, indent) in indents {
 3118                    if indent.len == 0 {
 3119                        continue;
 3120                    }
 3121
 3122                    let text = match indent.kind {
 3123                        IndentKind::Space => " ".repeat(indent.len as usize),
 3124                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3125                    };
 3126                    let point = Point::new(row.0, 0);
 3127                    indent_edits.push((point..point, text));
 3128                }
 3129            }
 3130            editor.edit(indent_edits, cx);
 3131        });
 3132    }
 3133
 3134    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3135        let buffer = self.buffer.read(cx);
 3136        let snapshot = buffer.snapshot(cx);
 3137
 3138        let mut edits = Vec::new();
 3139        let mut rows = Vec::new();
 3140        let mut rows_inserted = 0;
 3141
 3142        for selection in self.selections.all_adjusted(cx) {
 3143            let cursor = selection.head();
 3144            let row = cursor.row;
 3145
 3146            let point = Point::new(row + 1, 0);
 3147            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3148
 3149            let newline = "\n".to_string();
 3150            edits.push((start_of_line..start_of_line, newline));
 3151
 3152            rows_inserted += 1;
 3153            rows.push(row + rows_inserted);
 3154        }
 3155
 3156        self.transact(cx, |editor, cx| {
 3157            editor.edit(edits, cx);
 3158
 3159            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3160                let mut index = 0;
 3161                s.move_cursors_with(|map, _, _| {
 3162                    let row = rows[index];
 3163                    index += 1;
 3164
 3165                    let point = Point::new(row, 0);
 3166                    let boundary = map.next_line_boundary(point).1;
 3167                    let clipped = map.clip_point(boundary, Bias::Left);
 3168
 3169                    (clipped, SelectionGoal::None)
 3170                });
 3171            });
 3172
 3173            let mut indent_edits = Vec::new();
 3174            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3175            for row in rows {
 3176                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3177                for (row, indent) in indents {
 3178                    if indent.len == 0 {
 3179                        continue;
 3180                    }
 3181
 3182                    let text = match indent.kind {
 3183                        IndentKind::Space => " ".repeat(indent.len as usize),
 3184                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3185                    };
 3186                    let point = Point::new(row.0, 0);
 3187                    indent_edits.push((point..point, text));
 3188                }
 3189            }
 3190            editor.edit(indent_edits, cx);
 3191        });
 3192    }
 3193
 3194    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3195        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3196            original_indent_columns: Vec::new(),
 3197        });
 3198        self.insert_with_autoindent_mode(text, autoindent, cx);
 3199    }
 3200
 3201    fn insert_with_autoindent_mode(
 3202        &mut self,
 3203        text: &str,
 3204        autoindent_mode: Option<AutoindentMode>,
 3205        cx: &mut ViewContext<Self>,
 3206    ) {
 3207        if self.read_only(cx) {
 3208            return;
 3209        }
 3210
 3211        let text: Arc<str> = text.into();
 3212        self.transact(cx, |this, cx| {
 3213            let old_selections = this.selections.all_adjusted(cx);
 3214            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3215                let anchors = {
 3216                    let snapshot = buffer.read(cx);
 3217                    old_selections
 3218                        .iter()
 3219                        .map(|s| {
 3220                            let anchor = snapshot.anchor_after(s.head());
 3221                            s.map(|_| anchor)
 3222                        })
 3223                        .collect::<Vec<_>>()
 3224                };
 3225                buffer.edit(
 3226                    old_selections
 3227                        .iter()
 3228                        .map(|s| (s.start..s.end, text.clone())),
 3229                    autoindent_mode,
 3230                    cx,
 3231                );
 3232                anchors
 3233            });
 3234
 3235            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3236                s.select_anchors(selection_anchors);
 3237            })
 3238        });
 3239    }
 3240
 3241    fn trigger_completion_on_input(
 3242        &mut self,
 3243        text: &str,
 3244        trigger_in_words: bool,
 3245        cx: &mut ViewContext<Self>,
 3246    ) {
 3247        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3248            self.show_completions(
 3249                &ShowCompletions {
 3250                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3251                },
 3252                cx,
 3253            );
 3254        } else {
 3255            self.hide_context_menu(cx);
 3256        }
 3257    }
 3258
 3259    fn is_completion_trigger(
 3260        &self,
 3261        text: &str,
 3262        trigger_in_words: bool,
 3263        cx: &mut ViewContext<Self>,
 3264    ) -> bool {
 3265        let position = self.selections.newest_anchor().head();
 3266        let multibuffer = self.buffer.read(cx);
 3267        let Some(buffer) = position
 3268            .buffer_id
 3269            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3270        else {
 3271            return false;
 3272        };
 3273
 3274        if let Some(completion_provider) = &self.completion_provider {
 3275            completion_provider.is_completion_trigger(
 3276                &buffer,
 3277                position.text_anchor,
 3278                text,
 3279                trigger_in_words,
 3280                cx,
 3281            )
 3282        } else {
 3283            false
 3284        }
 3285    }
 3286
 3287    /// If any empty selections is touching the start of its innermost containing autoclose
 3288    /// region, expand it to select the brackets.
 3289    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3290        let selections = self.selections.all::<usize>(cx);
 3291        let buffer = self.buffer.read(cx).read(cx);
 3292        let new_selections = self
 3293            .selections_with_autoclose_regions(selections, &buffer)
 3294            .map(|(mut selection, region)| {
 3295                if !selection.is_empty() {
 3296                    return selection;
 3297                }
 3298
 3299                if let Some(region) = region {
 3300                    let mut range = region.range.to_offset(&buffer);
 3301                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3302                        range.start -= region.pair.start.len();
 3303                        if buffer.contains_str_at(range.start, &region.pair.start)
 3304                            && buffer.contains_str_at(range.end, &region.pair.end)
 3305                        {
 3306                            range.end += region.pair.end.len();
 3307                            selection.start = range.start;
 3308                            selection.end = range.end;
 3309
 3310                            return selection;
 3311                        }
 3312                    }
 3313                }
 3314
 3315                let always_treat_brackets_as_autoclosed = buffer
 3316                    .settings_at(selection.start, cx)
 3317                    .always_treat_brackets_as_autoclosed;
 3318
 3319                if !always_treat_brackets_as_autoclosed {
 3320                    return selection;
 3321                }
 3322
 3323                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3324                    for (pair, enabled) in scope.brackets() {
 3325                        if !enabled || !pair.close {
 3326                            continue;
 3327                        }
 3328
 3329                        if buffer.contains_str_at(selection.start, &pair.end) {
 3330                            let pair_start_len = pair.start.len();
 3331                            if buffer.contains_str_at(
 3332                                selection.start.saturating_sub(pair_start_len),
 3333                                &pair.start,
 3334                            ) {
 3335                                selection.start -= pair_start_len;
 3336                                selection.end += pair.end.len();
 3337
 3338                                return selection;
 3339                            }
 3340                        }
 3341                    }
 3342                }
 3343
 3344                selection
 3345            })
 3346            .collect();
 3347
 3348        drop(buffer);
 3349        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3350    }
 3351
 3352    /// Iterate the given selections, and for each one, find the smallest surrounding
 3353    /// autoclose region. This uses the ordering of the selections and the autoclose
 3354    /// regions to avoid repeated comparisons.
 3355    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3356        &'a self,
 3357        selections: impl IntoIterator<Item = Selection<D>>,
 3358        buffer: &'a MultiBufferSnapshot,
 3359    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3360        let mut i = 0;
 3361        let mut regions = self.autoclose_regions.as_slice();
 3362        selections.into_iter().map(move |selection| {
 3363            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3364
 3365            let mut enclosing = None;
 3366            while let Some(pair_state) = regions.get(i) {
 3367                if pair_state.range.end.to_offset(buffer) < range.start {
 3368                    regions = &regions[i + 1..];
 3369                    i = 0;
 3370                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3371                    break;
 3372                } else {
 3373                    if pair_state.selection_id == selection.id {
 3374                        enclosing = Some(pair_state);
 3375                    }
 3376                    i += 1;
 3377                }
 3378            }
 3379
 3380            (selection, enclosing)
 3381        })
 3382    }
 3383
 3384    /// Remove any autoclose regions that no longer contain their selection.
 3385    fn invalidate_autoclose_regions(
 3386        &mut self,
 3387        mut selections: &[Selection<Anchor>],
 3388        buffer: &MultiBufferSnapshot,
 3389    ) {
 3390        self.autoclose_regions.retain(|state| {
 3391            let mut i = 0;
 3392            while let Some(selection) = selections.get(i) {
 3393                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3394                    selections = &selections[1..];
 3395                    continue;
 3396                }
 3397                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3398                    break;
 3399                }
 3400                if selection.id == state.selection_id {
 3401                    return true;
 3402                } else {
 3403                    i += 1;
 3404                }
 3405            }
 3406            false
 3407        });
 3408    }
 3409
 3410    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3411        let offset = position.to_offset(buffer);
 3412        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3413        if offset > word_range.start && kind == Some(CharKind::Word) {
 3414            Some(
 3415                buffer
 3416                    .text_for_range(word_range.start..offset)
 3417                    .collect::<String>(),
 3418            )
 3419        } else {
 3420            None
 3421        }
 3422    }
 3423
 3424    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3425        self.refresh_inlay_hints(
 3426            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3427            cx,
 3428        );
 3429    }
 3430
 3431    pub fn inlay_hints_enabled(&self) -> bool {
 3432        self.inlay_hint_cache.enabled
 3433    }
 3434
 3435    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3436        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3437            return;
 3438        }
 3439
 3440        let reason_description = reason.description();
 3441        let ignore_debounce = matches!(
 3442            reason,
 3443            InlayHintRefreshReason::SettingsChange(_)
 3444                | InlayHintRefreshReason::Toggle(_)
 3445                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3446        );
 3447        let (invalidate_cache, required_languages) = match reason {
 3448            InlayHintRefreshReason::Toggle(enabled) => {
 3449                self.inlay_hint_cache.enabled = enabled;
 3450                if enabled {
 3451                    (InvalidationStrategy::RefreshRequested, None)
 3452                } else {
 3453                    self.inlay_hint_cache.clear();
 3454                    self.splice_inlays(
 3455                        self.visible_inlay_hints(cx)
 3456                            .iter()
 3457                            .map(|inlay| inlay.id)
 3458                            .collect(),
 3459                        Vec::new(),
 3460                        cx,
 3461                    );
 3462                    return;
 3463                }
 3464            }
 3465            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3466                match self.inlay_hint_cache.update_settings(
 3467                    &self.buffer,
 3468                    new_settings,
 3469                    self.visible_inlay_hints(cx),
 3470                    cx,
 3471                ) {
 3472                    ControlFlow::Break(Some(InlaySplice {
 3473                        to_remove,
 3474                        to_insert,
 3475                    })) => {
 3476                        self.splice_inlays(to_remove, to_insert, cx);
 3477                        return;
 3478                    }
 3479                    ControlFlow::Break(None) => return,
 3480                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3481                }
 3482            }
 3483            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3484                if let Some(InlaySplice {
 3485                    to_remove,
 3486                    to_insert,
 3487                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3488                {
 3489                    self.splice_inlays(to_remove, to_insert, cx);
 3490                }
 3491                return;
 3492            }
 3493            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3494            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3495                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3496            }
 3497            InlayHintRefreshReason::RefreshRequested => {
 3498                (InvalidationStrategy::RefreshRequested, None)
 3499            }
 3500        };
 3501
 3502        if let Some(InlaySplice {
 3503            to_remove,
 3504            to_insert,
 3505        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3506            reason_description,
 3507            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3508            invalidate_cache,
 3509            ignore_debounce,
 3510            cx,
 3511        ) {
 3512            self.splice_inlays(to_remove, to_insert, cx);
 3513        }
 3514    }
 3515
 3516    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3517        self.display_map
 3518            .read(cx)
 3519            .current_inlays()
 3520            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3521            .cloned()
 3522            .collect()
 3523    }
 3524
 3525    pub fn excerpts_for_inlay_hints_query(
 3526        &self,
 3527        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3528        cx: &mut ViewContext<Editor>,
 3529    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3530        let Some(project) = self.project.as_ref() else {
 3531            return HashMap::default();
 3532        };
 3533        let project = project.read(cx);
 3534        let multi_buffer = self.buffer().read(cx);
 3535        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3536        let multi_buffer_visible_start = self
 3537            .scroll_manager
 3538            .anchor()
 3539            .anchor
 3540            .to_point(&multi_buffer_snapshot);
 3541        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3542            multi_buffer_visible_start
 3543                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3544            Bias::Left,
 3545        );
 3546        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3547        multi_buffer
 3548            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3549            .into_iter()
 3550            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3551            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3552                let buffer = buffer_handle.read(cx);
 3553                let buffer_file = project::File::from_dyn(buffer.file())?;
 3554                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3555                let worktree_entry = buffer_worktree
 3556                    .read(cx)
 3557                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3558                if worktree_entry.is_ignored {
 3559                    return None;
 3560                }
 3561
 3562                let language = buffer.language()?;
 3563                if let Some(restrict_to_languages) = restrict_to_languages {
 3564                    if !restrict_to_languages.contains(language) {
 3565                        return None;
 3566                    }
 3567                }
 3568                Some((
 3569                    excerpt_id,
 3570                    (
 3571                        buffer_handle,
 3572                        buffer.version().clone(),
 3573                        excerpt_visible_range,
 3574                    ),
 3575                ))
 3576            })
 3577            .collect()
 3578    }
 3579
 3580    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3581        TextLayoutDetails {
 3582            text_system: cx.text_system().clone(),
 3583            editor_style: self.style.clone().unwrap(),
 3584            rem_size: cx.rem_size(),
 3585            scroll_anchor: self.scroll_manager.anchor(),
 3586            visible_rows: self.visible_line_count(),
 3587            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3588        }
 3589    }
 3590
 3591    fn splice_inlays(
 3592        &self,
 3593        to_remove: Vec<InlayId>,
 3594        to_insert: Vec<Inlay>,
 3595        cx: &mut ViewContext<Self>,
 3596    ) {
 3597        self.display_map.update(cx, |display_map, cx| {
 3598            display_map.splice_inlays(to_remove, to_insert, cx)
 3599        });
 3600        cx.notify();
 3601    }
 3602
 3603    fn trigger_on_type_formatting(
 3604        &self,
 3605        input: String,
 3606        cx: &mut ViewContext<Self>,
 3607    ) -> Option<Task<Result<()>>> {
 3608        if input.len() != 1 {
 3609            return None;
 3610        }
 3611
 3612        let project = self.project.as_ref()?;
 3613        let position = self.selections.newest_anchor().head();
 3614        let (buffer, buffer_position) = self
 3615            .buffer
 3616            .read(cx)
 3617            .text_anchor_for_position(position, cx)?;
 3618
 3619        let settings = language_settings::language_settings(
 3620            buffer
 3621                .read(cx)
 3622                .language_at(buffer_position)
 3623                .map(|l| l.name()),
 3624            buffer.read(cx).file(),
 3625            cx,
 3626        );
 3627        if !settings.use_on_type_format {
 3628            return None;
 3629        }
 3630
 3631        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3632        // hence we do LSP request & edit on host side only — add formats to host's history.
 3633        let push_to_lsp_host_history = true;
 3634        // If this is not the host, append its history with new edits.
 3635        let push_to_client_history = project.read(cx).is_via_collab();
 3636
 3637        let on_type_formatting = project.update(cx, |project, cx| {
 3638            project.on_type_format(
 3639                buffer.clone(),
 3640                buffer_position,
 3641                input,
 3642                push_to_lsp_host_history,
 3643                cx,
 3644            )
 3645        });
 3646        Some(cx.spawn(|editor, mut cx| async move {
 3647            if let Some(transaction) = on_type_formatting.await? {
 3648                if push_to_client_history {
 3649                    buffer
 3650                        .update(&mut cx, |buffer, _| {
 3651                            buffer.push_transaction(transaction, Instant::now());
 3652                        })
 3653                        .ok();
 3654                }
 3655                editor.update(&mut cx, |editor, cx| {
 3656                    editor.refresh_document_highlights(cx);
 3657                })?;
 3658            }
 3659            Ok(())
 3660        }))
 3661    }
 3662
 3663    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3664        if self.pending_rename.is_some() {
 3665            return;
 3666        }
 3667
 3668        let Some(provider) = self.completion_provider.as_ref() else {
 3669            return;
 3670        };
 3671
 3672        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3673            return;
 3674        }
 3675
 3676        let position = self.selections.newest_anchor().head();
 3677        let (buffer, buffer_position) =
 3678            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3679                output
 3680            } else {
 3681                return;
 3682            };
 3683        let show_completion_documentation = buffer
 3684            .read(cx)
 3685            .snapshot()
 3686            .settings_at(buffer_position, cx)
 3687            .show_completion_documentation;
 3688
 3689        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3690
 3691        let trigger_kind = match &options.trigger {
 3692            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3693                CompletionTriggerKind::TRIGGER_CHARACTER
 3694            }
 3695            _ => CompletionTriggerKind::INVOKED,
 3696        };
 3697        let completion_context = CompletionContext {
 3698            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3699                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3700                    Some(String::from(trigger))
 3701                } else {
 3702                    None
 3703                }
 3704            }),
 3705            trigger_kind,
 3706        };
 3707        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3708        let sort_completions = provider.sort_completions();
 3709
 3710        let id = post_inc(&mut self.next_completion_id);
 3711        let task = cx.spawn(|editor, mut cx| {
 3712            async move {
 3713                editor.update(&mut cx, |this, _| {
 3714                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3715                })?;
 3716                let completions = completions.await.log_err();
 3717                let menu = if let Some(completions) = completions {
 3718                    let mut menu = CompletionsMenu::new(
 3719                        id,
 3720                        sort_completions,
 3721                        show_completion_documentation,
 3722                        position,
 3723                        buffer.clone(),
 3724                        completions.into(),
 3725                    );
 3726
 3727                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3728                        .await;
 3729
 3730                    menu.visible().then_some(menu)
 3731                } else {
 3732                    None
 3733                };
 3734
 3735                editor.update(&mut cx, |editor, cx| {
 3736                    match editor.context_menu.borrow().as_ref() {
 3737                        None => {}
 3738                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3739                            if prev_menu.id > id {
 3740                                return;
 3741                            }
 3742                        }
 3743                        _ => return,
 3744                    }
 3745
 3746                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3747                        let mut menu = menu.unwrap();
 3748                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3749
 3750                        if editor.show_inline_completions_in_menu(cx) {
 3751                            if let Some(hint) = editor.inline_completion_menu_hint(cx) {
 3752                                menu.show_inline_completion_hint(hint);
 3753                            }
 3754                        } else {
 3755                            editor.discard_inline_completion(false, cx);
 3756                        }
 3757
 3758                        *editor.context_menu.borrow_mut() =
 3759                            Some(CodeContextMenu::Completions(menu));
 3760
 3761                        cx.notify();
 3762                    } else if editor.completion_tasks.len() <= 1 {
 3763                        // If there are no more completion tasks and the last menu was
 3764                        // empty, we should hide it.
 3765                        let was_hidden = editor.hide_context_menu(cx).is_none();
 3766                        // If it was already hidden and we don't show inline
 3767                        // completions in the menu, we should also show the
 3768                        // inline-completion when available.
 3769                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3770                            editor.update_visible_inline_completion(cx);
 3771                        }
 3772                    }
 3773                })?;
 3774
 3775                Ok::<_, anyhow::Error>(())
 3776            }
 3777            .log_err()
 3778        });
 3779
 3780        self.completion_tasks.push((id, task));
 3781    }
 3782
 3783    pub fn confirm_completion(
 3784        &mut self,
 3785        action: &ConfirmCompletion,
 3786        cx: &mut ViewContext<Self>,
 3787    ) -> Option<Task<Result<()>>> {
 3788        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3789    }
 3790
 3791    pub fn compose_completion(
 3792        &mut self,
 3793        action: &ComposeCompletion,
 3794        cx: &mut ViewContext<Self>,
 3795    ) -> Option<Task<Result<()>>> {
 3796        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3797    }
 3798
 3799    fn do_completion(
 3800        &mut self,
 3801        item_ix: Option<usize>,
 3802        intent: CompletionIntent,
 3803        cx: &mut ViewContext<Editor>,
 3804    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3805        use language::ToOffset as _;
 3806
 3807        let completions_menu =
 3808            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3809                menu
 3810            } else {
 3811                return None;
 3812            };
 3813
 3814        let mat = completions_menu
 3815            .entries
 3816            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3817
 3818        let mat = match mat {
 3819            CompletionEntry::InlineCompletionHint { .. } => {
 3820                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3821                cx.stop_propagation();
 3822                return Some(Task::ready(Ok(())));
 3823            }
 3824            CompletionEntry::Match(mat) => {
 3825                if self.show_inline_completions_in_menu(cx) {
 3826                    self.discard_inline_completion(true, cx);
 3827                }
 3828                mat
 3829            }
 3830        };
 3831
 3832        let buffer_handle = completions_menu.buffer;
 3833        let completions = completions_menu.completions.borrow_mut();
 3834        let completion = completions.get(mat.candidate_id)?;
 3835        cx.stop_propagation();
 3836
 3837        let snippet;
 3838        let text;
 3839
 3840        if completion.is_snippet() {
 3841            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3842            text = snippet.as_ref().unwrap().text.clone();
 3843        } else {
 3844            snippet = None;
 3845            text = completion.new_text.clone();
 3846        };
 3847        let selections = self.selections.all::<usize>(cx);
 3848        let buffer = buffer_handle.read(cx);
 3849        let old_range = completion.old_range.to_offset(buffer);
 3850        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3851
 3852        let newest_selection = self.selections.newest_anchor();
 3853        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3854            return None;
 3855        }
 3856
 3857        let lookbehind = newest_selection
 3858            .start
 3859            .text_anchor
 3860            .to_offset(buffer)
 3861            .saturating_sub(old_range.start);
 3862        let lookahead = old_range
 3863            .end
 3864            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3865        let mut common_prefix_len = old_text
 3866            .bytes()
 3867            .zip(text.bytes())
 3868            .take_while(|(a, b)| a == b)
 3869            .count();
 3870
 3871        let snapshot = self.buffer.read(cx).snapshot(cx);
 3872        let mut range_to_replace: Option<Range<isize>> = None;
 3873        let mut ranges = Vec::new();
 3874        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3875        for selection in &selections {
 3876            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3877                let start = selection.start.saturating_sub(lookbehind);
 3878                let end = selection.end + lookahead;
 3879                if selection.id == newest_selection.id {
 3880                    range_to_replace = Some(
 3881                        ((start + common_prefix_len) as isize - selection.start as isize)
 3882                            ..(end as isize - selection.start as isize),
 3883                    );
 3884                }
 3885                ranges.push(start + common_prefix_len..end);
 3886            } else {
 3887                common_prefix_len = 0;
 3888                ranges.clear();
 3889                ranges.extend(selections.iter().map(|s| {
 3890                    if s.id == newest_selection.id {
 3891                        range_to_replace = Some(
 3892                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3893                                - selection.start as isize
 3894                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3895                                    - selection.start as isize,
 3896                        );
 3897                        old_range.clone()
 3898                    } else {
 3899                        s.start..s.end
 3900                    }
 3901                }));
 3902                break;
 3903            }
 3904            if !self.linked_edit_ranges.is_empty() {
 3905                let start_anchor = snapshot.anchor_before(selection.head());
 3906                let end_anchor = snapshot.anchor_after(selection.tail());
 3907                if let Some(ranges) = self
 3908                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3909                {
 3910                    for (buffer, edits) in ranges {
 3911                        linked_edits.entry(buffer.clone()).or_default().extend(
 3912                            edits
 3913                                .into_iter()
 3914                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3915                        );
 3916                    }
 3917                }
 3918            }
 3919        }
 3920        let text = &text[common_prefix_len..];
 3921
 3922        cx.emit(EditorEvent::InputHandled {
 3923            utf16_range_to_replace: range_to_replace,
 3924            text: text.into(),
 3925        });
 3926
 3927        self.transact(cx, |this, cx| {
 3928            if let Some(mut snippet) = snippet {
 3929                snippet.text = text.to_string();
 3930                for tabstop in snippet
 3931                    .tabstops
 3932                    .iter_mut()
 3933                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3934                {
 3935                    tabstop.start -= common_prefix_len as isize;
 3936                    tabstop.end -= common_prefix_len as isize;
 3937                }
 3938
 3939                this.insert_snippet(&ranges, snippet, cx).log_err();
 3940            } else {
 3941                this.buffer.update(cx, |buffer, cx| {
 3942                    buffer.edit(
 3943                        ranges.iter().map(|range| (range.clone(), text)),
 3944                        this.autoindent_mode.clone(),
 3945                        cx,
 3946                    );
 3947                });
 3948            }
 3949            for (buffer, edits) in linked_edits {
 3950                buffer.update(cx, |buffer, cx| {
 3951                    let snapshot = buffer.snapshot();
 3952                    let edits = edits
 3953                        .into_iter()
 3954                        .map(|(range, text)| {
 3955                            use text::ToPoint as TP;
 3956                            let end_point = TP::to_point(&range.end, &snapshot);
 3957                            let start_point = TP::to_point(&range.start, &snapshot);
 3958                            (start_point..end_point, text)
 3959                        })
 3960                        .sorted_by_key(|(range, _)| range.start)
 3961                        .collect::<Vec<_>>();
 3962                    buffer.edit(edits, None, cx);
 3963                })
 3964            }
 3965
 3966            this.refresh_inline_completion(true, false, cx);
 3967        });
 3968
 3969        let show_new_completions_on_confirm = completion
 3970            .confirm
 3971            .as_ref()
 3972            .map_or(false, |confirm| confirm(intent, cx));
 3973        if show_new_completions_on_confirm {
 3974            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3975        }
 3976
 3977        let provider = self.completion_provider.as_ref()?;
 3978        let apply_edits = provider.apply_additional_edits_for_completion(
 3979            buffer_handle,
 3980            completion.clone(),
 3981            true,
 3982            cx,
 3983        );
 3984
 3985        let editor_settings = EditorSettings::get_global(cx);
 3986        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 3987            // After the code completion is finished, users often want to know what signatures are needed.
 3988            // so we should automatically call signature_help
 3989            self.show_signature_help(&ShowSignatureHelp, cx);
 3990        }
 3991
 3992        Some(cx.foreground_executor().spawn(async move {
 3993            apply_edits.await?;
 3994            Ok(())
 3995        }))
 3996    }
 3997
 3998    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 3999        let mut context_menu = self.context_menu.borrow_mut();
 4000        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4001            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4002                // Toggle if we're selecting the same one
 4003                *context_menu = None;
 4004                cx.notify();
 4005                return;
 4006            } else {
 4007                // Otherwise, clear it and start a new one
 4008                *context_menu = None;
 4009                cx.notify();
 4010            }
 4011        }
 4012        drop(context_menu);
 4013        let snapshot = self.snapshot(cx);
 4014        let deployed_from_indicator = action.deployed_from_indicator;
 4015        let mut task = self.code_actions_task.take();
 4016        let action = action.clone();
 4017        cx.spawn(|editor, mut cx| async move {
 4018            while let Some(prev_task) = task {
 4019                prev_task.await.log_err();
 4020                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4021            }
 4022
 4023            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4024                if editor.focus_handle.is_focused(cx) {
 4025                    let multibuffer_point = action
 4026                        .deployed_from_indicator
 4027                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4028                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4029                    let (buffer, buffer_row) = snapshot
 4030                        .buffer_snapshot
 4031                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4032                        .and_then(|(buffer_snapshot, range)| {
 4033                            editor
 4034                                .buffer
 4035                                .read(cx)
 4036                                .buffer(buffer_snapshot.remote_id())
 4037                                .map(|buffer| (buffer, range.start.row))
 4038                        })?;
 4039                    let (_, code_actions) = editor
 4040                        .available_code_actions
 4041                        .clone()
 4042                        .and_then(|(location, code_actions)| {
 4043                            let snapshot = location.buffer.read(cx).snapshot();
 4044                            let point_range = location.range.to_point(&snapshot);
 4045                            let point_range = point_range.start.row..=point_range.end.row;
 4046                            if point_range.contains(&buffer_row) {
 4047                                Some((location, code_actions))
 4048                            } else {
 4049                                None
 4050                            }
 4051                        })
 4052                        .unzip();
 4053                    let buffer_id = buffer.read(cx).remote_id();
 4054                    let tasks = editor
 4055                        .tasks
 4056                        .get(&(buffer_id, buffer_row))
 4057                        .map(|t| Arc::new(t.to_owned()));
 4058                    if tasks.is_none() && code_actions.is_none() {
 4059                        return None;
 4060                    }
 4061
 4062                    editor.completion_tasks.clear();
 4063                    editor.discard_inline_completion(false, cx);
 4064                    let task_context =
 4065                        tasks
 4066                            .as_ref()
 4067                            .zip(editor.project.clone())
 4068                            .map(|(tasks, project)| {
 4069                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4070                            });
 4071
 4072                    Some(cx.spawn(|editor, mut cx| async move {
 4073                        let task_context = match task_context {
 4074                            Some(task_context) => task_context.await,
 4075                            None => None,
 4076                        };
 4077                        let resolved_tasks =
 4078                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4079                                Rc::new(ResolvedTasks {
 4080                                    templates: tasks.resolve(&task_context).collect(),
 4081                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4082                                        multibuffer_point.row,
 4083                                        tasks.column,
 4084                                    )),
 4085                                })
 4086                            });
 4087                        let spawn_straight_away = resolved_tasks
 4088                            .as_ref()
 4089                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4090                            && code_actions
 4091                                .as_ref()
 4092                                .map_or(true, |actions| actions.is_empty());
 4093                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4094                            *editor.context_menu.borrow_mut() =
 4095                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4096                                    buffer,
 4097                                    actions: CodeActionContents {
 4098                                        tasks: resolved_tasks,
 4099                                        actions: code_actions,
 4100                                    },
 4101                                    selected_item: Default::default(),
 4102                                    scroll_handle: UniformListScrollHandle::default(),
 4103                                    deployed_from_indicator,
 4104                                }));
 4105                            if spawn_straight_away {
 4106                                if let Some(task) = editor.confirm_code_action(
 4107                                    &ConfirmCodeAction { item_ix: Some(0) },
 4108                                    cx,
 4109                                ) {
 4110                                    cx.notify();
 4111                                    return task;
 4112                                }
 4113                            }
 4114                            cx.notify();
 4115                            Task::ready(Ok(()))
 4116                        }) {
 4117                            task.await
 4118                        } else {
 4119                            Ok(())
 4120                        }
 4121                    }))
 4122                } else {
 4123                    Some(Task::ready(Ok(())))
 4124                }
 4125            })?;
 4126            if let Some(task) = spawned_test_task {
 4127                task.await?;
 4128            }
 4129
 4130            Ok::<_, anyhow::Error>(())
 4131        })
 4132        .detach_and_log_err(cx);
 4133    }
 4134
 4135    pub fn confirm_code_action(
 4136        &mut self,
 4137        action: &ConfirmCodeAction,
 4138        cx: &mut ViewContext<Self>,
 4139    ) -> Option<Task<Result<()>>> {
 4140        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4141            menu
 4142        } else {
 4143            return None;
 4144        };
 4145        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4146        let action = actions_menu.actions.get(action_ix)?;
 4147        let title = action.label();
 4148        let buffer = actions_menu.buffer;
 4149        let workspace = self.workspace()?;
 4150
 4151        match action {
 4152            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4153                workspace.update(cx, |workspace, cx| {
 4154                    workspace::tasks::schedule_resolved_task(
 4155                        workspace,
 4156                        task_source_kind,
 4157                        resolved_task,
 4158                        false,
 4159                        cx,
 4160                    );
 4161
 4162                    Some(Task::ready(Ok(())))
 4163                })
 4164            }
 4165            CodeActionsItem::CodeAction {
 4166                excerpt_id,
 4167                action,
 4168                provider,
 4169            } => {
 4170                let apply_code_action =
 4171                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4172                let workspace = workspace.downgrade();
 4173                Some(cx.spawn(|editor, cx| async move {
 4174                    let project_transaction = apply_code_action.await?;
 4175                    Self::open_project_transaction(
 4176                        &editor,
 4177                        workspace,
 4178                        project_transaction,
 4179                        title,
 4180                        cx,
 4181                    )
 4182                    .await
 4183                }))
 4184            }
 4185        }
 4186    }
 4187
 4188    pub async fn open_project_transaction(
 4189        this: &WeakView<Editor>,
 4190        workspace: WeakView<Workspace>,
 4191        transaction: ProjectTransaction,
 4192        title: String,
 4193        mut cx: AsyncWindowContext,
 4194    ) -> Result<()> {
 4195        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4196        cx.update(|cx| {
 4197            entries.sort_unstable_by_key(|(buffer, _)| {
 4198                buffer.read(cx).file().map(|f| f.path().clone())
 4199            });
 4200        })?;
 4201
 4202        // If the project transaction's edits are all contained within this editor, then
 4203        // avoid opening a new editor to display them.
 4204
 4205        if let Some((buffer, transaction)) = entries.first() {
 4206            if entries.len() == 1 {
 4207                let excerpt = this.update(&mut cx, |editor, cx| {
 4208                    editor
 4209                        .buffer()
 4210                        .read(cx)
 4211                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4212                })?;
 4213                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4214                    if excerpted_buffer == *buffer {
 4215                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4216                            let excerpt_range = excerpt_range.to_offset(buffer);
 4217                            buffer
 4218                                .edited_ranges_for_transaction::<usize>(transaction)
 4219                                .all(|range| {
 4220                                    excerpt_range.start <= range.start
 4221                                        && excerpt_range.end >= range.end
 4222                                })
 4223                        })?;
 4224
 4225                        if all_edits_within_excerpt {
 4226                            return Ok(());
 4227                        }
 4228                    }
 4229                }
 4230            }
 4231        } else {
 4232            return Ok(());
 4233        }
 4234
 4235        let mut ranges_to_highlight = Vec::new();
 4236        let excerpt_buffer = cx.new_model(|cx| {
 4237            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4238            for (buffer_handle, transaction) in &entries {
 4239                let buffer = buffer_handle.read(cx);
 4240                ranges_to_highlight.extend(
 4241                    multibuffer.push_excerpts_with_context_lines(
 4242                        buffer_handle.clone(),
 4243                        buffer
 4244                            .edited_ranges_for_transaction::<usize>(transaction)
 4245                            .collect(),
 4246                        DEFAULT_MULTIBUFFER_CONTEXT,
 4247                        cx,
 4248                    ),
 4249                );
 4250            }
 4251            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4252            multibuffer
 4253        })?;
 4254
 4255        workspace.update(&mut cx, |workspace, cx| {
 4256            let project = workspace.project().clone();
 4257            let editor =
 4258                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4259            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4260            editor.update(cx, |editor, cx| {
 4261                editor.highlight_background::<Self>(
 4262                    &ranges_to_highlight,
 4263                    |theme| theme.editor_highlighted_line_background,
 4264                    cx,
 4265                );
 4266            });
 4267        })?;
 4268
 4269        Ok(())
 4270    }
 4271
 4272    pub fn clear_code_action_providers(&mut self) {
 4273        self.code_action_providers.clear();
 4274        self.available_code_actions.take();
 4275    }
 4276
 4277    pub fn push_code_action_provider(
 4278        &mut self,
 4279        provider: Rc<dyn CodeActionProvider>,
 4280        cx: &mut ViewContext<Self>,
 4281    ) {
 4282        self.code_action_providers.push(provider);
 4283        self.refresh_code_actions(cx);
 4284    }
 4285
 4286    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4287        let buffer = self.buffer.read(cx);
 4288        let newest_selection = self.selections.newest_anchor().clone();
 4289        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4290        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4291        if start_buffer != end_buffer {
 4292            return None;
 4293        }
 4294
 4295        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4296            cx.background_executor()
 4297                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4298                .await;
 4299
 4300            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4301                let providers = this.code_action_providers.clone();
 4302                let tasks = this
 4303                    .code_action_providers
 4304                    .iter()
 4305                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4306                    .collect::<Vec<_>>();
 4307                (providers, tasks)
 4308            })?;
 4309
 4310            let mut actions = Vec::new();
 4311            for (provider, provider_actions) in
 4312                providers.into_iter().zip(future::join_all(tasks).await)
 4313            {
 4314                if let Some(provider_actions) = provider_actions.log_err() {
 4315                    actions.extend(provider_actions.into_iter().map(|action| {
 4316                        AvailableCodeAction {
 4317                            excerpt_id: newest_selection.start.excerpt_id,
 4318                            action,
 4319                            provider: provider.clone(),
 4320                        }
 4321                    }));
 4322                }
 4323            }
 4324
 4325            this.update(&mut cx, |this, cx| {
 4326                this.available_code_actions = if actions.is_empty() {
 4327                    None
 4328                } else {
 4329                    Some((
 4330                        Location {
 4331                            buffer: start_buffer,
 4332                            range: start..end,
 4333                        },
 4334                        actions.into(),
 4335                    ))
 4336                };
 4337                cx.notify();
 4338            })
 4339        }));
 4340        None
 4341    }
 4342
 4343    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4344        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4345            self.show_git_blame_inline = false;
 4346
 4347            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4348                cx.background_executor().timer(delay).await;
 4349
 4350                this.update(&mut cx, |this, cx| {
 4351                    this.show_git_blame_inline = true;
 4352                    cx.notify();
 4353                })
 4354                .log_err();
 4355            }));
 4356        }
 4357    }
 4358
 4359    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4360        if self.pending_rename.is_some() {
 4361            return None;
 4362        }
 4363
 4364        let provider = self.semantics_provider.clone()?;
 4365        let buffer = self.buffer.read(cx);
 4366        let newest_selection = self.selections.newest_anchor().clone();
 4367        let cursor_position = newest_selection.head();
 4368        let (cursor_buffer, cursor_buffer_position) =
 4369            buffer.text_anchor_for_position(cursor_position, cx)?;
 4370        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4371        if cursor_buffer != tail_buffer {
 4372            return None;
 4373        }
 4374        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4375        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4376            cx.background_executor()
 4377                .timer(Duration::from_millis(debounce))
 4378                .await;
 4379
 4380            let highlights = if let Some(highlights) = cx
 4381                .update(|cx| {
 4382                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4383                })
 4384                .ok()
 4385                .flatten()
 4386            {
 4387                highlights.await.log_err()
 4388            } else {
 4389                None
 4390            };
 4391
 4392            if let Some(highlights) = highlights {
 4393                this.update(&mut cx, |this, cx| {
 4394                    if this.pending_rename.is_some() {
 4395                        return;
 4396                    }
 4397
 4398                    let buffer_id = cursor_position.buffer_id;
 4399                    let buffer = this.buffer.read(cx);
 4400                    if !buffer
 4401                        .text_anchor_for_position(cursor_position, cx)
 4402                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4403                    {
 4404                        return;
 4405                    }
 4406
 4407                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4408                    let mut write_ranges = Vec::new();
 4409                    let mut read_ranges = Vec::new();
 4410                    for highlight in highlights {
 4411                        for (excerpt_id, excerpt_range) in
 4412                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4413                        {
 4414                            let start = highlight
 4415                                .range
 4416                                .start
 4417                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4418                            let end = highlight
 4419                                .range
 4420                                .end
 4421                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4422                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4423                                continue;
 4424                            }
 4425
 4426                            let range = Anchor {
 4427                                buffer_id,
 4428                                excerpt_id,
 4429                                text_anchor: start,
 4430                            }..Anchor {
 4431                                buffer_id,
 4432                                excerpt_id,
 4433                                text_anchor: end,
 4434                            };
 4435                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4436                                write_ranges.push(range);
 4437                            } else {
 4438                                read_ranges.push(range);
 4439                            }
 4440                        }
 4441                    }
 4442
 4443                    this.highlight_background::<DocumentHighlightRead>(
 4444                        &read_ranges,
 4445                        |theme| theme.editor_document_highlight_read_background,
 4446                        cx,
 4447                    );
 4448                    this.highlight_background::<DocumentHighlightWrite>(
 4449                        &write_ranges,
 4450                        |theme| theme.editor_document_highlight_write_background,
 4451                        cx,
 4452                    );
 4453                    cx.notify();
 4454                })
 4455                .log_err();
 4456            }
 4457        }));
 4458        None
 4459    }
 4460
 4461    pub fn refresh_inline_completion(
 4462        &mut self,
 4463        debounce: bool,
 4464        user_requested: bool,
 4465        cx: &mut ViewContext<Self>,
 4466    ) -> Option<()> {
 4467        let provider = self.inline_completion_provider()?;
 4468        let cursor = self.selections.newest_anchor().head();
 4469        let (buffer, cursor_buffer_position) =
 4470            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4471
 4472        if !user_requested
 4473            && (!self.enable_inline_completions
 4474                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4475                || !self.is_focused(cx))
 4476        {
 4477            self.discard_inline_completion(false, cx);
 4478            return None;
 4479        }
 4480
 4481        self.update_visible_inline_completion(cx);
 4482        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4483        Some(())
 4484    }
 4485
 4486    fn cycle_inline_completion(
 4487        &mut self,
 4488        direction: Direction,
 4489        cx: &mut ViewContext<Self>,
 4490    ) -> Option<()> {
 4491        let provider = self.inline_completion_provider()?;
 4492        let cursor = self.selections.newest_anchor().head();
 4493        let (buffer, cursor_buffer_position) =
 4494            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4495        if !self.enable_inline_completions
 4496            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4497        {
 4498            return None;
 4499        }
 4500
 4501        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4502        self.update_visible_inline_completion(cx);
 4503
 4504        Some(())
 4505    }
 4506
 4507    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4508        if !self.has_active_inline_completion() {
 4509            self.refresh_inline_completion(false, true, cx);
 4510            return;
 4511        }
 4512
 4513        self.update_visible_inline_completion(cx);
 4514    }
 4515
 4516    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4517        self.show_cursor_names(cx);
 4518    }
 4519
 4520    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4521        self.show_cursor_names = true;
 4522        cx.notify();
 4523        cx.spawn(|this, mut cx| async move {
 4524            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4525            this.update(&mut cx, |this, cx| {
 4526                this.show_cursor_names = false;
 4527                cx.notify()
 4528            })
 4529            .ok()
 4530        })
 4531        .detach();
 4532    }
 4533
 4534    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4535        if self.has_active_inline_completion() {
 4536            self.cycle_inline_completion(Direction::Next, cx);
 4537        } else {
 4538            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4539            if is_copilot_disabled {
 4540                cx.propagate();
 4541            }
 4542        }
 4543    }
 4544
 4545    pub fn previous_inline_completion(
 4546        &mut self,
 4547        _: &PreviousInlineCompletion,
 4548        cx: &mut ViewContext<Self>,
 4549    ) {
 4550        if self.has_active_inline_completion() {
 4551            self.cycle_inline_completion(Direction::Prev, cx);
 4552        } else {
 4553            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4554            if is_copilot_disabled {
 4555                cx.propagate();
 4556            }
 4557        }
 4558    }
 4559
 4560    pub fn accept_inline_completion(
 4561        &mut self,
 4562        _: &AcceptInlineCompletion,
 4563        cx: &mut ViewContext<Self>,
 4564    ) {
 4565        if self.show_inline_completions_in_menu(cx) {
 4566            self.hide_context_menu(cx);
 4567        }
 4568
 4569        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4570            return;
 4571        };
 4572
 4573        self.report_inline_completion_event(true, cx);
 4574
 4575        match &active_inline_completion.completion {
 4576            InlineCompletion::Move(position) => {
 4577                let position = *position;
 4578                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4579                    selections.select_anchor_ranges([position..position]);
 4580                });
 4581            }
 4582            InlineCompletion::Edit(edits) => {
 4583                if let Some(provider) = self.inline_completion_provider() {
 4584                    provider.accept(cx);
 4585                }
 4586
 4587                let snapshot = self.buffer.read(cx).snapshot(cx);
 4588                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4589
 4590                self.buffer.update(cx, |buffer, cx| {
 4591                    buffer.edit(edits.iter().cloned(), None, cx)
 4592                });
 4593
 4594                self.change_selections(None, cx, |s| {
 4595                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4596                });
 4597
 4598                self.update_visible_inline_completion(cx);
 4599                if self.active_inline_completion.is_none() {
 4600                    self.refresh_inline_completion(true, true, cx);
 4601                }
 4602
 4603                cx.notify();
 4604            }
 4605        }
 4606    }
 4607
 4608    pub fn accept_partial_inline_completion(
 4609        &mut self,
 4610        _: &AcceptPartialInlineCompletion,
 4611        cx: &mut ViewContext<Self>,
 4612    ) {
 4613        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4614            return;
 4615        };
 4616        if self.selections.count() != 1 {
 4617            return;
 4618        }
 4619
 4620        self.report_inline_completion_event(true, cx);
 4621
 4622        match &active_inline_completion.completion {
 4623            InlineCompletion::Move(position) => {
 4624                let position = *position;
 4625                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4626                    selections.select_anchor_ranges([position..position]);
 4627                });
 4628            }
 4629            InlineCompletion::Edit(edits) => {
 4630                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4631                    let text = edits[0].1.as_str();
 4632                    let mut partial_completion = text
 4633                        .chars()
 4634                        .by_ref()
 4635                        .take_while(|c| c.is_alphabetic())
 4636                        .collect::<String>();
 4637                    if partial_completion.is_empty() {
 4638                        partial_completion = text
 4639                            .chars()
 4640                            .by_ref()
 4641                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4642                            .collect::<String>();
 4643                    }
 4644
 4645                    cx.emit(EditorEvent::InputHandled {
 4646                        utf16_range_to_replace: None,
 4647                        text: partial_completion.clone().into(),
 4648                    });
 4649
 4650                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4651
 4652                    self.refresh_inline_completion(true, true, cx);
 4653                    cx.notify();
 4654                }
 4655            }
 4656        }
 4657    }
 4658
 4659    fn discard_inline_completion(
 4660        &mut self,
 4661        should_report_inline_completion_event: bool,
 4662        cx: &mut ViewContext<Self>,
 4663    ) -> bool {
 4664        if should_report_inline_completion_event {
 4665            self.report_inline_completion_event(false, cx);
 4666        }
 4667
 4668        if let Some(provider) = self.inline_completion_provider() {
 4669            provider.discard(cx);
 4670        }
 4671
 4672        self.take_active_inline_completion(cx).is_some()
 4673    }
 4674
 4675    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4676        let Some(provider) = self.inline_completion_provider() else {
 4677            return;
 4678        };
 4679        let Some(project) = self.project.as_ref() else {
 4680            return;
 4681        };
 4682        let Some((_, buffer, _)) = self
 4683            .buffer
 4684            .read(cx)
 4685            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4686        else {
 4687            return;
 4688        };
 4689
 4690        let project = project.read(cx);
 4691        let extension = buffer
 4692            .read(cx)
 4693            .file()
 4694            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4695        project.client().telemetry().report_inline_completion_event(
 4696            provider.name().into(),
 4697            accepted,
 4698            extension,
 4699        );
 4700    }
 4701
 4702    pub fn has_active_inline_completion(&self) -> bool {
 4703        self.active_inline_completion.is_some()
 4704    }
 4705
 4706    fn take_active_inline_completion(
 4707        &mut self,
 4708        cx: &mut ViewContext<Self>,
 4709    ) -> Option<InlineCompletion> {
 4710        let active_inline_completion = self.active_inline_completion.take()?;
 4711        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4712        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4713        Some(active_inline_completion.completion)
 4714    }
 4715
 4716    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4717        let selection = self.selections.newest_anchor();
 4718        let cursor = selection.head();
 4719        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4720        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4721        let excerpt_id = cursor.excerpt_id;
 4722
 4723        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 4724            && (self.context_menu.borrow().is_some()
 4725                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 4726        if completions_menu_has_precedence
 4727            || !offset_selection.is_empty()
 4728            || self
 4729                .active_inline_completion
 4730                .as_ref()
 4731                .map_or(false, |completion| {
 4732                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4733                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4734                    !invalidation_range.contains(&offset_selection.head())
 4735                })
 4736        {
 4737            self.discard_inline_completion(false, cx);
 4738            return None;
 4739        }
 4740
 4741        self.take_active_inline_completion(cx);
 4742        let provider = self.inline_completion_provider()?;
 4743
 4744        let (buffer, cursor_buffer_position) =
 4745            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4746
 4747        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4748        let edits = completion
 4749            .edits
 4750            .into_iter()
 4751            .flat_map(|(range, new_text)| {
 4752                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4753                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4754                Some((start..end, new_text))
 4755            })
 4756            .collect::<Vec<_>>();
 4757        if edits.is_empty() {
 4758            return None;
 4759        }
 4760
 4761        let first_edit_start = edits.first().unwrap().0.start;
 4762        let edit_start_row = first_edit_start
 4763            .to_point(&multibuffer)
 4764            .row
 4765            .saturating_sub(2);
 4766
 4767        let last_edit_end = edits.last().unwrap().0.end;
 4768        let edit_end_row = cmp::min(
 4769            multibuffer.max_point().row,
 4770            last_edit_end.to_point(&multibuffer).row + 2,
 4771        );
 4772
 4773        let cursor_row = cursor.to_point(&multibuffer).row;
 4774
 4775        let mut inlay_ids = Vec::new();
 4776        let invalidation_row_range;
 4777        let completion;
 4778        if cursor_row < edit_start_row {
 4779            invalidation_row_range = cursor_row..edit_end_row;
 4780            completion = InlineCompletion::Move(first_edit_start);
 4781        } else if cursor_row > edit_end_row {
 4782            invalidation_row_range = edit_start_row..cursor_row;
 4783            completion = InlineCompletion::Move(first_edit_start);
 4784        } else {
 4785            if edits
 4786                .iter()
 4787                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4788            {
 4789                let mut inlays = Vec::new();
 4790                for (range, new_text) in &edits {
 4791                    let inlay = Inlay::inline_completion(
 4792                        post_inc(&mut self.next_inlay_id),
 4793                        range.start,
 4794                        new_text.as_str(),
 4795                    );
 4796                    inlay_ids.push(inlay.id);
 4797                    inlays.push(inlay);
 4798                }
 4799
 4800                self.splice_inlays(vec![], inlays, cx);
 4801            } else {
 4802                let background_color = cx.theme().status().deleted_background;
 4803                self.highlight_text::<InlineCompletionHighlight>(
 4804                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4805                    HighlightStyle {
 4806                        background_color: Some(background_color),
 4807                        ..Default::default()
 4808                    },
 4809                    cx,
 4810                );
 4811            }
 4812
 4813            invalidation_row_range = edit_start_row..edit_end_row;
 4814            completion = InlineCompletion::Edit(edits);
 4815        };
 4816
 4817        let invalidation_range = multibuffer
 4818            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4819            ..multibuffer.anchor_after(Point::new(
 4820                invalidation_row_range.end,
 4821                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4822            ));
 4823
 4824        self.active_inline_completion = Some(InlineCompletionState {
 4825            inlay_ids,
 4826            completion,
 4827            invalidation_range,
 4828        });
 4829
 4830        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 4831            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4832                match self.context_menu.borrow_mut().as_mut() {
 4833                    Some(CodeContextMenu::Completions(menu)) => {
 4834                        menu.show_inline_completion_hint(hint);
 4835                    }
 4836                    _ => {}
 4837                }
 4838            }
 4839        }
 4840
 4841        cx.notify();
 4842
 4843        Some(())
 4844    }
 4845
 4846    fn inline_completion_menu_hint(
 4847        &mut self,
 4848        cx: &mut ViewContext<Self>,
 4849    ) -> Option<InlineCompletionMenuHint> {
 4850        if self.has_active_inline_completion() {
 4851            let provider_name = self.inline_completion_provider()?.display_name();
 4852            let editor_snapshot = self.snapshot(cx);
 4853
 4854            let text = match &self.active_inline_completion.as_ref()?.completion {
 4855                InlineCompletion::Edit(edits) => {
 4856                    inline_completion_edit_text(&editor_snapshot, edits, true, cx)
 4857                }
 4858                InlineCompletion::Move(target) => {
 4859                    let target_point =
 4860                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4861                    let target_line = target_point.row + 1;
 4862                    InlineCompletionText::Move(
 4863                        format!("Jump to edit in line {}", target_line).into(),
 4864                    )
 4865                }
 4866            };
 4867
 4868            Some(InlineCompletionMenuHint {
 4869                provider_name,
 4870                text,
 4871            })
 4872        } else {
 4873            None
 4874        }
 4875    }
 4876
 4877    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4878        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4879    }
 4880
 4881    fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
 4882        EditorSettings::get_global(cx).show_inline_completions_in_menu
 4883            && self
 4884                .inline_completion_provider()
 4885                .map_or(false, |provider| provider.show_completions_in_menu())
 4886    }
 4887
 4888    fn render_code_actions_indicator(
 4889        &self,
 4890        _style: &EditorStyle,
 4891        row: DisplayRow,
 4892        is_active: bool,
 4893        cx: &mut ViewContext<Self>,
 4894    ) -> Option<IconButton> {
 4895        if self.available_code_actions.is_some() {
 4896            Some(
 4897                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4898                    .shape(ui::IconButtonShape::Square)
 4899                    .icon_size(IconSize::XSmall)
 4900                    .icon_color(Color::Muted)
 4901                    .toggle_state(is_active)
 4902                    .tooltip({
 4903                        let focus_handle = self.focus_handle.clone();
 4904                        move |cx| {
 4905                            Tooltip::for_action_in(
 4906                                "Toggle Code Actions",
 4907                                &ToggleCodeActions {
 4908                                    deployed_from_indicator: None,
 4909                                },
 4910                                &focus_handle,
 4911                                cx,
 4912                            )
 4913                        }
 4914                    })
 4915                    .on_click(cx.listener(move |editor, _e, cx| {
 4916                        editor.focus(cx);
 4917                        editor.toggle_code_actions(
 4918                            &ToggleCodeActions {
 4919                                deployed_from_indicator: Some(row),
 4920                            },
 4921                            cx,
 4922                        );
 4923                    })),
 4924            )
 4925        } else {
 4926            None
 4927        }
 4928    }
 4929
 4930    fn clear_tasks(&mut self) {
 4931        self.tasks.clear()
 4932    }
 4933
 4934    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4935        if self.tasks.insert(key, value).is_some() {
 4936            // This case should hopefully be rare, but just in case...
 4937            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4938        }
 4939    }
 4940
 4941    fn build_tasks_context(
 4942        project: &Model<Project>,
 4943        buffer: &Model<Buffer>,
 4944        buffer_row: u32,
 4945        tasks: &Arc<RunnableTasks>,
 4946        cx: &mut ViewContext<Self>,
 4947    ) -> Task<Option<task::TaskContext>> {
 4948        let position = Point::new(buffer_row, tasks.column);
 4949        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4950        let location = Location {
 4951            buffer: buffer.clone(),
 4952            range: range_start..range_start,
 4953        };
 4954        // Fill in the environmental variables from the tree-sitter captures
 4955        let mut captured_task_variables = TaskVariables::default();
 4956        for (capture_name, value) in tasks.extra_variables.clone() {
 4957            captured_task_variables.insert(
 4958                task::VariableName::Custom(capture_name.into()),
 4959                value.clone(),
 4960            );
 4961        }
 4962        project.update(cx, |project, cx| {
 4963            project.task_store().update(cx, |task_store, cx| {
 4964                task_store.task_context_for_location(captured_task_variables, location, cx)
 4965            })
 4966        })
 4967    }
 4968
 4969    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 4970        let Some((workspace, _)) = self.workspace.clone() else {
 4971            return;
 4972        };
 4973        let Some(project) = self.project.clone() else {
 4974            return;
 4975        };
 4976
 4977        // Try to find a closest, enclosing node using tree-sitter that has a
 4978        // task
 4979        let Some((buffer, buffer_row, tasks)) = self
 4980            .find_enclosing_node_task(cx)
 4981            // Or find the task that's closest in row-distance.
 4982            .or_else(|| self.find_closest_task(cx))
 4983        else {
 4984            return;
 4985        };
 4986
 4987        let reveal_strategy = action.reveal;
 4988        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 4989        cx.spawn(|_, mut cx| async move {
 4990            let context = task_context.await?;
 4991            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 4992
 4993            let resolved = resolved_task.resolved.as_mut()?;
 4994            resolved.reveal = reveal_strategy;
 4995
 4996            workspace
 4997                .update(&mut cx, |workspace, cx| {
 4998                    workspace::tasks::schedule_resolved_task(
 4999                        workspace,
 5000                        task_source_kind,
 5001                        resolved_task,
 5002                        false,
 5003                        cx,
 5004                    );
 5005                })
 5006                .ok()
 5007        })
 5008        .detach();
 5009    }
 5010
 5011    fn find_closest_task(
 5012        &mut self,
 5013        cx: &mut ViewContext<Self>,
 5014    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5015        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5016
 5017        let ((buffer_id, row), tasks) = self
 5018            .tasks
 5019            .iter()
 5020            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5021
 5022        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5023        let tasks = Arc::new(tasks.to_owned());
 5024        Some((buffer, *row, tasks))
 5025    }
 5026
 5027    fn find_enclosing_node_task(
 5028        &mut self,
 5029        cx: &mut ViewContext<Self>,
 5030    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5031        let snapshot = self.buffer.read(cx).snapshot(cx);
 5032        let offset = self.selections.newest::<usize>(cx).head();
 5033        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5034        let buffer_id = excerpt.buffer().remote_id();
 5035
 5036        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5037        let mut cursor = layer.node().walk();
 5038
 5039        while cursor.goto_first_child_for_byte(offset).is_some() {
 5040            if cursor.node().end_byte() == offset {
 5041                cursor.goto_next_sibling();
 5042            }
 5043        }
 5044
 5045        // Ascend to the smallest ancestor that contains the range and has a task.
 5046        loop {
 5047            let node = cursor.node();
 5048            let node_range = node.byte_range();
 5049            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5050
 5051            // Check if this node contains our offset
 5052            if node_range.start <= offset && node_range.end >= offset {
 5053                // If it contains offset, check for task
 5054                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5055                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5056                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5057                }
 5058            }
 5059
 5060            if !cursor.goto_parent() {
 5061                break;
 5062            }
 5063        }
 5064        None
 5065    }
 5066
 5067    fn render_run_indicator(
 5068        &self,
 5069        _style: &EditorStyle,
 5070        is_active: bool,
 5071        row: DisplayRow,
 5072        cx: &mut ViewContext<Self>,
 5073    ) -> IconButton {
 5074        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5075            .shape(ui::IconButtonShape::Square)
 5076            .icon_size(IconSize::XSmall)
 5077            .icon_color(Color::Muted)
 5078            .toggle_state(is_active)
 5079            .on_click(cx.listener(move |editor, _e, cx| {
 5080                editor.focus(cx);
 5081                editor.toggle_code_actions(
 5082                    &ToggleCodeActions {
 5083                        deployed_from_indicator: Some(row),
 5084                    },
 5085                    cx,
 5086                );
 5087            }))
 5088    }
 5089
 5090    #[cfg(feature = "test-support")]
 5091    pub fn context_menu_visible(&self) -> bool {
 5092        self.context_menu
 5093            .borrow()
 5094            .as_ref()
 5095            .map_or(false, |menu| menu.visible())
 5096    }
 5097
 5098    #[cfg(feature = "test-support")]
 5099    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5100        self.context_menu
 5101            .borrow()
 5102            .as_ref()
 5103            .map_or(false, |menu| match menu {
 5104                CodeContextMenu::Completions(menu) => menu.entries.first().map_or(false, |entry| {
 5105                    matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5106                }),
 5107                CodeContextMenu::CodeActions(_) => false,
 5108            })
 5109    }
 5110
 5111    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5112        self.context_menu
 5113            .borrow()
 5114            .as_ref()
 5115            .map(|menu| menu.origin(cursor_position))
 5116    }
 5117
 5118    fn render_context_menu(
 5119        &self,
 5120        style: &EditorStyle,
 5121        max_height_in_lines: u32,
 5122        cx: &mut ViewContext<Editor>,
 5123    ) -> Option<AnyElement> {
 5124        self.context_menu.borrow().as_ref().and_then(|menu| {
 5125            if menu.visible() {
 5126                Some(menu.render(style, max_height_in_lines, cx))
 5127            } else {
 5128                None
 5129            }
 5130        })
 5131    }
 5132
 5133    fn render_context_menu_aside(
 5134        &self,
 5135        style: &EditorStyle,
 5136        max_size: Size<Pixels>,
 5137        cx: &mut ViewContext<Editor>,
 5138    ) -> Option<AnyElement> {
 5139        self.context_menu.borrow().as_ref().and_then(|menu| {
 5140            if menu.visible() {
 5141                menu.render_aside(
 5142                    style,
 5143                    max_size,
 5144                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5145                    cx,
 5146                )
 5147            } else {
 5148                None
 5149            }
 5150        })
 5151    }
 5152
 5153    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5154        cx.notify();
 5155        self.completion_tasks.clear();
 5156        let context_menu = self.context_menu.borrow_mut().take();
 5157        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5158            self.update_visible_inline_completion(cx);
 5159        }
 5160        context_menu
 5161    }
 5162
 5163    fn show_snippet_choices(
 5164        &mut self,
 5165        choices: &Vec<String>,
 5166        selection: Range<Anchor>,
 5167        cx: &mut ViewContext<Self>,
 5168    ) {
 5169        if selection.start.buffer_id.is_none() {
 5170            return;
 5171        }
 5172        let buffer_id = selection.start.buffer_id.unwrap();
 5173        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5174        let id = post_inc(&mut self.next_completion_id);
 5175
 5176        if let Some(buffer) = buffer {
 5177            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5178                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5179            ));
 5180        }
 5181    }
 5182
 5183    pub fn insert_snippet(
 5184        &mut self,
 5185        insertion_ranges: &[Range<usize>],
 5186        snippet: Snippet,
 5187        cx: &mut ViewContext<Self>,
 5188    ) -> Result<()> {
 5189        struct Tabstop<T> {
 5190            is_end_tabstop: bool,
 5191            ranges: Vec<Range<T>>,
 5192            choices: Option<Vec<String>>,
 5193        }
 5194
 5195        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5196            let snippet_text: Arc<str> = snippet.text.clone().into();
 5197            buffer.edit(
 5198                insertion_ranges
 5199                    .iter()
 5200                    .cloned()
 5201                    .map(|range| (range, snippet_text.clone())),
 5202                Some(AutoindentMode::EachLine),
 5203                cx,
 5204            );
 5205
 5206            let snapshot = &*buffer.read(cx);
 5207            let snippet = &snippet;
 5208            snippet
 5209                .tabstops
 5210                .iter()
 5211                .map(|tabstop| {
 5212                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5213                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5214                    });
 5215                    let mut tabstop_ranges = tabstop
 5216                        .ranges
 5217                        .iter()
 5218                        .flat_map(|tabstop_range| {
 5219                            let mut delta = 0_isize;
 5220                            insertion_ranges.iter().map(move |insertion_range| {
 5221                                let insertion_start = insertion_range.start as isize + delta;
 5222                                delta +=
 5223                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5224
 5225                                let start = ((insertion_start + tabstop_range.start) as usize)
 5226                                    .min(snapshot.len());
 5227                                let end = ((insertion_start + tabstop_range.end) as usize)
 5228                                    .min(snapshot.len());
 5229                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5230                            })
 5231                        })
 5232                        .collect::<Vec<_>>();
 5233                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5234
 5235                    Tabstop {
 5236                        is_end_tabstop,
 5237                        ranges: tabstop_ranges,
 5238                        choices: tabstop.choices.clone(),
 5239                    }
 5240                })
 5241                .collect::<Vec<_>>()
 5242        });
 5243        if let Some(tabstop) = tabstops.first() {
 5244            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5245                s.select_ranges(tabstop.ranges.iter().cloned());
 5246            });
 5247
 5248            if let Some(choices) = &tabstop.choices {
 5249                if let Some(selection) = tabstop.ranges.first() {
 5250                    self.show_snippet_choices(choices, selection.clone(), cx)
 5251                }
 5252            }
 5253
 5254            // If we're already at the last tabstop and it's at the end of the snippet,
 5255            // we're done, we don't need to keep the state around.
 5256            if !tabstop.is_end_tabstop {
 5257                let choices = tabstops
 5258                    .iter()
 5259                    .map(|tabstop| tabstop.choices.clone())
 5260                    .collect();
 5261
 5262                let ranges = tabstops
 5263                    .into_iter()
 5264                    .map(|tabstop| tabstop.ranges)
 5265                    .collect::<Vec<_>>();
 5266
 5267                self.snippet_stack.push(SnippetState {
 5268                    active_index: 0,
 5269                    ranges,
 5270                    choices,
 5271                });
 5272            }
 5273
 5274            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5275            if self.autoclose_regions.is_empty() {
 5276                let snapshot = self.buffer.read(cx).snapshot(cx);
 5277                for selection in &mut self.selections.all::<Point>(cx) {
 5278                    let selection_head = selection.head();
 5279                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5280                        continue;
 5281                    };
 5282
 5283                    let mut bracket_pair = None;
 5284                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5285                    let prev_chars = snapshot
 5286                        .reversed_chars_at(selection_head)
 5287                        .collect::<String>();
 5288                    for (pair, enabled) in scope.brackets() {
 5289                        if enabled
 5290                            && pair.close
 5291                            && prev_chars.starts_with(pair.start.as_str())
 5292                            && next_chars.starts_with(pair.end.as_str())
 5293                        {
 5294                            bracket_pair = Some(pair.clone());
 5295                            break;
 5296                        }
 5297                    }
 5298                    if let Some(pair) = bracket_pair {
 5299                        let start = snapshot.anchor_after(selection_head);
 5300                        let end = snapshot.anchor_after(selection_head);
 5301                        self.autoclose_regions.push(AutocloseRegion {
 5302                            selection_id: selection.id,
 5303                            range: start..end,
 5304                            pair,
 5305                        });
 5306                    }
 5307                }
 5308            }
 5309        }
 5310        Ok(())
 5311    }
 5312
 5313    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5314        self.move_to_snippet_tabstop(Bias::Right, cx)
 5315    }
 5316
 5317    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5318        self.move_to_snippet_tabstop(Bias::Left, cx)
 5319    }
 5320
 5321    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5322        if let Some(mut snippet) = self.snippet_stack.pop() {
 5323            match bias {
 5324                Bias::Left => {
 5325                    if snippet.active_index > 0 {
 5326                        snippet.active_index -= 1;
 5327                    } else {
 5328                        self.snippet_stack.push(snippet);
 5329                        return false;
 5330                    }
 5331                }
 5332                Bias::Right => {
 5333                    if snippet.active_index + 1 < snippet.ranges.len() {
 5334                        snippet.active_index += 1;
 5335                    } else {
 5336                        self.snippet_stack.push(snippet);
 5337                        return false;
 5338                    }
 5339                }
 5340            }
 5341            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5342                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5343                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5344                });
 5345
 5346                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5347                    if let Some(selection) = current_ranges.first() {
 5348                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5349                    }
 5350                }
 5351
 5352                // If snippet state is not at the last tabstop, push it back on the stack
 5353                if snippet.active_index + 1 < snippet.ranges.len() {
 5354                    self.snippet_stack.push(snippet);
 5355                }
 5356                return true;
 5357            }
 5358        }
 5359
 5360        false
 5361    }
 5362
 5363    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5364        self.transact(cx, |this, cx| {
 5365            this.select_all(&SelectAll, cx);
 5366            this.insert("", cx);
 5367        });
 5368    }
 5369
 5370    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5371        self.transact(cx, |this, cx| {
 5372            this.select_autoclose_pair(cx);
 5373            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5374            if !this.linked_edit_ranges.is_empty() {
 5375                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5376                let snapshot = this.buffer.read(cx).snapshot(cx);
 5377
 5378                for selection in selections.iter() {
 5379                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5380                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5381                    if selection_start.buffer_id != selection_end.buffer_id {
 5382                        continue;
 5383                    }
 5384                    if let Some(ranges) =
 5385                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5386                    {
 5387                        for (buffer, entries) in ranges {
 5388                            linked_ranges.entry(buffer).or_default().extend(entries);
 5389                        }
 5390                    }
 5391                }
 5392            }
 5393
 5394            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5395            if !this.selections.line_mode {
 5396                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5397                for selection in &mut selections {
 5398                    if selection.is_empty() {
 5399                        let old_head = selection.head();
 5400                        let mut new_head =
 5401                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5402                                .to_point(&display_map);
 5403                        if let Some((buffer, line_buffer_range)) = display_map
 5404                            .buffer_snapshot
 5405                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5406                        {
 5407                            let indent_size =
 5408                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5409                            let indent_len = match indent_size.kind {
 5410                                IndentKind::Space => {
 5411                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5412                                }
 5413                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5414                            };
 5415                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5416                                let indent_len = indent_len.get();
 5417                                new_head = cmp::min(
 5418                                    new_head,
 5419                                    MultiBufferPoint::new(
 5420                                        old_head.row,
 5421                                        ((old_head.column - 1) / indent_len) * indent_len,
 5422                                    ),
 5423                                );
 5424                            }
 5425                        }
 5426
 5427                        selection.set_head(new_head, SelectionGoal::None);
 5428                    }
 5429                }
 5430            }
 5431
 5432            this.signature_help_state.set_backspace_pressed(true);
 5433            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5434            this.insert("", cx);
 5435            let empty_str: Arc<str> = Arc::from("");
 5436            for (buffer, edits) in linked_ranges {
 5437                let snapshot = buffer.read(cx).snapshot();
 5438                use text::ToPoint as TP;
 5439
 5440                let edits = edits
 5441                    .into_iter()
 5442                    .map(|range| {
 5443                        let end_point = TP::to_point(&range.end, &snapshot);
 5444                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5445
 5446                        if end_point == start_point {
 5447                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5448                                .saturating_sub(1);
 5449                            start_point =
 5450                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5451                        };
 5452
 5453                        (start_point..end_point, empty_str.clone())
 5454                    })
 5455                    .sorted_by_key(|(range, _)| range.start)
 5456                    .collect::<Vec<_>>();
 5457                buffer.update(cx, |this, cx| {
 5458                    this.edit(edits, None, cx);
 5459                })
 5460            }
 5461            this.refresh_inline_completion(true, false, cx);
 5462            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5463        });
 5464    }
 5465
 5466    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5467        self.transact(cx, |this, cx| {
 5468            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5469                let line_mode = s.line_mode;
 5470                s.move_with(|map, selection| {
 5471                    if selection.is_empty() && !line_mode {
 5472                        let cursor = movement::right(map, selection.head());
 5473                        selection.end = cursor;
 5474                        selection.reversed = true;
 5475                        selection.goal = SelectionGoal::None;
 5476                    }
 5477                })
 5478            });
 5479            this.insert("", cx);
 5480            this.refresh_inline_completion(true, false, cx);
 5481        });
 5482    }
 5483
 5484    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5485        if self.move_to_prev_snippet_tabstop(cx) {
 5486            return;
 5487        }
 5488
 5489        self.outdent(&Outdent, cx);
 5490    }
 5491
 5492    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5493        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5494            return;
 5495        }
 5496
 5497        let mut selections = self.selections.all_adjusted(cx);
 5498        let buffer = self.buffer.read(cx);
 5499        let snapshot = buffer.snapshot(cx);
 5500        let rows_iter = selections.iter().map(|s| s.head().row);
 5501        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5502
 5503        let mut edits = Vec::new();
 5504        let mut prev_edited_row = 0;
 5505        let mut row_delta = 0;
 5506        for selection in &mut selections {
 5507            if selection.start.row != prev_edited_row {
 5508                row_delta = 0;
 5509            }
 5510            prev_edited_row = selection.end.row;
 5511
 5512            // If the selection is non-empty, then increase the indentation of the selected lines.
 5513            if !selection.is_empty() {
 5514                row_delta =
 5515                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5516                continue;
 5517            }
 5518
 5519            // If the selection is empty and the cursor is in the leading whitespace before the
 5520            // suggested indentation, then auto-indent the line.
 5521            let cursor = selection.head();
 5522            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5523            if let Some(suggested_indent) =
 5524                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5525            {
 5526                if cursor.column < suggested_indent.len
 5527                    && cursor.column <= current_indent.len
 5528                    && current_indent.len <= suggested_indent.len
 5529                {
 5530                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5531                    selection.end = selection.start;
 5532                    if row_delta == 0 {
 5533                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5534                            cursor.row,
 5535                            current_indent,
 5536                            suggested_indent,
 5537                        ));
 5538                        row_delta = suggested_indent.len - current_indent.len;
 5539                    }
 5540                    continue;
 5541                }
 5542            }
 5543
 5544            // Otherwise, insert a hard or soft tab.
 5545            let settings = buffer.settings_at(cursor, cx);
 5546            let tab_size = if settings.hard_tabs {
 5547                IndentSize::tab()
 5548            } else {
 5549                let tab_size = settings.tab_size.get();
 5550                let char_column = snapshot
 5551                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5552                    .flat_map(str::chars)
 5553                    .count()
 5554                    + row_delta as usize;
 5555                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5556                IndentSize::spaces(chars_to_next_tab_stop)
 5557            };
 5558            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5559            selection.end = selection.start;
 5560            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5561            row_delta += tab_size.len;
 5562        }
 5563
 5564        self.transact(cx, |this, cx| {
 5565            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5566            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5567            this.refresh_inline_completion(true, false, cx);
 5568        });
 5569    }
 5570
 5571    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5572        if self.read_only(cx) {
 5573            return;
 5574        }
 5575        let mut selections = self.selections.all::<Point>(cx);
 5576        let mut prev_edited_row = 0;
 5577        let mut row_delta = 0;
 5578        let mut edits = Vec::new();
 5579        let buffer = self.buffer.read(cx);
 5580        let snapshot = buffer.snapshot(cx);
 5581        for selection in &mut selections {
 5582            if selection.start.row != prev_edited_row {
 5583                row_delta = 0;
 5584            }
 5585            prev_edited_row = selection.end.row;
 5586
 5587            row_delta =
 5588                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5589        }
 5590
 5591        self.transact(cx, |this, cx| {
 5592            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5593            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5594        });
 5595    }
 5596
 5597    fn indent_selection(
 5598        buffer: &MultiBuffer,
 5599        snapshot: &MultiBufferSnapshot,
 5600        selection: &mut Selection<Point>,
 5601        edits: &mut Vec<(Range<Point>, String)>,
 5602        delta_for_start_row: u32,
 5603        cx: &AppContext,
 5604    ) -> u32 {
 5605        let settings = buffer.settings_at(selection.start, cx);
 5606        let tab_size = settings.tab_size.get();
 5607        let indent_kind = if settings.hard_tabs {
 5608            IndentKind::Tab
 5609        } else {
 5610            IndentKind::Space
 5611        };
 5612        let mut start_row = selection.start.row;
 5613        let mut end_row = selection.end.row + 1;
 5614
 5615        // If a selection ends at the beginning of a line, don't indent
 5616        // that last line.
 5617        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5618            end_row -= 1;
 5619        }
 5620
 5621        // Avoid re-indenting a row that has already been indented by a
 5622        // previous selection, but still update this selection's column
 5623        // to reflect that indentation.
 5624        if delta_for_start_row > 0 {
 5625            start_row += 1;
 5626            selection.start.column += delta_for_start_row;
 5627            if selection.end.row == selection.start.row {
 5628                selection.end.column += delta_for_start_row;
 5629            }
 5630        }
 5631
 5632        let mut delta_for_end_row = 0;
 5633        let has_multiple_rows = start_row + 1 != end_row;
 5634        for row in start_row..end_row {
 5635            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5636            let indent_delta = match (current_indent.kind, indent_kind) {
 5637                (IndentKind::Space, IndentKind::Space) => {
 5638                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5639                    IndentSize::spaces(columns_to_next_tab_stop)
 5640                }
 5641                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5642                (_, IndentKind::Tab) => IndentSize::tab(),
 5643            };
 5644
 5645            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5646                0
 5647            } else {
 5648                selection.start.column
 5649            };
 5650            let row_start = Point::new(row, start);
 5651            edits.push((
 5652                row_start..row_start,
 5653                indent_delta.chars().collect::<String>(),
 5654            ));
 5655
 5656            // Update this selection's endpoints to reflect the indentation.
 5657            if row == selection.start.row {
 5658                selection.start.column += indent_delta.len;
 5659            }
 5660            if row == selection.end.row {
 5661                selection.end.column += indent_delta.len;
 5662                delta_for_end_row = indent_delta.len;
 5663            }
 5664        }
 5665
 5666        if selection.start.row == selection.end.row {
 5667            delta_for_start_row + delta_for_end_row
 5668        } else {
 5669            delta_for_end_row
 5670        }
 5671    }
 5672
 5673    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5674        if self.read_only(cx) {
 5675            return;
 5676        }
 5677        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5678        let selections = self.selections.all::<Point>(cx);
 5679        let mut deletion_ranges = Vec::new();
 5680        let mut last_outdent = None;
 5681        {
 5682            let buffer = self.buffer.read(cx);
 5683            let snapshot = buffer.snapshot(cx);
 5684            for selection in &selections {
 5685                let settings = buffer.settings_at(selection.start, cx);
 5686                let tab_size = settings.tab_size.get();
 5687                let mut rows = selection.spanned_rows(false, &display_map);
 5688
 5689                // Avoid re-outdenting a row that has already been outdented by a
 5690                // previous selection.
 5691                if let Some(last_row) = last_outdent {
 5692                    if last_row == rows.start {
 5693                        rows.start = rows.start.next_row();
 5694                    }
 5695                }
 5696                let has_multiple_rows = rows.len() > 1;
 5697                for row in rows.iter_rows() {
 5698                    let indent_size = snapshot.indent_size_for_line(row);
 5699                    if indent_size.len > 0 {
 5700                        let deletion_len = match indent_size.kind {
 5701                            IndentKind::Space => {
 5702                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5703                                if columns_to_prev_tab_stop == 0 {
 5704                                    tab_size
 5705                                } else {
 5706                                    columns_to_prev_tab_stop
 5707                                }
 5708                            }
 5709                            IndentKind::Tab => 1,
 5710                        };
 5711                        let start = if has_multiple_rows
 5712                            || deletion_len > selection.start.column
 5713                            || indent_size.len < selection.start.column
 5714                        {
 5715                            0
 5716                        } else {
 5717                            selection.start.column - deletion_len
 5718                        };
 5719                        deletion_ranges.push(
 5720                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5721                        );
 5722                        last_outdent = Some(row);
 5723                    }
 5724                }
 5725            }
 5726        }
 5727
 5728        self.transact(cx, |this, cx| {
 5729            this.buffer.update(cx, |buffer, cx| {
 5730                let empty_str: Arc<str> = Arc::default();
 5731                buffer.edit(
 5732                    deletion_ranges
 5733                        .into_iter()
 5734                        .map(|range| (range, empty_str.clone())),
 5735                    None,
 5736                    cx,
 5737                );
 5738            });
 5739            let selections = this.selections.all::<usize>(cx);
 5740            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5741        });
 5742    }
 5743
 5744    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5745        if self.read_only(cx) {
 5746            return;
 5747        }
 5748        let selections = self
 5749            .selections
 5750            .all::<usize>(cx)
 5751            .into_iter()
 5752            .map(|s| s.range());
 5753
 5754        self.transact(cx, |this, cx| {
 5755            this.buffer.update(cx, |buffer, cx| {
 5756                buffer.autoindent_ranges(selections, cx);
 5757            });
 5758            let selections = this.selections.all::<usize>(cx);
 5759            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5760        });
 5761    }
 5762
 5763    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5764        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5765        let selections = self.selections.all::<Point>(cx);
 5766
 5767        let mut new_cursors = Vec::new();
 5768        let mut edit_ranges = Vec::new();
 5769        let mut selections = selections.iter().peekable();
 5770        while let Some(selection) = selections.next() {
 5771            let mut rows = selection.spanned_rows(false, &display_map);
 5772            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5773
 5774            // Accumulate contiguous regions of rows that we want to delete.
 5775            while let Some(next_selection) = selections.peek() {
 5776                let next_rows = next_selection.spanned_rows(false, &display_map);
 5777                if next_rows.start <= rows.end {
 5778                    rows.end = next_rows.end;
 5779                    selections.next().unwrap();
 5780                } else {
 5781                    break;
 5782                }
 5783            }
 5784
 5785            let buffer = &display_map.buffer_snapshot;
 5786            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5787            let edit_end;
 5788            let cursor_buffer_row;
 5789            if buffer.max_point().row >= rows.end.0 {
 5790                // If there's a line after the range, delete the \n from the end of the row range
 5791                // and position the cursor on the next line.
 5792                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5793                cursor_buffer_row = rows.end;
 5794            } else {
 5795                // If there isn't a line after the range, delete the \n from the line before the
 5796                // start of the row range and position the cursor there.
 5797                edit_start = edit_start.saturating_sub(1);
 5798                edit_end = buffer.len();
 5799                cursor_buffer_row = rows.start.previous_row();
 5800            }
 5801
 5802            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5803            *cursor.column_mut() =
 5804                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5805
 5806            new_cursors.push((
 5807                selection.id,
 5808                buffer.anchor_after(cursor.to_point(&display_map)),
 5809            ));
 5810            edit_ranges.push(edit_start..edit_end);
 5811        }
 5812
 5813        self.transact(cx, |this, cx| {
 5814            let buffer = this.buffer.update(cx, |buffer, cx| {
 5815                let empty_str: Arc<str> = Arc::default();
 5816                buffer.edit(
 5817                    edit_ranges
 5818                        .into_iter()
 5819                        .map(|range| (range, empty_str.clone())),
 5820                    None,
 5821                    cx,
 5822                );
 5823                buffer.snapshot(cx)
 5824            });
 5825            let new_selections = new_cursors
 5826                .into_iter()
 5827                .map(|(id, cursor)| {
 5828                    let cursor = cursor.to_point(&buffer);
 5829                    Selection {
 5830                        id,
 5831                        start: cursor,
 5832                        end: cursor,
 5833                        reversed: false,
 5834                        goal: SelectionGoal::None,
 5835                    }
 5836                })
 5837                .collect();
 5838
 5839            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5840                s.select(new_selections);
 5841            });
 5842        });
 5843    }
 5844
 5845    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5846        if self.read_only(cx) {
 5847            return;
 5848        }
 5849        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5850        for selection in self.selections.all::<Point>(cx) {
 5851            let start = MultiBufferRow(selection.start.row);
 5852            // Treat single line selections as if they include the next line. Otherwise this action
 5853            // would do nothing for single line selections individual cursors.
 5854            let end = if selection.start.row == selection.end.row {
 5855                MultiBufferRow(selection.start.row + 1)
 5856            } else {
 5857                MultiBufferRow(selection.end.row)
 5858            };
 5859
 5860            if let Some(last_row_range) = row_ranges.last_mut() {
 5861                if start <= last_row_range.end {
 5862                    last_row_range.end = end;
 5863                    continue;
 5864                }
 5865            }
 5866            row_ranges.push(start..end);
 5867        }
 5868
 5869        let snapshot = self.buffer.read(cx).snapshot(cx);
 5870        let mut cursor_positions = Vec::new();
 5871        for row_range in &row_ranges {
 5872            let anchor = snapshot.anchor_before(Point::new(
 5873                row_range.end.previous_row().0,
 5874                snapshot.line_len(row_range.end.previous_row()),
 5875            ));
 5876            cursor_positions.push(anchor..anchor);
 5877        }
 5878
 5879        self.transact(cx, |this, cx| {
 5880            for row_range in row_ranges.into_iter().rev() {
 5881                for row in row_range.iter_rows().rev() {
 5882                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5883                    let next_line_row = row.next_row();
 5884                    let indent = snapshot.indent_size_for_line(next_line_row);
 5885                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5886
 5887                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5888                        " "
 5889                    } else {
 5890                        ""
 5891                    };
 5892
 5893                    this.buffer.update(cx, |buffer, cx| {
 5894                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5895                    });
 5896                }
 5897            }
 5898
 5899            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5900                s.select_anchor_ranges(cursor_positions)
 5901            });
 5902        });
 5903    }
 5904
 5905    pub fn sort_lines_case_sensitive(
 5906        &mut self,
 5907        _: &SortLinesCaseSensitive,
 5908        cx: &mut ViewContext<Self>,
 5909    ) {
 5910        self.manipulate_lines(cx, |lines| lines.sort())
 5911    }
 5912
 5913    pub fn sort_lines_case_insensitive(
 5914        &mut self,
 5915        _: &SortLinesCaseInsensitive,
 5916        cx: &mut ViewContext<Self>,
 5917    ) {
 5918        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5919    }
 5920
 5921    pub fn unique_lines_case_insensitive(
 5922        &mut self,
 5923        _: &UniqueLinesCaseInsensitive,
 5924        cx: &mut ViewContext<Self>,
 5925    ) {
 5926        self.manipulate_lines(cx, |lines| {
 5927            let mut seen = HashSet::default();
 5928            lines.retain(|line| seen.insert(line.to_lowercase()));
 5929        })
 5930    }
 5931
 5932    pub fn unique_lines_case_sensitive(
 5933        &mut self,
 5934        _: &UniqueLinesCaseSensitive,
 5935        cx: &mut ViewContext<Self>,
 5936    ) {
 5937        self.manipulate_lines(cx, |lines| {
 5938            let mut seen = HashSet::default();
 5939            lines.retain(|line| seen.insert(*line));
 5940        })
 5941    }
 5942
 5943    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 5944        let mut revert_changes = HashMap::default();
 5945        let snapshot = self.snapshot(cx);
 5946        for hunk in hunks_for_ranges(
 5947            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 5948            &snapshot,
 5949        ) {
 5950            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5951        }
 5952        if !revert_changes.is_empty() {
 5953            self.transact(cx, |editor, cx| {
 5954                editor.revert(revert_changes, cx);
 5955            });
 5956        }
 5957    }
 5958
 5959    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 5960        let Some(project) = self.project.clone() else {
 5961            return;
 5962        };
 5963        self.reload(project, cx).detach_and_notify_err(cx);
 5964    }
 5965
 5966    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5967        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 5968        if !revert_changes.is_empty() {
 5969            self.transact(cx, |editor, cx| {
 5970                editor.revert(revert_changes, cx);
 5971            });
 5972        }
 5973    }
 5974
 5975    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 5976        let snapshot = self.buffer.read(cx).read(cx);
 5977        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 5978            drop(snapshot);
 5979            let mut revert_changes = HashMap::default();
 5980            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5981            if !revert_changes.is_empty() {
 5982                self.revert(revert_changes, cx)
 5983            }
 5984        }
 5985    }
 5986
 5987    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5988        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5989            let project_path = buffer.read(cx).project_path(cx)?;
 5990            let project = self.project.as_ref()?.read(cx);
 5991            let entry = project.entry_for_path(&project_path, cx)?;
 5992            let parent = match &entry.canonical_path {
 5993                Some(canonical_path) => canonical_path.to_path_buf(),
 5994                None => project.absolute_path(&project_path, cx)?,
 5995            }
 5996            .parent()?
 5997            .to_path_buf();
 5998            Some(parent)
 5999        }) {
 6000            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6001        }
 6002    }
 6003
 6004    fn gather_revert_changes(
 6005        &mut self,
 6006        selections: &[Selection<Point>],
 6007        cx: &mut ViewContext<'_, Editor>,
 6008    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6009        let mut revert_changes = HashMap::default();
 6010        let snapshot = self.snapshot(cx);
 6011        for hunk in hunks_for_selections(&snapshot, selections) {
 6012            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6013        }
 6014        revert_changes
 6015    }
 6016
 6017    pub fn prepare_revert_change(
 6018        &mut self,
 6019        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6020        hunk: &MultiBufferDiffHunk,
 6021        cx: &AppContext,
 6022    ) -> Option<()> {
 6023        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6024        let buffer = buffer.read(cx);
 6025        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6026        let original_text = change_set
 6027            .read(cx)
 6028            .base_text
 6029            .as_ref()?
 6030            .read(cx)
 6031            .as_rope()
 6032            .slice(hunk.diff_base_byte_range.clone());
 6033        let buffer_snapshot = buffer.snapshot();
 6034        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6035        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6036            probe
 6037                .0
 6038                .start
 6039                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6040                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6041        }) {
 6042            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6043            Some(())
 6044        } else {
 6045            None
 6046        }
 6047    }
 6048
 6049    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6050        self.manipulate_lines(cx, |lines| lines.reverse())
 6051    }
 6052
 6053    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6054        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6055    }
 6056
 6057    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6058    where
 6059        Fn: FnMut(&mut Vec<&str>),
 6060    {
 6061        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6062        let buffer = self.buffer.read(cx).snapshot(cx);
 6063
 6064        let mut edits = Vec::new();
 6065
 6066        let selections = self.selections.all::<Point>(cx);
 6067        let mut selections = selections.iter().peekable();
 6068        let mut contiguous_row_selections = Vec::new();
 6069        let mut new_selections = Vec::new();
 6070        let mut added_lines = 0;
 6071        let mut removed_lines = 0;
 6072
 6073        while let Some(selection) = selections.next() {
 6074            let (start_row, end_row) = consume_contiguous_rows(
 6075                &mut contiguous_row_selections,
 6076                selection,
 6077                &display_map,
 6078                &mut selections,
 6079            );
 6080
 6081            let start_point = Point::new(start_row.0, 0);
 6082            let end_point = Point::new(
 6083                end_row.previous_row().0,
 6084                buffer.line_len(end_row.previous_row()),
 6085            );
 6086            let text = buffer
 6087                .text_for_range(start_point..end_point)
 6088                .collect::<String>();
 6089
 6090            let mut lines = text.split('\n').collect_vec();
 6091
 6092            let lines_before = lines.len();
 6093            callback(&mut lines);
 6094            let lines_after = lines.len();
 6095
 6096            edits.push((start_point..end_point, lines.join("\n")));
 6097
 6098            // Selections must change based on added and removed line count
 6099            let start_row =
 6100                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6101            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6102            new_selections.push(Selection {
 6103                id: selection.id,
 6104                start: start_row,
 6105                end: end_row,
 6106                goal: SelectionGoal::None,
 6107                reversed: selection.reversed,
 6108            });
 6109
 6110            if lines_after > lines_before {
 6111                added_lines += lines_after - lines_before;
 6112            } else if lines_before > lines_after {
 6113                removed_lines += lines_before - lines_after;
 6114            }
 6115        }
 6116
 6117        self.transact(cx, |this, cx| {
 6118            let buffer = this.buffer.update(cx, |buffer, cx| {
 6119                buffer.edit(edits, None, cx);
 6120                buffer.snapshot(cx)
 6121            });
 6122
 6123            // Recalculate offsets on newly edited buffer
 6124            let new_selections = new_selections
 6125                .iter()
 6126                .map(|s| {
 6127                    let start_point = Point::new(s.start.0, 0);
 6128                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6129                    Selection {
 6130                        id: s.id,
 6131                        start: buffer.point_to_offset(start_point),
 6132                        end: buffer.point_to_offset(end_point),
 6133                        goal: s.goal,
 6134                        reversed: s.reversed,
 6135                    }
 6136                })
 6137                .collect();
 6138
 6139            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6140                s.select(new_selections);
 6141            });
 6142
 6143            this.request_autoscroll(Autoscroll::fit(), cx);
 6144        });
 6145    }
 6146
 6147    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6148        self.manipulate_text(cx, |text| text.to_uppercase())
 6149    }
 6150
 6151    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6152        self.manipulate_text(cx, |text| text.to_lowercase())
 6153    }
 6154
 6155    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6156        self.manipulate_text(cx, |text| {
 6157            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6158            // https://github.com/rutrum/convert-case/issues/16
 6159            text.split('\n')
 6160                .map(|line| line.to_case(Case::Title))
 6161                .join("\n")
 6162        })
 6163    }
 6164
 6165    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6166        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6167    }
 6168
 6169    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6170        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6171    }
 6172
 6173    pub fn convert_to_upper_camel_case(
 6174        &mut self,
 6175        _: &ConvertToUpperCamelCase,
 6176        cx: &mut ViewContext<Self>,
 6177    ) {
 6178        self.manipulate_text(cx, |text| {
 6179            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6180            // https://github.com/rutrum/convert-case/issues/16
 6181            text.split('\n')
 6182                .map(|line| line.to_case(Case::UpperCamel))
 6183                .join("\n")
 6184        })
 6185    }
 6186
 6187    pub fn convert_to_lower_camel_case(
 6188        &mut self,
 6189        _: &ConvertToLowerCamelCase,
 6190        cx: &mut ViewContext<Self>,
 6191    ) {
 6192        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6193    }
 6194
 6195    pub fn convert_to_opposite_case(
 6196        &mut self,
 6197        _: &ConvertToOppositeCase,
 6198        cx: &mut ViewContext<Self>,
 6199    ) {
 6200        self.manipulate_text(cx, |text| {
 6201            text.chars()
 6202                .fold(String::with_capacity(text.len()), |mut t, c| {
 6203                    if c.is_uppercase() {
 6204                        t.extend(c.to_lowercase());
 6205                    } else {
 6206                        t.extend(c.to_uppercase());
 6207                    }
 6208                    t
 6209                })
 6210        })
 6211    }
 6212
 6213    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6214    where
 6215        Fn: FnMut(&str) -> String,
 6216    {
 6217        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6218        let buffer = self.buffer.read(cx).snapshot(cx);
 6219
 6220        let mut new_selections = Vec::new();
 6221        let mut edits = Vec::new();
 6222        let mut selection_adjustment = 0i32;
 6223
 6224        for selection in self.selections.all::<usize>(cx) {
 6225            let selection_is_empty = selection.is_empty();
 6226
 6227            let (start, end) = if selection_is_empty {
 6228                let word_range = movement::surrounding_word(
 6229                    &display_map,
 6230                    selection.start.to_display_point(&display_map),
 6231                );
 6232                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6233                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6234                (start, end)
 6235            } else {
 6236                (selection.start, selection.end)
 6237            };
 6238
 6239            let text = buffer.text_for_range(start..end).collect::<String>();
 6240            let old_length = text.len() as i32;
 6241            let text = callback(&text);
 6242
 6243            new_selections.push(Selection {
 6244                start: (start as i32 - selection_adjustment) as usize,
 6245                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6246                goal: SelectionGoal::None,
 6247                ..selection
 6248            });
 6249
 6250            selection_adjustment += old_length - text.len() as i32;
 6251
 6252            edits.push((start..end, text));
 6253        }
 6254
 6255        self.transact(cx, |this, cx| {
 6256            this.buffer.update(cx, |buffer, cx| {
 6257                buffer.edit(edits, None, cx);
 6258            });
 6259
 6260            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6261                s.select(new_selections);
 6262            });
 6263
 6264            this.request_autoscroll(Autoscroll::fit(), cx);
 6265        });
 6266    }
 6267
 6268    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6269        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6270        let buffer = &display_map.buffer_snapshot;
 6271        let selections = self.selections.all::<Point>(cx);
 6272
 6273        let mut edits = Vec::new();
 6274        let mut selections_iter = selections.iter().peekable();
 6275        while let Some(selection) = selections_iter.next() {
 6276            let mut rows = selection.spanned_rows(false, &display_map);
 6277            // duplicate line-wise
 6278            if whole_lines || selection.start == selection.end {
 6279                // Avoid duplicating the same lines twice.
 6280                while let Some(next_selection) = selections_iter.peek() {
 6281                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6282                    if next_rows.start < rows.end {
 6283                        rows.end = next_rows.end;
 6284                        selections_iter.next().unwrap();
 6285                    } else {
 6286                        break;
 6287                    }
 6288                }
 6289
 6290                // Copy the text from the selected row region and splice it either at the start
 6291                // or end of the region.
 6292                let start = Point::new(rows.start.0, 0);
 6293                let end = Point::new(
 6294                    rows.end.previous_row().0,
 6295                    buffer.line_len(rows.end.previous_row()),
 6296                );
 6297                let text = buffer
 6298                    .text_for_range(start..end)
 6299                    .chain(Some("\n"))
 6300                    .collect::<String>();
 6301                let insert_location = if upwards {
 6302                    Point::new(rows.end.0, 0)
 6303                } else {
 6304                    start
 6305                };
 6306                edits.push((insert_location..insert_location, text));
 6307            } else {
 6308                // duplicate character-wise
 6309                let start = selection.start;
 6310                let end = selection.end;
 6311                let text = buffer.text_for_range(start..end).collect::<String>();
 6312                edits.push((selection.end..selection.end, text));
 6313            }
 6314        }
 6315
 6316        self.transact(cx, |this, cx| {
 6317            this.buffer.update(cx, |buffer, cx| {
 6318                buffer.edit(edits, None, cx);
 6319            });
 6320
 6321            this.request_autoscroll(Autoscroll::fit(), cx);
 6322        });
 6323    }
 6324
 6325    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6326        self.duplicate(true, true, cx);
 6327    }
 6328
 6329    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6330        self.duplicate(false, true, cx);
 6331    }
 6332
 6333    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6334        self.duplicate(false, false, cx);
 6335    }
 6336
 6337    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6338        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6339        let buffer = self.buffer.read(cx).snapshot(cx);
 6340
 6341        let mut edits = Vec::new();
 6342        let mut unfold_ranges = Vec::new();
 6343        let mut refold_creases = Vec::new();
 6344
 6345        let selections = self.selections.all::<Point>(cx);
 6346        let mut selections = selections.iter().peekable();
 6347        let mut contiguous_row_selections = Vec::new();
 6348        let mut new_selections = Vec::new();
 6349
 6350        while let Some(selection) = selections.next() {
 6351            // Find all the selections that span a contiguous row range
 6352            let (start_row, end_row) = consume_contiguous_rows(
 6353                &mut contiguous_row_selections,
 6354                selection,
 6355                &display_map,
 6356                &mut selections,
 6357            );
 6358
 6359            // Move the text spanned by the row range to be before the line preceding the row range
 6360            if start_row.0 > 0 {
 6361                let range_to_move = Point::new(
 6362                    start_row.previous_row().0,
 6363                    buffer.line_len(start_row.previous_row()),
 6364                )
 6365                    ..Point::new(
 6366                        end_row.previous_row().0,
 6367                        buffer.line_len(end_row.previous_row()),
 6368                    );
 6369                let insertion_point = display_map
 6370                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6371                    .0;
 6372
 6373                // Don't move lines across excerpts
 6374                if buffer
 6375                    .excerpt_boundaries_in_range((
 6376                        Bound::Excluded(insertion_point),
 6377                        Bound::Included(range_to_move.end),
 6378                    ))
 6379                    .next()
 6380                    .is_none()
 6381                {
 6382                    let text = buffer
 6383                        .text_for_range(range_to_move.clone())
 6384                        .flat_map(|s| s.chars())
 6385                        .skip(1)
 6386                        .chain(['\n'])
 6387                        .collect::<String>();
 6388
 6389                    edits.push((
 6390                        buffer.anchor_after(range_to_move.start)
 6391                            ..buffer.anchor_before(range_to_move.end),
 6392                        String::new(),
 6393                    ));
 6394                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6395                    edits.push((insertion_anchor..insertion_anchor, text));
 6396
 6397                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6398
 6399                    // Move selections up
 6400                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6401                        |mut selection| {
 6402                            selection.start.row -= row_delta;
 6403                            selection.end.row -= row_delta;
 6404                            selection
 6405                        },
 6406                    ));
 6407
 6408                    // Move folds up
 6409                    unfold_ranges.push(range_to_move.clone());
 6410                    for fold in display_map.folds_in_range(
 6411                        buffer.anchor_before(range_to_move.start)
 6412                            ..buffer.anchor_after(range_to_move.end),
 6413                    ) {
 6414                        let mut start = fold.range.start.to_point(&buffer);
 6415                        let mut end = fold.range.end.to_point(&buffer);
 6416                        start.row -= row_delta;
 6417                        end.row -= row_delta;
 6418                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6419                    }
 6420                }
 6421            }
 6422
 6423            // If we didn't move line(s), preserve the existing selections
 6424            new_selections.append(&mut contiguous_row_selections);
 6425        }
 6426
 6427        self.transact(cx, |this, cx| {
 6428            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6429            this.buffer.update(cx, |buffer, cx| {
 6430                for (range, text) in edits {
 6431                    buffer.edit([(range, text)], None, cx);
 6432                }
 6433            });
 6434            this.fold_creases(refold_creases, true, cx);
 6435            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6436                s.select(new_selections);
 6437            })
 6438        });
 6439    }
 6440
 6441    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6442        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6443        let buffer = self.buffer.read(cx).snapshot(cx);
 6444
 6445        let mut edits = Vec::new();
 6446        let mut unfold_ranges = Vec::new();
 6447        let mut refold_creases = Vec::new();
 6448
 6449        let selections = self.selections.all::<Point>(cx);
 6450        let mut selections = selections.iter().peekable();
 6451        let mut contiguous_row_selections = Vec::new();
 6452        let mut new_selections = Vec::new();
 6453
 6454        while let Some(selection) = selections.next() {
 6455            // Find all the selections that span a contiguous row range
 6456            let (start_row, end_row) = consume_contiguous_rows(
 6457                &mut contiguous_row_selections,
 6458                selection,
 6459                &display_map,
 6460                &mut selections,
 6461            );
 6462
 6463            // Move the text spanned by the row range to be after the last line of the row range
 6464            if end_row.0 <= buffer.max_point().row {
 6465                let range_to_move =
 6466                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6467                let insertion_point = display_map
 6468                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6469                    .0;
 6470
 6471                // Don't move lines across excerpt boundaries
 6472                if buffer
 6473                    .excerpt_boundaries_in_range((
 6474                        Bound::Excluded(range_to_move.start),
 6475                        Bound::Included(insertion_point),
 6476                    ))
 6477                    .next()
 6478                    .is_none()
 6479                {
 6480                    let mut text = String::from("\n");
 6481                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6482                    text.pop(); // Drop trailing newline
 6483                    edits.push((
 6484                        buffer.anchor_after(range_to_move.start)
 6485                            ..buffer.anchor_before(range_to_move.end),
 6486                        String::new(),
 6487                    ));
 6488                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6489                    edits.push((insertion_anchor..insertion_anchor, text));
 6490
 6491                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6492
 6493                    // Move selections down
 6494                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6495                        |mut selection| {
 6496                            selection.start.row += row_delta;
 6497                            selection.end.row += row_delta;
 6498                            selection
 6499                        },
 6500                    ));
 6501
 6502                    // Move folds down
 6503                    unfold_ranges.push(range_to_move.clone());
 6504                    for fold in display_map.folds_in_range(
 6505                        buffer.anchor_before(range_to_move.start)
 6506                            ..buffer.anchor_after(range_to_move.end),
 6507                    ) {
 6508                        let mut start = fold.range.start.to_point(&buffer);
 6509                        let mut end = fold.range.end.to_point(&buffer);
 6510                        start.row += row_delta;
 6511                        end.row += row_delta;
 6512                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6513                    }
 6514                }
 6515            }
 6516
 6517            // If we didn't move line(s), preserve the existing selections
 6518            new_selections.append(&mut contiguous_row_selections);
 6519        }
 6520
 6521        self.transact(cx, |this, cx| {
 6522            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6523            this.buffer.update(cx, |buffer, cx| {
 6524                for (range, text) in edits {
 6525                    buffer.edit([(range, text)], None, cx);
 6526                }
 6527            });
 6528            this.fold_creases(refold_creases, true, cx);
 6529            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6530        });
 6531    }
 6532
 6533    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6534        let text_layout_details = &self.text_layout_details(cx);
 6535        self.transact(cx, |this, cx| {
 6536            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6537                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6538                let line_mode = s.line_mode;
 6539                s.move_with(|display_map, selection| {
 6540                    if !selection.is_empty() || line_mode {
 6541                        return;
 6542                    }
 6543
 6544                    let mut head = selection.head();
 6545                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6546                    if head.column() == display_map.line_len(head.row()) {
 6547                        transpose_offset = display_map
 6548                            .buffer_snapshot
 6549                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6550                    }
 6551
 6552                    if transpose_offset == 0 {
 6553                        return;
 6554                    }
 6555
 6556                    *head.column_mut() += 1;
 6557                    head = display_map.clip_point(head, Bias::Right);
 6558                    let goal = SelectionGoal::HorizontalPosition(
 6559                        display_map
 6560                            .x_for_display_point(head, text_layout_details)
 6561                            .into(),
 6562                    );
 6563                    selection.collapse_to(head, goal);
 6564
 6565                    let transpose_start = display_map
 6566                        .buffer_snapshot
 6567                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6568                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6569                        let transpose_end = display_map
 6570                            .buffer_snapshot
 6571                            .clip_offset(transpose_offset + 1, Bias::Right);
 6572                        if let Some(ch) =
 6573                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6574                        {
 6575                            edits.push((transpose_start..transpose_offset, String::new()));
 6576                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6577                        }
 6578                    }
 6579                });
 6580                edits
 6581            });
 6582            this.buffer
 6583                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6584            let selections = this.selections.all::<usize>(cx);
 6585            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6586                s.select(selections);
 6587            });
 6588        });
 6589    }
 6590
 6591    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6592        self.rewrap_impl(IsVimMode::No, cx)
 6593    }
 6594
 6595    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6596        let buffer = self.buffer.read(cx).snapshot(cx);
 6597        let selections = self.selections.all::<Point>(cx);
 6598        let mut selections = selections.iter().peekable();
 6599
 6600        let mut edits = Vec::new();
 6601        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6602
 6603        while let Some(selection) = selections.next() {
 6604            let mut start_row = selection.start.row;
 6605            let mut end_row = selection.end.row;
 6606
 6607            // Skip selections that overlap with a range that has already been rewrapped.
 6608            let selection_range = start_row..end_row;
 6609            if rewrapped_row_ranges
 6610                .iter()
 6611                .any(|range| range.overlaps(&selection_range))
 6612            {
 6613                continue;
 6614            }
 6615
 6616            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6617
 6618            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6619                match language_scope.language_name().0.as_ref() {
 6620                    "Markdown" | "Plain Text" => {
 6621                        should_rewrap = true;
 6622                    }
 6623                    _ => {}
 6624                }
 6625            }
 6626
 6627            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6628
 6629            // Since not all lines in the selection may be at the same indent
 6630            // level, choose the indent size that is the most common between all
 6631            // of the lines.
 6632            //
 6633            // If there is a tie, we use the deepest indent.
 6634            let (indent_size, indent_end) = {
 6635                let mut indent_size_occurrences = HashMap::default();
 6636                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6637
 6638                for row in start_row..=end_row {
 6639                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6640                    rows_by_indent_size.entry(indent).or_default().push(row);
 6641                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6642                }
 6643
 6644                let indent_size = indent_size_occurrences
 6645                    .into_iter()
 6646                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6647                    .map(|(indent, _)| indent)
 6648                    .unwrap_or_default();
 6649                let row = rows_by_indent_size[&indent_size][0];
 6650                let indent_end = Point::new(row, indent_size.len);
 6651
 6652                (indent_size, indent_end)
 6653            };
 6654
 6655            let mut line_prefix = indent_size.chars().collect::<String>();
 6656
 6657            if let Some(comment_prefix) =
 6658                buffer
 6659                    .language_scope_at(selection.head())
 6660                    .and_then(|language| {
 6661                        language
 6662                            .line_comment_prefixes()
 6663                            .iter()
 6664                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6665                            .cloned()
 6666                    })
 6667            {
 6668                line_prefix.push_str(&comment_prefix);
 6669                should_rewrap = true;
 6670            }
 6671
 6672            if !should_rewrap {
 6673                continue;
 6674            }
 6675
 6676            if selection.is_empty() {
 6677                'expand_upwards: while start_row > 0 {
 6678                    let prev_row = start_row - 1;
 6679                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6680                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6681                    {
 6682                        start_row = prev_row;
 6683                    } else {
 6684                        break 'expand_upwards;
 6685                    }
 6686                }
 6687
 6688                'expand_downwards: while end_row < buffer.max_point().row {
 6689                    let next_row = end_row + 1;
 6690                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6691                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6692                    {
 6693                        end_row = next_row;
 6694                    } else {
 6695                        break 'expand_downwards;
 6696                    }
 6697                }
 6698            }
 6699
 6700            let start = Point::new(start_row, 0);
 6701            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6702            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6703            let Some(lines_without_prefixes) = selection_text
 6704                .lines()
 6705                .map(|line| {
 6706                    line.strip_prefix(&line_prefix)
 6707                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6708                        .ok_or_else(|| {
 6709                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6710                        })
 6711                })
 6712                .collect::<Result<Vec<_>, _>>()
 6713                .log_err()
 6714            else {
 6715                continue;
 6716            };
 6717
 6718            let wrap_column = buffer
 6719                .settings_at(Point::new(start_row, 0), cx)
 6720                .preferred_line_length as usize;
 6721            let wrapped_text = wrap_with_prefix(
 6722                line_prefix,
 6723                lines_without_prefixes.join(" "),
 6724                wrap_column,
 6725                tab_size,
 6726            );
 6727
 6728            // TODO: should always use char-based diff while still supporting cursor behavior that
 6729            // matches vim.
 6730            let diff = match is_vim_mode {
 6731                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6732                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6733            };
 6734            let mut offset = start.to_offset(&buffer);
 6735            let mut moved_since_edit = true;
 6736
 6737            for change in diff.iter_all_changes() {
 6738                let value = change.value();
 6739                match change.tag() {
 6740                    ChangeTag::Equal => {
 6741                        offset += value.len();
 6742                        moved_since_edit = true;
 6743                    }
 6744                    ChangeTag::Delete => {
 6745                        let start = buffer.anchor_after(offset);
 6746                        let end = buffer.anchor_before(offset + value.len());
 6747
 6748                        if moved_since_edit {
 6749                            edits.push((start..end, String::new()));
 6750                        } else {
 6751                            edits.last_mut().unwrap().0.end = end;
 6752                        }
 6753
 6754                        offset += value.len();
 6755                        moved_since_edit = false;
 6756                    }
 6757                    ChangeTag::Insert => {
 6758                        if moved_since_edit {
 6759                            let anchor = buffer.anchor_after(offset);
 6760                            edits.push((anchor..anchor, value.to_string()));
 6761                        } else {
 6762                            edits.last_mut().unwrap().1.push_str(value);
 6763                        }
 6764
 6765                        moved_since_edit = false;
 6766                    }
 6767                }
 6768            }
 6769
 6770            rewrapped_row_ranges.push(start_row..=end_row);
 6771        }
 6772
 6773        self.buffer
 6774            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6775    }
 6776
 6777    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6778        let mut text = String::new();
 6779        let buffer = self.buffer.read(cx).snapshot(cx);
 6780        let mut selections = self.selections.all::<Point>(cx);
 6781        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6782        {
 6783            let max_point = buffer.max_point();
 6784            let mut is_first = true;
 6785            for selection in &mut selections {
 6786                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6787                if is_entire_line {
 6788                    selection.start = Point::new(selection.start.row, 0);
 6789                    if !selection.is_empty() && selection.end.column == 0 {
 6790                        selection.end = cmp::min(max_point, selection.end);
 6791                    } else {
 6792                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6793                    }
 6794                    selection.goal = SelectionGoal::None;
 6795                }
 6796                if is_first {
 6797                    is_first = false;
 6798                } else {
 6799                    text += "\n";
 6800                }
 6801                let mut len = 0;
 6802                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6803                    text.push_str(chunk);
 6804                    len += chunk.len();
 6805                }
 6806                clipboard_selections.push(ClipboardSelection {
 6807                    len,
 6808                    is_entire_line,
 6809                    first_line_indent: buffer
 6810                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6811                        .len,
 6812                });
 6813            }
 6814        }
 6815
 6816        self.transact(cx, |this, cx| {
 6817            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6818                s.select(selections);
 6819            });
 6820            this.insert("", cx);
 6821        });
 6822        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6823    }
 6824
 6825    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6826        let item = self.cut_common(cx);
 6827        cx.write_to_clipboard(item);
 6828    }
 6829
 6830    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6831        self.change_selections(None, cx, |s| {
 6832            s.move_with(|snapshot, sel| {
 6833                if sel.is_empty() {
 6834                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6835                }
 6836            });
 6837        });
 6838        let item = self.cut_common(cx);
 6839        cx.set_global(KillRing(item))
 6840    }
 6841
 6842    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6843        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6844            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6845                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6846            } else {
 6847                return;
 6848            }
 6849        } else {
 6850            return;
 6851        };
 6852        self.do_paste(&text, metadata, false, cx);
 6853    }
 6854
 6855    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6856        let selections = self.selections.all::<Point>(cx);
 6857        let buffer = self.buffer.read(cx).read(cx);
 6858        let mut text = String::new();
 6859
 6860        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6861        {
 6862            let max_point = buffer.max_point();
 6863            let mut is_first = true;
 6864            for selection in selections.iter() {
 6865                let mut start = selection.start;
 6866                let mut end = selection.end;
 6867                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6868                if is_entire_line {
 6869                    start = Point::new(start.row, 0);
 6870                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6871                }
 6872                if is_first {
 6873                    is_first = false;
 6874                } else {
 6875                    text += "\n";
 6876                }
 6877                let mut len = 0;
 6878                for chunk in buffer.text_for_range(start..end) {
 6879                    text.push_str(chunk);
 6880                    len += chunk.len();
 6881                }
 6882                clipboard_selections.push(ClipboardSelection {
 6883                    len,
 6884                    is_entire_line,
 6885                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6886                });
 6887            }
 6888        }
 6889
 6890        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6891            text,
 6892            clipboard_selections,
 6893        ));
 6894    }
 6895
 6896    pub fn do_paste(
 6897        &mut self,
 6898        text: &String,
 6899        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6900        handle_entire_lines: bool,
 6901        cx: &mut ViewContext<Self>,
 6902    ) {
 6903        if self.read_only(cx) {
 6904            return;
 6905        }
 6906
 6907        let clipboard_text = Cow::Borrowed(text);
 6908
 6909        self.transact(cx, |this, cx| {
 6910            if let Some(mut clipboard_selections) = clipboard_selections {
 6911                let old_selections = this.selections.all::<usize>(cx);
 6912                let all_selections_were_entire_line =
 6913                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6914                let first_selection_indent_column =
 6915                    clipboard_selections.first().map(|s| s.first_line_indent);
 6916                if clipboard_selections.len() != old_selections.len() {
 6917                    clipboard_selections.drain(..);
 6918                }
 6919                let cursor_offset = this.selections.last::<usize>(cx).head();
 6920                let mut auto_indent_on_paste = true;
 6921
 6922                this.buffer.update(cx, |buffer, cx| {
 6923                    let snapshot = buffer.read(cx);
 6924                    auto_indent_on_paste =
 6925                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6926
 6927                    let mut start_offset = 0;
 6928                    let mut edits = Vec::new();
 6929                    let mut original_indent_columns = Vec::new();
 6930                    for (ix, selection) in old_selections.iter().enumerate() {
 6931                        let to_insert;
 6932                        let entire_line;
 6933                        let original_indent_column;
 6934                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6935                            let end_offset = start_offset + clipboard_selection.len;
 6936                            to_insert = &clipboard_text[start_offset..end_offset];
 6937                            entire_line = clipboard_selection.is_entire_line;
 6938                            start_offset = end_offset + 1;
 6939                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6940                        } else {
 6941                            to_insert = clipboard_text.as_str();
 6942                            entire_line = all_selections_were_entire_line;
 6943                            original_indent_column = first_selection_indent_column
 6944                        }
 6945
 6946                        // If the corresponding selection was empty when this slice of the
 6947                        // clipboard text was written, then the entire line containing the
 6948                        // selection was copied. If this selection is also currently empty,
 6949                        // then paste the line before the current line of the buffer.
 6950                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6951                            let column = selection.start.to_point(&snapshot).column as usize;
 6952                            let line_start = selection.start - column;
 6953                            line_start..line_start
 6954                        } else {
 6955                            selection.range()
 6956                        };
 6957
 6958                        edits.push((range, to_insert));
 6959                        original_indent_columns.extend(original_indent_column);
 6960                    }
 6961                    drop(snapshot);
 6962
 6963                    buffer.edit(
 6964                        edits,
 6965                        if auto_indent_on_paste {
 6966                            Some(AutoindentMode::Block {
 6967                                original_indent_columns,
 6968                            })
 6969                        } else {
 6970                            None
 6971                        },
 6972                        cx,
 6973                    );
 6974                });
 6975
 6976                let selections = this.selections.all::<usize>(cx);
 6977                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6978            } else {
 6979                this.insert(&clipboard_text, cx);
 6980            }
 6981        });
 6982    }
 6983
 6984    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6985        if let Some(item) = cx.read_from_clipboard() {
 6986            let entries = item.entries();
 6987
 6988            match entries.first() {
 6989                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 6990                // of all the pasted entries.
 6991                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 6992                    .do_paste(
 6993                        clipboard_string.text(),
 6994                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 6995                        true,
 6996                        cx,
 6997                    ),
 6998                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 6999            }
 7000        }
 7001    }
 7002
 7003    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7004        if self.read_only(cx) {
 7005            return;
 7006        }
 7007
 7008        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7009            if let Some((selections, _)) =
 7010                self.selection_history.transaction(transaction_id).cloned()
 7011            {
 7012                self.change_selections(None, cx, |s| {
 7013                    s.select_anchors(selections.to_vec());
 7014                });
 7015            }
 7016            self.request_autoscroll(Autoscroll::fit(), cx);
 7017            self.unmark_text(cx);
 7018            self.refresh_inline_completion(true, false, cx);
 7019            cx.emit(EditorEvent::Edited { transaction_id });
 7020            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7021        }
 7022    }
 7023
 7024    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7025        if self.read_only(cx) {
 7026            return;
 7027        }
 7028
 7029        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7030            if let Some((_, Some(selections))) =
 7031                self.selection_history.transaction(transaction_id).cloned()
 7032            {
 7033                self.change_selections(None, cx, |s| {
 7034                    s.select_anchors(selections.to_vec());
 7035                });
 7036            }
 7037            self.request_autoscroll(Autoscroll::fit(), cx);
 7038            self.unmark_text(cx);
 7039            self.refresh_inline_completion(true, false, cx);
 7040            cx.emit(EditorEvent::Edited { transaction_id });
 7041        }
 7042    }
 7043
 7044    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7045        self.buffer
 7046            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7047    }
 7048
 7049    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7050        self.buffer
 7051            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7052    }
 7053
 7054    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7055        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7056            let line_mode = s.line_mode;
 7057            s.move_with(|map, selection| {
 7058                let cursor = if selection.is_empty() && !line_mode {
 7059                    movement::left(map, selection.start)
 7060                } else {
 7061                    selection.start
 7062                };
 7063                selection.collapse_to(cursor, SelectionGoal::None);
 7064            });
 7065        })
 7066    }
 7067
 7068    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7069        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7070            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7071        })
 7072    }
 7073
 7074    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7075        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7076            let line_mode = s.line_mode;
 7077            s.move_with(|map, selection| {
 7078                let cursor = if selection.is_empty() && !line_mode {
 7079                    movement::right(map, selection.end)
 7080                } else {
 7081                    selection.end
 7082                };
 7083                selection.collapse_to(cursor, SelectionGoal::None)
 7084            });
 7085        })
 7086    }
 7087
 7088    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7089        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7090            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7091        })
 7092    }
 7093
 7094    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7095        if self.take_rename(true, cx).is_some() {
 7096            return;
 7097        }
 7098
 7099        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7100            cx.propagate();
 7101            return;
 7102        }
 7103
 7104        let text_layout_details = &self.text_layout_details(cx);
 7105        let selection_count = self.selections.count();
 7106        let first_selection = self.selections.first_anchor();
 7107
 7108        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7109            let line_mode = s.line_mode;
 7110            s.move_with(|map, selection| {
 7111                if !selection.is_empty() && !line_mode {
 7112                    selection.goal = SelectionGoal::None;
 7113                }
 7114                let (cursor, goal) = movement::up(
 7115                    map,
 7116                    selection.start,
 7117                    selection.goal,
 7118                    false,
 7119                    text_layout_details,
 7120                );
 7121                selection.collapse_to(cursor, goal);
 7122            });
 7123        });
 7124
 7125        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7126        {
 7127            cx.propagate();
 7128        }
 7129    }
 7130
 7131    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7132        if self.take_rename(true, cx).is_some() {
 7133            return;
 7134        }
 7135
 7136        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7137            cx.propagate();
 7138            return;
 7139        }
 7140
 7141        let text_layout_details = &self.text_layout_details(cx);
 7142
 7143        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7144            let line_mode = s.line_mode;
 7145            s.move_with(|map, selection| {
 7146                if !selection.is_empty() && !line_mode {
 7147                    selection.goal = SelectionGoal::None;
 7148                }
 7149                let (cursor, goal) = movement::up_by_rows(
 7150                    map,
 7151                    selection.start,
 7152                    action.lines,
 7153                    selection.goal,
 7154                    false,
 7155                    text_layout_details,
 7156                );
 7157                selection.collapse_to(cursor, goal);
 7158            });
 7159        })
 7160    }
 7161
 7162    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7163        if self.take_rename(true, cx).is_some() {
 7164            return;
 7165        }
 7166
 7167        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7168            cx.propagate();
 7169            return;
 7170        }
 7171
 7172        let text_layout_details = &self.text_layout_details(cx);
 7173
 7174        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7175            let line_mode = s.line_mode;
 7176            s.move_with(|map, selection| {
 7177                if !selection.is_empty() && !line_mode {
 7178                    selection.goal = SelectionGoal::None;
 7179                }
 7180                let (cursor, goal) = movement::down_by_rows(
 7181                    map,
 7182                    selection.start,
 7183                    action.lines,
 7184                    selection.goal,
 7185                    false,
 7186                    text_layout_details,
 7187                );
 7188                selection.collapse_to(cursor, goal);
 7189            });
 7190        })
 7191    }
 7192
 7193    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7194        let text_layout_details = &self.text_layout_details(cx);
 7195        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7196            s.move_heads_with(|map, head, goal| {
 7197                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7198            })
 7199        })
 7200    }
 7201
 7202    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7203        let text_layout_details = &self.text_layout_details(cx);
 7204        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7205            s.move_heads_with(|map, head, goal| {
 7206                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7207            })
 7208        })
 7209    }
 7210
 7211    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7212        let Some(row_count) = self.visible_row_count() else {
 7213            return;
 7214        };
 7215
 7216        let text_layout_details = &self.text_layout_details(cx);
 7217
 7218        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7219            s.move_heads_with(|map, head, goal| {
 7220                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7221            })
 7222        })
 7223    }
 7224
 7225    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7226        if self.take_rename(true, cx).is_some() {
 7227            return;
 7228        }
 7229
 7230        if self
 7231            .context_menu
 7232            .borrow_mut()
 7233            .as_mut()
 7234            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7235            .unwrap_or(false)
 7236        {
 7237            return;
 7238        }
 7239
 7240        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7241            cx.propagate();
 7242            return;
 7243        }
 7244
 7245        let Some(row_count) = self.visible_row_count() else {
 7246            return;
 7247        };
 7248
 7249        let autoscroll = if action.center_cursor {
 7250            Autoscroll::center()
 7251        } else {
 7252            Autoscroll::fit()
 7253        };
 7254
 7255        let text_layout_details = &self.text_layout_details(cx);
 7256
 7257        self.change_selections(Some(autoscroll), cx, |s| {
 7258            let line_mode = s.line_mode;
 7259            s.move_with(|map, selection| {
 7260                if !selection.is_empty() && !line_mode {
 7261                    selection.goal = SelectionGoal::None;
 7262                }
 7263                let (cursor, goal) = movement::up_by_rows(
 7264                    map,
 7265                    selection.end,
 7266                    row_count,
 7267                    selection.goal,
 7268                    false,
 7269                    text_layout_details,
 7270                );
 7271                selection.collapse_to(cursor, goal);
 7272            });
 7273        });
 7274    }
 7275
 7276    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7277        let text_layout_details = &self.text_layout_details(cx);
 7278        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7279            s.move_heads_with(|map, head, goal| {
 7280                movement::up(map, head, goal, false, text_layout_details)
 7281            })
 7282        })
 7283    }
 7284
 7285    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7286        self.take_rename(true, cx);
 7287
 7288        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7289            cx.propagate();
 7290            return;
 7291        }
 7292
 7293        let text_layout_details = &self.text_layout_details(cx);
 7294        let selection_count = self.selections.count();
 7295        let first_selection = self.selections.first_anchor();
 7296
 7297        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7298            let line_mode = s.line_mode;
 7299            s.move_with(|map, selection| {
 7300                if !selection.is_empty() && !line_mode {
 7301                    selection.goal = SelectionGoal::None;
 7302                }
 7303                let (cursor, goal) = movement::down(
 7304                    map,
 7305                    selection.end,
 7306                    selection.goal,
 7307                    false,
 7308                    text_layout_details,
 7309                );
 7310                selection.collapse_to(cursor, goal);
 7311            });
 7312        });
 7313
 7314        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7315        {
 7316            cx.propagate();
 7317        }
 7318    }
 7319
 7320    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7321        let Some(row_count) = self.visible_row_count() else {
 7322            return;
 7323        };
 7324
 7325        let text_layout_details = &self.text_layout_details(cx);
 7326
 7327        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7328            s.move_heads_with(|map, head, goal| {
 7329                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7330            })
 7331        })
 7332    }
 7333
 7334    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7335        if self.take_rename(true, cx).is_some() {
 7336            return;
 7337        }
 7338
 7339        if self
 7340            .context_menu
 7341            .borrow_mut()
 7342            .as_mut()
 7343            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7344            .unwrap_or(false)
 7345        {
 7346            return;
 7347        }
 7348
 7349        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7350            cx.propagate();
 7351            return;
 7352        }
 7353
 7354        let Some(row_count) = self.visible_row_count() else {
 7355            return;
 7356        };
 7357
 7358        let autoscroll = if action.center_cursor {
 7359            Autoscroll::center()
 7360        } else {
 7361            Autoscroll::fit()
 7362        };
 7363
 7364        let text_layout_details = &self.text_layout_details(cx);
 7365        self.change_selections(Some(autoscroll), cx, |s| {
 7366            let line_mode = s.line_mode;
 7367            s.move_with(|map, selection| {
 7368                if !selection.is_empty() && !line_mode {
 7369                    selection.goal = SelectionGoal::None;
 7370                }
 7371                let (cursor, goal) = movement::down_by_rows(
 7372                    map,
 7373                    selection.end,
 7374                    row_count,
 7375                    selection.goal,
 7376                    false,
 7377                    text_layout_details,
 7378                );
 7379                selection.collapse_to(cursor, goal);
 7380            });
 7381        });
 7382    }
 7383
 7384    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7385        let text_layout_details = &self.text_layout_details(cx);
 7386        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7387            s.move_heads_with(|map, head, goal| {
 7388                movement::down(map, head, goal, false, text_layout_details)
 7389            })
 7390        });
 7391    }
 7392
 7393    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7394        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7395            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7396        }
 7397    }
 7398
 7399    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7400        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7401            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7402        }
 7403    }
 7404
 7405    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7406        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7407            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7408        }
 7409    }
 7410
 7411    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7412        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7413            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7414        }
 7415    }
 7416
 7417    pub fn move_to_previous_word_start(
 7418        &mut self,
 7419        _: &MoveToPreviousWordStart,
 7420        cx: &mut ViewContext<Self>,
 7421    ) {
 7422        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7423            s.move_cursors_with(|map, head, _| {
 7424                (
 7425                    movement::previous_word_start(map, head),
 7426                    SelectionGoal::None,
 7427                )
 7428            });
 7429        })
 7430    }
 7431
 7432    pub fn move_to_previous_subword_start(
 7433        &mut self,
 7434        _: &MoveToPreviousSubwordStart,
 7435        cx: &mut ViewContext<Self>,
 7436    ) {
 7437        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7438            s.move_cursors_with(|map, head, _| {
 7439                (
 7440                    movement::previous_subword_start(map, head),
 7441                    SelectionGoal::None,
 7442                )
 7443            });
 7444        })
 7445    }
 7446
 7447    pub fn select_to_previous_word_start(
 7448        &mut self,
 7449        _: &SelectToPreviousWordStart,
 7450        cx: &mut ViewContext<Self>,
 7451    ) {
 7452        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7453            s.move_heads_with(|map, head, _| {
 7454                (
 7455                    movement::previous_word_start(map, head),
 7456                    SelectionGoal::None,
 7457                )
 7458            });
 7459        })
 7460    }
 7461
 7462    pub fn select_to_previous_subword_start(
 7463        &mut self,
 7464        _: &SelectToPreviousSubwordStart,
 7465        cx: &mut ViewContext<Self>,
 7466    ) {
 7467        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7468            s.move_heads_with(|map, head, _| {
 7469                (
 7470                    movement::previous_subword_start(map, head),
 7471                    SelectionGoal::None,
 7472                )
 7473            });
 7474        })
 7475    }
 7476
 7477    pub fn delete_to_previous_word_start(
 7478        &mut self,
 7479        action: &DeleteToPreviousWordStart,
 7480        cx: &mut ViewContext<Self>,
 7481    ) {
 7482        self.transact(cx, |this, cx| {
 7483            this.select_autoclose_pair(cx);
 7484            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7485                let line_mode = s.line_mode;
 7486                s.move_with(|map, selection| {
 7487                    if selection.is_empty() && !line_mode {
 7488                        let cursor = if action.ignore_newlines {
 7489                            movement::previous_word_start(map, selection.head())
 7490                        } else {
 7491                            movement::previous_word_start_or_newline(map, selection.head())
 7492                        };
 7493                        selection.set_head(cursor, SelectionGoal::None);
 7494                    }
 7495                });
 7496            });
 7497            this.insert("", cx);
 7498        });
 7499    }
 7500
 7501    pub fn delete_to_previous_subword_start(
 7502        &mut self,
 7503        _: &DeleteToPreviousSubwordStart,
 7504        cx: &mut ViewContext<Self>,
 7505    ) {
 7506        self.transact(cx, |this, cx| {
 7507            this.select_autoclose_pair(cx);
 7508            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7509                let line_mode = s.line_mode;
 7510                s.move_with(|map, selection| {
 7511                    if selection.is_empty() && !line_mode {
 7512                        let cursor = movement::previous_subword_start(map, selection.head());
 7513                        selection.set_head(cursor, SelectionGoal::None);
 7514                    }
 7515                });
 7516            });
 7517            this.insert("", cx);
 7518        });
 7519    }
 7520
 7521    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7522        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7523            s.move_cursors_with(|map, head, _| {
 7524                (movement::next_word_end(map, head), SelectionGoal::None)
 7525            });
 7526        })
 7527    }
 7528
 7529    pub fn move_to_next_subword_end(
 7530        &mut self,
 7531        _: &MoveToNextSubwordEnd,
 7532        cx: &mut ViewContext<Self>,
 7533    ) {
 7534        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7535            s.move_cursors_with(|map, head, _| {
 7536                (movement::next_subword_end(map, head), SelectionGoal::None)
 7537            });
 7538        })
 7539    }
 7540
 7541    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7542        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7543            s.move_heads_with(|map, head, _| {
 7544                (movement::next_word_end(map, head), SelectionGoal::None)
 7545            });
 7546        })
 7547    }
 7548
 7549    pub fn select_to_next_subword_end(
 7550        &mut self,
 7551        _: &SelectToNextSubwordEnd,
 7552        cx: &mut ViewContext<Self>,
 7553    ) {
 7554        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7555            s.move_heads_with(|map, head, _| {
 7556                (movement::next_subword_end(map, head), SelectionGoal::None)
 7557            });
 7558        })
 7559    }
 7560
 7561    pub fn delete_to_next_word_end(
 7562        &mut self,
 7563        action: &DeleteToNextWordEnd,
 7564        cx: &mut ViewContext<Self>,
 7565    ) {
 7566        self.transact(cx, |this, 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 = if action.ignore_newlines {
 7572                            movement::next_word_end(map, selection.head())
 7573                        } else {
 7574                            movement::next_word_end_or_newline(map, selection.head())
 7575                        };
 7576                        selection.set_head(cursor, SelectionGoal::None);
 7577                    }
 7578                });
 7579            });
 7580            this.insert("", cx);
 7581        });
 7582    }
 7583
 7584    pub fn delete_to_next_subword_end(
 7585        &mut self,
 7586        _: &DeleteToNextSubwordEnd,
 7587        cx: &mut ViewContext<Self>,
 7588    ) {
 7589        self.transact(cx, |this, cx| {
 7590            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7591                s.move_with(|map, selection| {
 7592                    if selection.is_empty() {
 7593                        let cursor = movement::next_subword_end(map, selection.head());
 7594                        selection.set_head(cursor, SelectionGoal::None);
 7595                    }
 7596                });
 7597            });
 7598            this.insert("", cx);
 7599        });
 7600    }
 7601
 7602    pub fn move_to_beginning_of_line(
 7603        &mut self,
 7604        action: &MoveToBeginningOfLine,
 7605        cx: &mut ViewContext<Self>,
 7606    ) {
 7607        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7608            s.move_cursors_with(|map, head, _| {
 7609                (
 7610                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7611                    SelectionGoal::None,
 7612                )
 7613            });
 7614        })
 7615    }
 7616
 7617    pub fn select_to_beginning_of_line(
 7618        &mut self,
 7619        action: &SelectToBeginningOfLine,
 7620        cx: &mut ViewContext<Self>,
 7621    ) {
 7622        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7623            s.move_heads_with(|map, head, _| {
 7624                (
 7625                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7626                    SelectionGoal::None,
 7627                )
 7628            });
 7629        });
 7630    }
 7631
 7632    pub fn delete_to_beginning_of_line(
 7633        &mut self,
 7634        _: &DeleteToBeginningOfLine,
 7635        cx: &mut ViewContext<Self>,
 7636    ) {
 7637        self.transact(cx, |this, cx| {
 7638            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7639                s.move_with(|_, selection| {
 7640                    selection.reversed = true;
 7641                });
 7642            });
 7643
 7644            this.select_to_beginning_of_line(
 7645                &SelectToBeginningOfLine {
 7646                    stop_at_soft_wraps: false,
 7647                },
 7648                cx,
 7649            );
 7650            this.backspace(&Backspace, cx);
 7651        });
 7652    }
 7653
 7654    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7655        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7656            s.move_cursors_with(|map, head, _| {
 7657                (
 7658                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7659                    SelectionGoal::None,
 7660                )
 7661            });
 7662        })
 7663    }
 7664
 7665    pub fn select_to_end_of_line(
 7666        &mut self,
 7667        action: &SelectToEndOfLine,
 7668        cx: &mut ViewContext<Self>,
 7669    ) {
 7670        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7671            s.move_heads_with(|map, head, _| {
 7672                (
 7673                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7674                    SelectionGoal::None,
 7675                )
 7676            });
 7677        })
 7678    }
 7679
 7680    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7681        self.transact(cx, |this, cx| {
 7682            this.select_to_end_of_line(
 7683                &SelectToEndOfLine {
 7684                    stop_at_soft_wraps: false,
 7685                },
 7686                cx,
 7687            );
 7688            this.delete(&Delete, cx);
 7689        });
 7690    }
 7691
 7692    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7693        self.transact(cx, |this, cx| {
 7694            this.select_to_end_of_line(
 7695                &SelectToEndOfLine {
 7696                    stop_at_soft_wraps: false,
 7697                },
 7698                cx,
 7699            );
 7700            this.cut(&Cut, cx);
 7701        });
 7702    }
 7703
 7704    pub fn move_to_start_of_paragraph(
 7705        &mut self,
 7706        _: &MoveToStartOfParagraph,
 7707        cx: &mut ViewContext<Self>,
 7708    ) {
 7709        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7710            cx.propagate();
 7711            return;
 7712        }
 7713
 7714        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7715            s.move_with(|map, selection| {
 7716                selection.collapse_to(
 7717                    movement::start_of_paragraph(map, selection.head(), 1),
 7718                    SelectionGoal::None,
 7719                )
 7720            });
 7721        })
 7722    }
 7723
 7724    pub fn move_to_end_of_paragraph(
 7725        &mut self,
 7726        _: &MoveToEndOfParagraph,
 7727        cx: &mut ViewContext<Self>,
 7728    ) {
 7729        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7730            cx.propagate();
 7731            return;
 7732        }
 7733
 7734        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7735            s.move_with(|map, selection| {
 7736                selection.collapse_to(
 7737                    movement::end_of_paragraph(map, selection.head(), 1),
 7738                    SelectionGoal::None,
 7739                )
 7740            });
 7741        })
 7742    }
 7743
 7744    pub fn select_to_start_of_paragraph(
 7745        &mut self,
 7746        _: &SelectToStartOfParagraph,
 7747        cx: &mut ViewContext<Self>,
 7748    ) {
 7749        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7750            cx.propagate();
 7751            return;
 7752        }
 7753
 7754        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7755            s.move_heads_with(|map, head, _| {
 7756                (
 7757                    movement::start_of_paragraph(map, head, 1),
 7758                    SelectionGoal::None,
 7759                )
 7760            });
 7761        })
 7762    }
 7763
 7764    pub fn select_to_end_of_paragraph(
 7765        &mut self,
 7766        _: &SelectToEndOfParagraph,
 7767        cx: &mut ViewContext<Self>,
 7768    ) {
 7769        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7770            cx.propagate();
 7771            return;
 7772        }
 7773
 7774        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7775            s.move_heads_with(|map, head, _| {
 7776                (
 7777                    movement::end_of_paragraph(map, head, 1),
 7778                    SelectionGoal::None,
 7779                )
 7780            });
 7781        })
 7782    }
 7783
 7784    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7785        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7786            cx.propagate();
 7787            return;
 7788        }
 7789
 7790        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7791            s.select_ranges(vec![0..0]);
 7792        });
 7793    }
 7794
 7795    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7796        let mut selection = self.selections.last::<Point>(cx);
 7797        selection.set_head(Point::zero(), SelectionGoal::None);
 7798
 7799        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7800            s.select(vec![selection]);
 7801        });
 7802    }
 7803
 7804    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7805        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7806            cx.propagate();
 7807            return;
 7808        }
 7809
 7810        let cursor = self.buffer.read(cx).read(cx).len();
 7811        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7812            s.select_ranges(vec![cursor..cursor])
 7813        });
 7814    }
 7815
 7816    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7817        self.nav_history = nav_history;
 7818    }
 7819
 7820    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7821        self.nav_history.as_ref()
 7822    }
 7823
 7824    fn push_to_nav_history(
 7825        &mut self,
 7826        cursor_anchor: Anchor,
 7827        new_position: Option<Point>,
 7828        cx: &mut ViewContext<Self>,
 7829    ) {
 7830        if let Some(nav_history) = self.nav_history.as_mut() {
 7831            let buffer = self.buffer.read(cx).read(cx);
 7832            let cursor_position = cursor_anchor.to_point(&buffer);
 7833            let scroll_state = self.scroll_manager.anchor();
 7834            let scroll_top_row = scroll_state.top_row(&buffer);
 7835            drop(buffer);
 7836
 7837            if let Some(new_position) = new_position {
 7838                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7839                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7840                    return;
 7841                }
 7842            }
 7843
 7844            nav_history.push(
 7845                Some(NavigationData {
 7846                    cursor_anchor,
 7847                    cursor_position,
 7848                    scroll_anchor: scroll_state,
 7849                    scroll_top_row,
 7850                }),
 7851                cx,
 7852            );
 7853        }
 7854    }
 7855
 7856    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7857        let buffer = self.buffer.read(cx).snapshot(cx);
 7858        let mut selection = self.selections.first::<usize>(cx);
 7859        selection.set_head(buffer.len(), SelectionGoal::None);
 7860        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7861            s.select(vec![selection]);
 7862        });
 7863    }
 7864
 7865    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7866        let end = self.buffer.read(cx).read(cx).len();
 7867        self.change_selections(None, cx, |s| {
 7868            s.select_ranges(vec![0..end]);
 7869        });
 7870    }
 7871
 7872    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7873        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7874        let mut selections = self.selections.all::<Point>(cx);
 7875        let max_point = display_map.buffer_snapshot.max_point();
 7876        for selection in &mut selections {
 7877            let rows = selection.spanned_rows(true, &display_map);
 7878            selection.start = Point::new(rows.start.0, 0);
 7879            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7880            selection.reversed = false;
 7881        }
 7882        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7883            s.select(selections);
 7884        });
 7885    }
 7886
 7887    pub fn split_selection_into_lines(
 7888        &mut self,
 7889        _: &SplitSelectionIntoLines,
 7890        cx: &mut ViewContext<Self>,
 7891    ) {
 7892        let mut to_unfold = Vec::new();
 7893        let mut new_selection_ranges = Vec::new();
 7894        {
 7895            let selections = self.selections.all::<Point>(cx);
 7896            let buffer = self.buffer.read(cx).read(cx);
 7897            for selection in selections {
 7898                for row in selection.start.row..selection.end.row {
 7899                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7900                    new_selection_ranges.push(cursor..cursor);
 7901                }
 7902                new_selection_ranges.push(selection.end..selection.end);
 7903                to_unfold.push(selection.start..selection.end);
 7904            }
 7905        }
 7906        self.unfold_ranges(&to_unfold, true, true, cx);
 7907        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7908            s.select_ranges(new_selection_ranges);
 7909        });
 7910    }
 7911
 7912    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7913        self.add_selection(true, cx);
 7914    }
 7915
 7916    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7917        self.add_selection(false, cx);
 7918    }
 7919
 7920    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7921        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7922        let mut selections = self.selections.all::<Point>(cx);
 7923        let text_layout_details = self.text_layout_details(cx);
 7924        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7925            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7926            let range = oldest_selection.display_range(&display_map).sorted();
 7927
 7928            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7929            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7930            let positions = start_x.min(end_x)..start_x.max(end_x);
 7931
 7932            selections.clear();
 7933            let mut stack = Vec::new();
 7934            for row in range.start.row().0..=range.end.row().0 {
 7935                if let Some(selection) = self.selections.build_columnar_selection(
 7936                    &display_map,
 7937                    DisplayRow(row),
 7938                    &positions,
 7939                    oldest_selection.reversed,
 7940                    &text_layout_details,
 7941                ) {
 7942                    stack.push(selection.id);
 7943                    selections.push(selection);
 7944                }
 7945            }
 7946
 7947            if above {
 7948                stack.reverse();
 7949            }
 7950
 7951            AddSelectionsState { above, stack }
 7952        });
 7953
 7954        let last_added_selection = *state.stack.last().unwrap();
 7955        let mut new_selections = Vec::new();
 7956        if above == state.above {
 7957            let end_row = if above {
 7958                DisplayRow(0)
 7959            } else {
 7960                display_map.max_point().row()
 7961            };
 7962
 7963            'outer: for selection in selections {
 7964                if selection.id == last_added_selection {
 7965                    let range = selection.display_range(&display_map).sorted();
 7966                    debug_assert_eq!(range.start.row(), range.end.row());
 7967                    let mut row = range.start.row();
 7968                    let positions =
 7969                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7970                            px(start)..px(end)
 7971                        } else {
 7972                            let start_x =
 7973                                display_map.x_for_display_point(range.start, &text_layout_details);
 7974                            let end_x =
 7975                                display_map.x_for_display_point(range.end, &text_layout_details);
 7976                            start_x.min(end_x)..start_x.max(end_x)
 7977                        };
 7978
 7979                    while row != end_row {
 7980                        if above {
 7981                            row.0 -= 1;
 7982                        } else {
 7983                            row.0 += 1;
 7984                        }
 7985
 7986                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7987                            &display_map,
 7988                            row,
 7989                            &positions,
 7990                            selection.reversed,
 7991                            &text_layout_details,
 7992                        ) {
 7993                            state.stack.push(new_selection.id);
 7994                            if above {
 7995                                new_selections.push(new_selection);
 7996                                new_selections.push(selection);
 7997                            } else {
 7998                                new_selections.push(selection);
 7999                                new_selections.push(new_selection);
 8000                            }
 8001
 8002                            continue 'outer;
 8003                        }
 8004                    }
 8005                }
 8006
 8007                new_selections.push(selection);
 8008            }
 8009        } else {
 8010            new_selections = selections;
 8011            new_selections.retain(|s| s.id != last_added_selection);
 8012            state.stack.pop();
 8013        }
 8014
 8015        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8016            s.select(new_selections);
 8017        });
 8018        if state.stack.len() > 1 {
 8019            self.add_selections_state = Some(state);
 8020        }
 8021    }
 8022
 8023    pub fn select_next_match_internal(
 8024        &mut self,
 8025        display_map: &DisplaySnapshot,
 8026        replace_newest: bool,
 8027        autoscroll: Option<Autoscroll>,
 8028        cx: &mut ViewContext<Self>,
 8029    ) -> Result<()> {
 8030        fn select_next_match_ranges(
 8031            this: &mut Editor,
 8032            range: Range<usize>,
 8033            replace_newest: bool,
 8034            auto_scroll: Option<Autoscroll>,
 8035            cx: &mut ViewContext<Editor>,
 8036        ) {
 8037            this.unfold_ranges(&[range.clone()], false, true, cx);
 8038            this.change_selections(auto_scroll, cx, |s| {
 8039                if replace_newest {
 8040                    s.delete(s.newest_anchor().id);
 8041                }
 8042                s.insert_range(range.clone());
 8043            });
 8044        }
 8045
 8046        let buffer = &display_map.buffer_snapshot;
 8047        let mut selections = self.selections.all::<usize>(cx);
 8048        if let Some(mut select_next_state) = self.select_next_state.take() {
 8049            let query = &select_next_state.query;
 8050            if !select_next_state.done {
 8051                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8052                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8053                let mut next_selected_range = None;
 8054
 8055                let bytes_after_last_selection =
 8056                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8057                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8058                let query_matches = query
 8059                    .stream_find_iter(bytes_after_last_selection)
 8060                    .map(|result| (last_selection.end, result))
 8061                    .chain(
 8062                        query
 8063                            .stream_find_iter(bytes_before_first_selection)
 8064                            .map(|result| (0, result)),
 8065                    );
 8066
 8067                for (start_offset, query_match) in query_matches {
 8068                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8069                    let offset_range =
 8070                        start_offset + query_match.start()..start_offset + query_match.end();
 8071                    let display_range = offset_range.start.to_display_point(display_map)
 8072                        ..offset_range.end.to_display_point(display_map);
 8073
 8074                    if !select_next_state.wordwise
 8075                        || (!movement::is_inside_word(display_map, display_range.start)
 8076                            && !movement::is_inside_word(display_map, display_range.end))
 8077                    {
 8078                        // TODO: This is n^2, because we might check all the selections
 8079                        if !selections
 8080                            .iter()
 8081                            .any(|selection| selection.range().overlaps(&offset_range))
 8082                        {
 8083                            next_selected_range = Some(offset_range);
 8084                            break;
 8085                        }
 8086                    }
 8087                }
 8088
 8089                if let Some(next_selected_range) = next_selected_range {
 8090                    select_next_match_ranges(
 8091                        self,
 8092                        next_selected_range,
 8093                        replace_newest,
 8094                        autoscroll,
 8095                        cx,
 8096                    );
 8097                } else {
 8098                    select_next_state.done = true;
 8099                }
 8100            }
 8101
 8102            self.select_next_state = Some(select_next_state);
 8103        } else {
 8104            let mut only_carets = true;
 8105            let mut same_text_selected = true;
 8106            let mut selected_text = None;
 8107
 8108            let mut selections_iter = selections.iter().peekable();
 8109            while let Some(selection) = selections_iter.next() {
 8110                if selection.start != selection.end {
 8111                    only_carets = false;
 8112                }
 8113
 8114                if same_text_selected {
 8115                    if selected_text.is_none() {
 8116                        selected_text =
 8117                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8118                    }
 8119
 8120                    if let Some(next_selection) = selections_iter.peek() {
 8121                        if next_selection.range().len() == selection.range().len() {
 8122                            let next_selected_text = buffer
 8123                                .text_for_range(next_selection.range())
 8124                                .collect::<String>();
 8125                            if Some(next_selected_text) != selected_text {
 8126                                same_text_selected = false;
 8127                                selected_text = None;
 8128                            }
 8129                        } else {
 8130                            same_text_selected = false;
 8131                            selected_text = None;
 8132                        }
 8133                    }
 8134                }
 8135            }
 8136
 8137            if only_carets {
 8138                for selection in &mut selections {
 8139                    let word_range = movement::surrounding_word(
 8140                        display_map,
 8141                        selection.start.to_display_point(display_map),
 8142                    );
 8143                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8144                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8145                    selection.goal = SelectionGoal::None;
 8146                    selection.reversed = false;
 8147                    select_next_match_ranges(
 8148                        self,
 8149                        selection.start..selection.end,
 8150                        replace_newest,
 8151                        autoscroll,
 8152                        cx,
 8153                    );
 8154                }
 8155
 8156                if selections.len() == 1 {
 8157                    let selection = selections
 8158                        .last()
 8159                        .expect("ensured that there's only one selection");
 8160                    let query = buffer
 8161                        .text_for_range(selection.start..selection.end)
 8162                        .collect::<String>();
 8163                    let is_empty = query.is_empty();
 8164                    let select_state = SelectNextState {
 8165                        query: AhoCorasick::new(&[query])?,
 8166                        wordwise: true,
 8167                        done: is_empty,
 8168                    };
 8169                    self.select_next_state = Some(select_state);
 8170                } else {
 8171                    self.select_next_state = None;
 8172                }
 8173            } else if let Some(selected_text) = selected_text {
 8174                self.select_next_state = Some(SelectNextState {
 8175                    query: AhoCorasick::new(&[selected_text])?,
 8176                    wordwise: false,
 8177                    done: false,
 8178                });
 8179                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8180            }
 8181        }
 8182        Ok(())
 8183    }
 8184
 8185    pub fn select_all_matches(
 8186        &mut self,
 8187        _action: &SelectAllMatches,
 8188        cx: &mut ViewContext<Self>,
 8189    ) -> Result<()> {
 8190        self.push_to_selection_history();
 8191        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8192
 8193        self.select_next_match_internal(&display_map, false, None, cx)?;
 8194        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8195            return Ok(());
 8196        };
 8197        if select_next_state.done {
 8198            return Ok(());
 8199        }
 8200
 8201        let mut new_selections = self.selections.all::<usize>(cx);
 8202
 8203        let buffer = &display_map.buffer_snapshot;
 8204        let query_matches = select_next_state
 8205            .query
 8206            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8207
 8208        for query_match in query_matches {
 8209            let query_match = query_match.unwrap(); // can only fail due to I/O
 8210            let offset_range = query_match.start()..query_match.end();
 8211            let display_range = offset_range.start.to_display_point(&display_map)
 8212                ..offset_range.end.to_display_point(&display_map);
 8213
 8214            if !select_next_state.wordwise
 8215                || (!movement::is_inside_word(&display_map, display_range.start)
 8216                    && !movement::is_inside_word(&display_map, display_range.end))
 8217            {
 8218                self.selections.change_with(cx, |selections| {
 8219                    new_selections.push(Selection {
 8220                        id: selections.new_selection_id(),
 8221                        start: offset_range.start,
 8222                        end: offset_range.end,
 8223                        reversed: false,
 8224                        goal: SelectionGoal::None,
 8225                    });
 8226                });
 8227            }
 8228        }
 8229
 8230        new_selections.sort_by_key(|selection| selection.start);
 8231        let mut ix = 0;
 8232        while ix + 1 < new_selections.len() {
 8233            let current_selection = &new_selections[ix];
 8234            let next_selection = &new_selections[ix + 1];
 8235            if current_selection.range().overlaps(&next_selection.range()) {
 8236                if current_selection.id < next_selection.id {
 8237                    new_selections.remove(ix + 1);
 8238                } else {
 8239                    new_selections.remove(ix);
 8240                }
 8241            } else {
 8242                ix += 1;
 8243            }
 8244        }
 8245
 8246        select_next_state.done = true;
 8247        self.unfold_ranges(
 8248            &new_selections
 8249                .iter()
 8250                .map(|selection| selection.range())
 8251                .collect::<Vec<_>>(),
 8252            false,
 8253            false,
 8254            cx,
 8255        );
 8256        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8257            selections.select(new_selections)
 8258        });
 8259
 8260        Ok(())
 8261    }
 8262
 8263    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8264        self.push_to_selection_history();
 8265        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8266        self.select_next_match_internal(
 8267            &display_map,
 8268            action.replace_newest,
 8269            Some(Autoscroll::newest()),
 8270            cx,
 8271        )?;
 8272        Ok(())
 8273    }
 8274
 8275    pub fn select_previous(
 8276        &mut self,
 8277        action: &SelectPrevious,
 8278        cx: &mut ViewContext<Self>,
 8279    ) -> Result<()> {
 8280        self.push_to_selection_history();
 8281        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8282        let buffer = &display_map.buffer_snapshot;
 8283        let mut selections = self.selections.all::<usize>(cx);
 8284        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8285            let query = &select_prev_state.query;
 8286            if !select_prev_state.done {
 8287                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8288                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8289                let mut next_selected_range = None;
 8290                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8291                let bytes_before_last_selection =
 8292                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8293                let bytes_after_first_selection =
 8294                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8295                let query_matches = query
 8296                    .stream_find_iter(bytes_before_last_selection)
 8297                    .map(|result| (last_selection.start, result))
 8298                    .chain(
 8299                        query
 8300                            .stream_find_iter(bytes_after_first_selection)
 8301                            .map(|result| (buffer.len(), result)),
 8302                    );
 8303                for (end_offset, query_match) in query_matches {
 8304                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8305                    let offset_range =
 8306                        end_offset - query_match.end()..end_offset - query_match.start();
 8307                    let display_range = offset_range.start.to_display_point(&display_map)
 8308                        ..offset_range.end.to_display_point(&display_map);
 8309
 8310                    if !select_prev_state.wordwise
 8311                        || (!movement::is_inside_word(&display_map, display_range.start)
 8312                            && !movement::is_inside_word(&display_map, display_range.end))
 8313                    {
 8314                        next_selected_range = Some(offset_range);
 8315                        break;
 8316                    }
 8317                }
 8318
 8319                if let Some(next_selected_range) = next_selected_range {
 8320                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8321                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8322                        if action.replace_newest {
 8323                            s.delete(s.newest_anchor().id);
 8324                        }
 8325                        s.insert_range(next_selected_range);
 8326                    });
 8327                } else {
 8328                    select_prev_state.done = true;
 8329                }
 8330            }
 8331
 8332            self.select_prev_state = Some(select_prev_state);
 8333        } else {
 8334            let mut only_carets = true;
 8335            let mut same_text_selected = true;
 8336            let mut selected_text = None;
 8337
 8338            let mut selections_iter = selections.iter().peekable();
 8339            while let Some(selection) = selections_iter.next() {
 8340                if selection.start != selection.end {
 8341                    only_carets = false;
 8342                }
 8343
 8344                if same_text_selected {
 8345                    if selected_text.is_none() {
 8346                        selected_text =
 8347                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8348                    }
 8349
 8350                    if let Some(next_selection) = selections_iter.peek() {
 8351                        if next_selection.range().len() == selection.range().len() {
 8352                            let next_selected_text = buffer
 8353                                .text_for_range(next_selection.range())
 8354                                .collect::<String>();
 8355                            if Some(next_selected_text) != selected_text {
 8356                                same_text_selected = false;
 8357                                selected_text = None;
 8358                            }
 8359                        } else {
 8360                            same_text_selected = false;
 8361                            selected_text = None;
 8362                        }
 8363                    }
 8364                }
 8365            }
 8366
 8367            if only_carets {
 8368                for selection in &mut selections {
 8369                    let word_range = movement::surrounding_word(
 8370                        &display_map,
 8371                        selection.start.to_display_point(&display_map),
 8372                    );
 8373                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8374                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8375                    selection.goal = SelectionGoal::None;
 8376                    selection.reversed = false;
 8377                }
 8378                if selections.len() == 1 {
 8379                    let selection = selections
 8380                        .last()
 8381                        .expect("ensured that there's only one selection");
 8382                    let query = buffer
 8383                        .text_for_range(selection.start..selection.end)
 8384                        .collect::<String>();
 8385                    let is_empty = query.is_empty();
 8386                    let select_state = SelectNextState {
 8387                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8388                        wordwise: true,
 8389                        done: is_empty,
 8390                    };
 8391                    self.select_prev_state = Some(select_state);
 8392                } else {
 8393                    self.select_prev_state = None;
 8394                }
 8395
 8396                self.unfold_ranges(
 8397                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8398                    false,
 8399                    true,
 8400                    cx,
 8401                );
 8402                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8403                    s.select(selections);
 8404                });
 8405            } else if let Some(selected_text) = selected_text {
 8406                self.select_prev_state = Some(SelectNextState {
 8407                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8408                    wordwise: false,
 8409                    done: false,
 8410                });
 8411                self.select_previous(action, cx)?;
 8412            }
 8413        }
 8414        Ok(())
 8415    }
 8416
 8417    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8418        if self.read_only(cx) {
 8419            return;
 8420        }
 8421        let text_layout_details = &self.text_layout_details(cx);
 8422        self.transact(cx, |this, cx| {
 8423            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8424            let mut edits = Vec::new();
 8425            let mut selection_edit_ranges = Vec::new();
 8426            let mut last_toggled_row = None;
 8427            let snapshot = this.buffer.read(cx).read(cx);
 8428            let empty_str: Arc<str> = Arc::default();
 8429            let mut suffixes_inserted = Vec::new();
 8430            let ignore_indent = action.ignore_indent;
 8431
 8432            fn comment_prefix_range(
 8433                snapshot: &MultiBufferSnapshot,
 8434                row: MultiBufferRow,
 8435                comment_prefix: &str,
 8436                comment_prefix_whitespace: &str,
 8437                ignore_indent: bool,
 8438            ) -> Range<Point> {
 8439                let indent_size = if ignore_indent {
 8440                    0
 8441                } else {
 8442                    snapshot.indent_size_for_line(row).len
 8443                };
 8444
 8445                let start = Point::new(row.0, indent_size);
 8446
 8447                let mut line_bytes = snapshot
 8448                    .bytes_in_range(start..snapshot.max_point())
 8449                    .flatten()
 8450                    .copied();
 8451
 8452                // If this line currently begins with the line comment prefix, then record
 8453                // the range containing the prefix.
 8454                if line_bytes
 8455                    .by_ref()
 8456                    .take(comment_prefix.len())
 8457                    .eq(comment_prefix.bytes())
 8458                {
 8459                    // Include any whitespace that matches the comment prefix.
 8460                    let matching_whitespace_len = line_bytes
 8461                        .zip(comment_prefix_whitespace.bytes())
 8462                        .take_while(|(a, b)| a == b)
 8463                        .count() as u32;
 8464                    let end = Point::new(
 8465                        start.row,
 8466                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8467                    );
 8468                    start..end
 8469                } else {
 8470                    start..start
 8471                }
 8472            }
 8473
 8474            fn comment_suffix_range(
 8475                snapshot: &MultiBufferSnapshot,
 8476                row: MultiBufferRow,
 8477                comment_suffix: &str,
 8478                comment_suffix_has_leading_space: bool,
 8479            ) -> Range<Point> {
 8480                let end = Point::new(row.0, snapshot.line_len(row));
 8481                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8482
 8483                let mut line_end_bytes = snapshot
 8484                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8485                    .flatten()
 8486                    .copied();
 8487
 8488                let leading_space_len = if suffix_start_column > 0
 8489                    && line_end_bytes.next() == Some(b' ')
 8490                    && comment_suffix_has_leading_space
 8491                {
 8492                    1
 8493                } else {
 8494                    0
 8495                };
 8496
 8497                // If this line currently begins with the line comment prefix, then record
 8498                // the range containing the prefix.
 8499                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8500                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8501                    start..end
 8502                } else {
 8503                    end..end
 8504                }
 8505            }
 8506
 8507            // TODO: Handle selections that cross excerpts
 8508            for selection in &mut selections {
 8509                let start_column = snapshot
 8510                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8511                    .len;
 8512                let language = if let Some(language) =
 8513                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8514                {
 8515                    language
 8516                } else {
 8517                    continue;
 8518                };
 8519
 8520                selection_edit_ranges.clear();
 8521
 8522                // If multiple selections contain a given row, avoid processing that
 8523                // row more than once.
 8524                let mut start_row = MultiBufferRow(selection.start.row);
 8525                if last_toggled_row == Some(start_row) {
 8526                    start_row = start_row.next_row();
 8527                }
 8528                let end_row =
 8529                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8530                        MultiBufferRow(selection.end.row - 1)
 8531                    } else {
 8532                        MultiBufferRow(selection.end.row)
 8533                    };
 8534                last_toggled_row = Some(end_row);
 8535
 8536                if start_row > end_row {
 8537                    continue;
 8538                }
 8539
 8540                // If the language has line comments, toggle those.
 8541                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8542
 8543                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8544                if ignore_indent {
 8545                    full_comment_prefixes = full_comment_prefixes
 8546                        .into_iter()
 8547                        .map(|s| Arc::from(s.trim_end()))
 8548                        .collect();
 8549                }
 8550
 8551                if !full_comment_prefixes.is_empty() {
 8552                    let first_prefix = full_comment_prefixes
 8553                        .first()
 8554                        .expect("prefixes is non-empty");
 8555                    let prefix_trimmed_lengths = full_comment_prefixes
 8556                        .iter()
 8557                        .map(|p| p.trim_end_matches(' ').len())
 8558                        .collect::<SmallVec<[usize; 4]>>();
 8559
 8560                    let mut all_selection_lines_are_comments = true;
 8561
 8562                    for row in start_row.0..=end_row.0 {
 8563                        let row = MultiBufferRow(row);
 8564                        if start_row < end_row && snapshot.is_line_blank(row) {
 8565                            continue;
 8566                        }
 8567
 8568                        let prefix_range = full_comment_prefixes
 8569                            .iter()
 8570                            .zip(prefix_trimmed_lengths.iter().copied())
 8571                            .map(|(prefix, trimmed_prefix_len)| {
 8572                                comment_prefix_range(
 8573                                    snapshot.deref(),
 8574                                    row,
 8575                                    &prefix[..trimmed_prefix_len],
 8576                                    &prefix[trimmed_prefix_len..],
 8577                                    ignore_indent,
 8578                                )
 8579                            })
 8580                            .max_by_key(|range| range.end.column - range.start.column)
 8581                            .expect("prefixes is non-empty");
 8582
 8583                        if prefix_range.is_empty() {
 8584                            all_selection_lines_are_comments = false;
 8585                        }
 8586
 8587                        selection_edit_ranges.push(prefix_range);
 8588                    }
 8589
 8590                    if all_selection_lines_are_comments {
 8591                        edits.extend(
 8592                            selection_edit_ranges
 8593                                .iter()
 8594                                .cloned()
 8595                                .map(|range| (range, empty_str.clone())),
 8596                        );
 8597                    } else {
 8598                        let min_column = selection_edit_ranges
 8599                            .iter()
 8600                            .map(|range| range.start.column)
 8601                            .min()
 8602                            .unwrap_or(0);
 8603                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8604                            let position = Point::new(range.start.row, min_column);
 8605                            (position..position, first_prefix.clone())
 8606                        }));
 8607                    }
 8608                } else if let Some((full_comment_prefix, comment_suffix)) =
 8609                    language.block_comment_delimiters()
 8610                {
 8611                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8612                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8613                    let prefix_range = comment_prefix_range(
 8614                        snapshot.deref(),
 8615                        start_row,
 8616                        comment_prefix,
 8617                        comment_prefix_whitespace,
 8618                        ignore_indent,
 8619                    );
 8620                    let suffix_range = comment_suffix_range(
 8621                        snapshot.deref(),
 8622                        end_row,
 8623                        comment_suffix.trim_start_matches(' '),
 8624                        comment_suffix.starts_with(' '),
 8625                    );
 8626
 8627                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8628                        edits.push((
 8629                            prefix_range.start..prefix_range.start,
 8630                            full_comment_prefix.clone(),
 8631                        ));
 8632                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8633                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8634                    } else {
 8635                        edits.push((prefix_range, empty_str.clone()));
 8636                        edits.push((suffix_range, empty_str.clone()));
 8637                    }
 8638                } else {
 8639                    continue;
 8640                }
 8641            }
 8642
 8643            drop(snapshot);
 8644            this.buffer.update(cx, |buffer, cx| {
 8645                buffer.edit(edits, None, cx);
 8646            });
 8647
 8648            // Adjust selections so that they end before any comment suffixes that
 8649            // were inserted.
 8650            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8651            let mut selections = this.selections.all::<Point>(cx);
 8652            let snapshot = this.buffer.read(cx).read(cx);
 8653            for selection in &mut selections {
 8654                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8655                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8656                        Ordering::Less => {
 8657                            suffixes_inserted.next();
 8658                            continue;
 8659                        }
 8660                        Ordering::Greater => break,
 8661                        Ordering::Equal => {
 8662                            if selection.end.column == snapshot.line_len(row) {
 8663                                if selection.is_empty() {
 8664                                    selection.start.column -= suffix_len as u32;
 8665                                }
 8666                                selection.end.column -= suffix_len as u32;
 8667                            }
 8668                            break;
 8669                        }
 8670                    }
 8671                }
 8672            }
 8673
 8674            drop(snapshot);
 8675            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8676
 8677            let selections = this.selections.all::<Point>(cx);
 8678            let selections_on_single_row = selections.windows(2).all(|selections| {
 8679                selections[0].start.row == selections[1].start.row
 8680                    && selections[0].end.row == selections[1].end.row
 8681                    && selections[0].start.row == selections[0].end.row
 8682            });
 8683            let selections_selecting = selections
 8684                .iter()
 8685                .any(|selection| selection.start != selection.end);
 8686            let advance_downwards = action.advance_downwards
 8687                && selections_on_single_row
 8688                && !selections_selecting
 8689                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8690
 8691            if advance_downwards {
 8692                let snapshot = this.buffer.read(cx).snapshot(cx);
 8693
 8694                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8695                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8696                        let mut point = display_point.to_point(display_snapshot);
 8697                        point.row += 1;
 8698                        point = snapshot.clip_point(point, Bias::Left);
 8699                        let display_point = point.to_display_point(display_snapshot);
 8700                        let goal = SelectionGoal::HorizontalPosition(
 8701                            display_snapshot
 8702                                .x_for_display_point(display_point, text_layout_details)
 8703                                .into(),
 8704                        );
 8705                        (display_point, goal)
 8706                    })
 8707                });
 8708            }
 8709        });
 8710    }
 8711
 8712    pub fn select_enclosing_symbol(
 8713        &mut self,
 8714        _: &SelectEnclosingSymbol,
 8715        cx: &mut ViewContext<Self>,
 8716    ) {
 8717        let buffer = self.buffer.read(cx).snapshot(cx);
 8718        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8719
 8720        fn update_selection(
 8721            selection: &Selection<usize>,
 8722            buffer_snap: &MultiBufferSnapshot,
 8723        ) -> Option<Selection<usize>> {
 8724            let cursor = selection.head();
 8725            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8726            for symbol in symbols.iter().rev() {
 8727                let start = symbol.range.start.to_offset(buffer_snap);
 8728                let end = symbol.range.end.to_offset(buffer_snap);
 8729                let new_range = start..end;
 8730                if start < selection.start || end > selection.end {
 8731                    return Some(Selection {
 8732                        id: selection.id,
 8733                        start: new_range.start,
 8734                        end: new_range.end,
 8735                        goal: SelectionGoal::None,
 8736                        reversed: selection.reversed,
 8737                    });
 8738                }
 8739            }
 8740            None
 8741        }
 8742
 8743        let mut selected_larger_symbol = false;
 8744        let new_selections = old_selections
 8745            .iter()
 8746            .map(|selection| match update_selection(selection, &buffer) {
 8747                Some(new_selection) => {
 8748                    if new_selection.range() != selection.range() {
 8749                        selected_larger_symbol = true;
 8750                    }
 8751                    new_selection
 8752                }
 8753                None => selection.clone(),
 8754            })
 8755            .collect::<Vec<_>>();
 8756
 8757        if selected_larger_symbol {
 8758            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8759                s.select(new_selections);
 8760            });
 8761        }
 8762    }
 8763
 8764    pub fn select_larger_syntax_node(
 8765        &mut self,
 8766        _: &SelectLargerSyntaxNode,
 8767        cx: &mut ViewContext<Self>,
 8768    ) {
 8769        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8770        let buffer = self.buffer.read(cx).snapshot(cx);
 8771        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8772
 8773        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8774        let mut selected_larger_node = false;
 8775        let new_selections = old_selections
 8776            .iter()
 8777            .map(|selection| {
 8778                let old_range = selection.start..selection.end;
 8779                let mut new_range = old_range.clone();
 8780                let mut new_node = None;
 8781                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 8782                {
 8783                    new_node = Some(node);
 8784                    new_range = containing_range;
 8785                    if !display_map.intersects_fold(new_range.start)
 8786                        && !display_map.intersects_fold(new_range.end)
 8787                    {
 8788                        break;
 8789                    }
 8790                }
 8791
 8792                if let Some(node) = new_node {
 8793                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 8794                    // nodes. Parent and grandparent are also logged because this operation will not
 8795                    // visit nodes that have the same range as their parent.
 8796                    log::info!("Node: {node:?}");
 8797                    let parent = node.parent();
 8798                    log::info!("Parent: {parent:?}");
 8799                    let grandparent = parent.and_then(|x| x.parent());
 8800                    log::info!("Grandparent: {grandparent:?}");
 8801                }
 8802
 8803                selected_larger_node |= new_range != old_range;
 8804                Selection {
 8805                    id: selection.id,
 8806                    start: new_range.start,
 8807                    end: new_range.end,
 8808                    goal: SelectionGoal::None,
 8809                    reversed: selection.reversed,
 8810                }
 8811            })
 8812            .collect::<Vec<_>>();
 8813
 8814        if selected_larger_node {
 8815            stack.push(old_selections);
 8816            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8817                s.select(new_selections);
 8818            });
 8819        }
 8820        self.select_larger_syntax_node_stack = stack;
 8821    }
 8822
 8823    pub fn select_smaller_syntax_node(
 8824        &mut self,
 8825        _: &SelectSmallerSyntaxNode,
 8826        cx: &mut ViewContext<Self>,
 8827    ) {
 8828        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8829        if let Some(selections) = stack.pop() {
 8830            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8831                s.select(selections.to_vec());
 8832            });
 8833        }
 8834        self.select_larger_syntax_node_stack = stack;
 8835    }
 8836
 8837    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8838        if !EditorSettings::get_global(cx).gutter.runnables {
 8839            self.clear_tasks();
 8840            return Task::ready(());
 8841        }
 8842        let project = self.project.as_ref().map(Model::downgrade);
 8843        cx.spawn(|this, mut cx| async move {
 8844            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8845            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8846                return;
 8847            };
 8848            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8849                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8850            }) else {
 8851                return;
 8852            };
 8853
 8854            let hide_runnables = project
 8855                .update(&mut cx, |project, cx| {
 8856                    // Do not display any test indicators in non-dev server remote projects.
 8857                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8858                })
 8859                .unwrap_or(true);
 8860            if hide_runnables {
 8861                return;
 8862            }
 8863            let new_rows =
 8864                cx.background_executor()
 8865                    .spawn({
 8866                        let snapshot = display_snapshot.clone();
 8867                        async move {
 8868                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8869                        }
 8870                    })
 8871                    .await;
 8872            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8873
 8874            this.update(&mut cx, |this, _| {
 8875                this.clear_tasks();
 8876                for (key, value) in rows {
 8877                    this.insert_tasks(key, value);
 8878                }
 8879            })
 8880            .ok();
 8881        })
 8882    }
 8883    fn fetch_runnable_ranges(
 8884        snapshot: &DisplaySnapshot,
 8885        range: Range<Anchor>,
 8886    ) -> Vec<language::RunnableRange> {
 8887        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8888    }
 8889
 8890    fn runnable_rows(
 8891        project: Model<Project>,
 8892        snapshot: DisplaySnapshot,
 8893        runnable_ranges: Vec<RunnableRange>,
 8894        mut cx: AsyncWindowContext,
 8895    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8896        runnable_ranges
 8897            .into_iter()
 8898            .filter_map(|mut runnable| {
 8899                let tasks = cx
 8900                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8901                    .ok()?;
 8902                if tasks.is_empty() {
 8903                    return None;
 8904                }
 8905
 8906                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8907
 8908                let row = snapshot
 8909                    .buffer_snapshot
 8910                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8911                    .1
 8912                    .start
 8913                    .row;
 8914
 8915                let context_range =
 8916                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8917                Some((
 8918                    (runnable.buffer_id, row),
 8919                    RunnableTasks {
 8920                        templates: tasks,
 8921                        offset: MultiBufferOffset(runnable.run_range.start),
 8922                        context_range,
 8923                        column: point.column,
 8924                        extra_variables: runnable.extra_captures,
 8925                    },
 8926                ))
 8927            })
 8928            .collect()
 8929    }
 8930
 8931    fn templates_with_tags(
 8932        project: &Model<Project>,
 8933        runnable: &mut Runnable,
 8934        cx: &WindowContext<'_>,
 8935    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8936        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8937            let (worktree_id, file) = project
 8938                .buffer_for_id(runnable.buffer, cx)
 8939                .and_then(|buffer| buffer.read(cx).file())
 8940                .map(|file| (file.worktree_id(cx), file.clone()))
 8941                .unzip();
 8942
 8943            (
 8944                project.task_store().read(cx).task_inventory().cloned(),
 8945                worktree_id,
 8946                file,
 8947            )
 8948        });
 8949
 8950        let tags = mem::take(&mut runnable.tags);
 8951        let mut tags: Vec<_> = tags
 8952            .into_iter()
 8953            .flat_map(|tag| {
 8954                let tag = tag.0.clone();
 8955                inventory
 8956                    .as_ref()
 8957                    .into_iter()
 8958                    .flat_map(|inventory| {
 8959                        inventory.read(cx).list_tasks(
 8960                            file.clone(),
 8961                            Some(runnable.language.clone()),
 8962                            worktree_id,
 8963                            cx,
 8964                        )
 8965                    })
 8966                    .filter(move |(_, template)| {
 8967                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8968                    })
 8969            })
 8970            .sorted_by_key(|(kind, _)| kind.to_owned())
 8971            .collect();
 8972        if let Some((leading_tag_source, _)) = tags.first() {
 8973            // Strongest source wins; if we have worktree tag binding, prefer that to
 8974            // global and language bindings;
 8975            // if we have a global binding, prefer that to language binding.
 8976            let first_mismatch = tags
 8977                .iter()
 8978                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8979            if let Some(index) = first_mismatch {
 8980                tags.truncate(index);
 8981            }
 8982        }
 8983
 8984        tags
 8985    }
 8986
 8987    pub fn move_to_enclosing_bracket(
 8988        &mut self,
 8989        _: &MoveToEnclosingBracket,
 8990        cx: &mut ViewContext<Self>,
 8991    ) {
 8992        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8993            s.move_offsets_with(|snapshot, selection| {
 8994                let Some(enclosing_bracket_ranges) =
 8995                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8996                else {
 8997                    return;
 8998                };
 8999
 9000                let mut best_length = usize::MAX;
 9001                let mut best_inside = false;
 9002                let mut best_in_bracket_range = false;
 9003                let mut best_destination = None;
 9004                for (open, close) in enclosing_bracket_ranges {
 9005                    let close = close.to_inclusive();
 9006                    let length = close.end() - open.start;
 9007                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9008                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9009                        || close.contains(&selection.head());
 9010
 9011                    // If best is next to a bracket and current isn't, skip
 9012                    if !in_bracket_range && best_in_bracket_range {
 9013                        continue;
 9014                    }
 9015
 9016                    // Prefer smaller lengths unless best is inside and current isn't
 9017                    if length > best_length && (best_inside || !inside) {
 9018                        continue;
 9019                    }
 9020
 9021                    best_length = length;
 9022                    best_inside = inside;
 9023                    best_in_bracket_range = in_bracket_range;
 9024                    best_destination = Some(
 9025                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9026                            if inside {
 9027                                open.end
 9028                            } else {
 9029                                open.start
 9030                            }
 9031                        } else if inside {
 9032                            *close.start()
 9033                        } else {
 9034                            *close.end()
 9035                        },
 9036                    );
 9037                }
 9038
 9039                if let Some(destination) = best_destination {
 9040                    selection.collapse_to(destination, SelectionGoal::None);
 9041                }
 9042            })
 9043        });
 9044    }
 9045
 9046    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9047        self.end_selection(cx);
 9048        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9049        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9050            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9051            self.select_next_state = entry.select_next_state;
 9052            self.select_prev_state = entry.select_prev_state;
 9053            self.add_selections_state = entry.add_selections_state;
 9054            self.request_autoscroll(Autoscroll::newest(), cx);
 9055        }
 9056        self.selection_history.mode = SelectionHistoryMode::Normal;
 9057    }
 9058
 9059    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9060        self.end_selection(cx);
 9061        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9062        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9063            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9064            self.select_next_state = entry.select_next_state;
 9065            self.select_prev_state = entry.select_prev_state;
 9066            self.add_selections_state = entry.add_selections_state;
 9067            self.request_autoscroll(Autoscroll::newest(), cx);
 9068        }
 9069        self.selection_history.mode = SelectionHistoryMode::Normal;
 9070    }
 9071
 9072    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9073        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9074    }
 9075
 9076    pub fn expand_excerpts_down(
 9077        &mut self,
 9078        action: &ExpandExcerptsDown,
 9079        cx: &mut ViewContext<Self>,
 9080    ) {
 9081        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9082    }
 9083
 9084    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9085        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9086    }
 9087
 9088    pub fn expand_excerpts_for_direction(
 9089        &mut self,
 9090        lines: u32,
 9091        direction: ExpandExcerptDirection,
 9092        cx: &mut ViewContext<Self>,
 9093    ) {
 9094        let selections = self.selections.disjoint_anchors();
 9095
 9096        let lines = if lines == 0 {
 9097            EditorSettings::get_global(cx).expand_excerpt_lines
 9098        } else {
 9099            lines
 9100        };
 9101
 9102        self.buffer.update(cx, |buffer, cx| {
 9103            buffer.expand_excerpts(
 9104                selections
 9105                    .iter()
 9106                    .map(|selection| selection.head().excerpt_id)
 9107                    .dedup(),
 9108                lines,
 9109                direction,
 9110                cx,
 9111            )
 9112        })
 9113    }
 9114
 9115    pub fn expand_excerpt(
 9116        &mut self,
 9117        excerpt: ExcerptId,
 9118        direction: ExpandExcerptDirection,
 9119        cx: &mut ViewContext<Self>,
 9120    ) {
 9121        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9122        self.buffer.update(cx, |buffer, cx| {
 9123            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9124        })
 9125    }
 9126
 9127    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9128        self.go_to_diagnostic_impl(Direction::Next, cx)
 9129    }
 9130
 9131    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9132        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9133    }
 9134
 9135    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9136        let buffer = self.buffer.read(cx).snapshot(cx);
 9137        let selection = self.selections.newest::<usize>(cx);
 9138
 9139        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9140        if direction == Direction::Next {
 9141            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9142                let (group_id, jump_to) = popover.activation_info();
 9143                if self.activate_diagnostics(group_id, cx) {
 9144                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9145                        let mut new_selection = s.newest_anchor().clone();
 9146                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9147                        s.select_anchors(vec![new_selection.clone()]);
 9148                    });
 9149                }
 9150                return;
 9151            }
 9152        }
 9153
 9154        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9155            active_diagnostics
 9156                .primary_range
 9157                .to_offset(&buffer)
 9158                .to_inclusive()
 9159        });
 9160        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9161            if active_primary_range.contains(&selection.head()) {
 9162                *active_primary_range.start()
 9163            } else {
 9164                selection.head()
 9165            }
 9166        } else {
 9167            selection.head()
 9168        };
 9169        let snapshot = self.snapshot(cx);
 9170        loop {
 9171            let diagnostics = if direction == Direction::Prev {
 9172                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9173            } else {
 9174                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9175            }
 9176            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9177            let group = diagnostics
 9178                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9179                // be sorted in a stable way
 9180                // skip until we are at current active diagnostic, if it exists
 9181                .skip_while(|entry| {
 9182                    (match direction {
 9183                        Direction::Prev => entry.range.start >= search_start,
 9184                        Direction::Next => entry.range.start <= search_start,
 9185                    }) && self
 9186                        .active_diagnostics
 9187                        .as_ref()
 9188                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9189                })
 9190                .find_map(|entry| {
 9191                    if entry.diagnostic.is_primary
 9192                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9193                        && !entry.range.is_empty()
 9194                        // if we match with the active diagnostic, skip it
 9195                        && Some(entry.diagnostic.group_id)
 9196                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9197                    {
 9198                        Some((entry.range, entry.diagnostic.group_id))
 9199                    } else {
 9200                        None
 9201                    }
 9202                });
 9203
 9204            if let Some((primary_range, group_id)) = group {
 9205                if self.activate_diagnostics(group_id, cx) {
 9206                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9207                        s.select(vec![Selection {
 9208                            id: selection.id,
 9209                            start: primary_range.start,
 9210                            end: primary_range.start,
 9211                            reversed: false,
 9212                            goal: SelectionGoal::None,
 9213                        }]);
 9214                    });
 9215                }
 9216                break;
 9217            } else {
 9218                // Cycle around to the start of the buffer, potentially moving back to the start of
 9219                // the currently active diagnostic.
 9220                active_primary_range.take();
 9221                if direction == Direction::Prev {
 9222                    if search_start == buffer.len() {
 9223                        break;
 9224                    } else {
 9225                        search_start = buffer.len();
 9226                    }
 9227                } else if search_start == 0 {
 9228                    break;
 9229                } else {
 9230                    search_start = 0;
 9231                }
 9232            }
 9233        }
 9234    }
 9235
 9236    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9237        let snapshot = self.snapshot(cx);
 9238        let selection = self.selections.newest::<Point>(cx);
 9239        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9240    }
 9241
 9242    fn go_to_hunk_after_position(
 9243        &mut self,
 9244        snapshot: &EditorSnapshot,
 9245        position: Point,
 9246        cx: &mut ViewContext<'_, Editor>,
 9247    ) -> Option<MultiBufferDiffHunk> {
 9248        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9249            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9250                snapshot,
 9251                position,
 9252                ix > 0,
 9253                snapshot.diff_map.diff_hunks_in_range(
 9254                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9255                    &snapshot.buffer_snapshot,
 9256                ),
 9257                cx,
 9258            ) {
 9259                return Some(hunk);
 9260            }
 9261        }
 9262        None
 9263    }
 9264
 9265    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9266        let snapshot = self.snapshot(cx);
 9267        let selection = self.selections.newest::<Point>(cx);
 9268        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9269    }
 9270
 9271    fn go_to_hunk_before_position(
 9272        &mut self,
 9273        snapshot: &EditorSnapshot,
 9274        position: Point,
 9275        cx: &mut ViewContext<'_, Editor>,
 9276    ) -> Option<MultiBufferDiffHunk> {
 9277        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9278            .into_iter()
 9279            .enumerate()
 9280        {
 9281            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9282                snapshot,
 9283                position,
 9284                ix > 0,
 9285                snapshot
 9286                    .diff_map
 9287                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9288                cx,
 9289            ) {
 9290                return Some(hunk);
 9291            }
 9292        }
 9293        None
 9294    }
 9295
 9296    fn go_to_next_hunk_in_direction(
 9297        &mut self,
 9298        snapshot: &DisplaySnapshot,
 9299        initial_point: Point,
 9300        is_wrapped: bool,
 9301        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9302        cx: &mut ViewContext<Editor>,
 9303    ) -> Option<MultiBufferDiffHunk> {
 9304        let display_point = initial_point.to_display_point(snapshot);
 9305        let mut hunks = hunks
 9306            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9307            .filter(|(display_hunk, _)| {
 9308                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9309            })
 9310            .dedup();
 9311
 9312        if let Some((display_hunk, hunk)) = hunks.next() {
 9313            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9314                let row = display_hunk.start_display_row();
 9315                let point = DisplayPoint::new(row, 0);
 9316                s.select_display_ranges([point..point]);
 9317            });
 9318
 9319            Some(hunk)
 9320        } else {
 9321            None
 9322        }
 9323    }
 9324
 9325    pub fn go_to_definition(
 9326        &mut self,
 9327        _: &GoToDefinition,
 9328        cx: &mut ViewContext<Self>,
 9329    ) -> Task<Result<Navigated>> {
 9330        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9331        cx.spawn(|editor, mut cx| async move {
 9332            if definition.await? == Navigated::Yes {
 9333                return Ok(Navigated::Yes);
 9334            }
 9335            match editor.update(&mut cx, |editor, cx| {
 9336                editor.find_all_references(&FindAllReferences, cx)
 9337            })? {
 9338                Some(references) => references.await,
 9339                None => Ok(Navigated::No),
 9340            }
 9341        })
 9342    }
 9343
 9344    pub fn go_to_declaration(
 9345        &mut self,
 9346        _: &GoToDeclaration,
 9347        cx: &mut ViewContext<Self>,
 9348    ) -> Task<Result<Navigated>> {
 9349        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9350    }
 9351
 9352    pub fn go_to_declaration_split(
 9353        &mut self,
 9354        _: &GoToDeclaration,
 9355        cx: &mut ViewContext<Self>,
 9356    ) -> Task<Result<Navigated>> {
 9357        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9358    }
 9359
 9360    pub fn go_to_implementation(
 9361        &mut self,
 9362        _: &GoToImplementation,
 9363        cx: &mut ViewContext<Self>,
 9364    ) -> Task<Result<Navigated>> {
 9365        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9366    }
 9367
 9368    pub fn go_to_implementation_split(
 9369        &mut self,
 9370        _: &GoToImplementationSplit,
 9371        cx: &mut ViewContext<Self>,
 9372    ) -> Task<Result<Navigated>> {
 9373        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9374    }
 9375
 9376    pub fn go_to_type_definition(
 9377        &mut self,
 9378        _: &GoToTypeDefinition,
 9379        cx: &mut ViewContext<Self>,
 9380    ) -> Task<Result<Navigated>> {
 9381        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9382    }
 9383
 9384    pub fn go_to_definition_split(
 9385        &mut self,
 9386        _: &GoToDefinitionSplit,
 9387        cx: &mut ViewContext<Self>,
 9388    ) -> Task<Result<Navigated>> {
 9389        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9390    }
 9391
 9392    pub fn go_to_type_definition_split(
 9393        &mut self,
 9394        _: &GoToTypeDefinitionSplit,
 9395        cx: &mut ViewContext<Self>,
 9396    ) -> Task<Result<Navigated>> {
 9397        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9398    }
 9399
 9400    fn go_to_definition_of_kind(
 9401        &mut self,
 9402        kind: GotoDefinitionKind,
 9403        split: bool,
 9404        cx: &mut ViewContext<Self>,
 9405    ) -> Task<Result<Navigated>> {
 9406        let Some(provider) = self.semantics_provider.clone() else {
 9407            return Task::ready(Ok(Navigated::No));
 9408        };
 9409        let head = self.selections.newest::<usize>(cx).head();
 9410        let buffer = self.buffer.read(cx);
 9411        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9412            text_anchor
 9413        } else {
 9414            return Task::ready(Ok(Navigated::No));
 9415        };
 9416
 9417        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9418            return Task::ready(Ok(Navigated::No));
 9419        };
 9420
 9421        cx.spawn(|editor, mut cx| async move {
 9422            let definitions = definitions.await?;
 9423            let navigated = editor
 9424                .update(&mut cx, |editor, cx| {
 9425                    editor.navigate_to_hover_links(
 9426                        Some(kind),
 9427                        definitions
 9428                            .into_iter()
 9429                            .filter(|location| {
 9430                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9431                            })
 9432                            .map(HoverLink::Text)
 9433                            .collect::<Vec<_>>(),
 9434                        split,
 9435                        cx,
 9436                    )
 9437                })?
 9438                .await?;
 9439            anyhow::Ok(navigated)
 9440        })
 9441    }
 9442
 9443    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9444        let selection = self.selections.newest_anchor();
 9445        let head = selection.head();
 9446        let tail = selection.tail();
 9447
 9448        let Some((buffer, start_position)) =
 9449            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9450        else {
 9451            return;
 9452        };
 9453
 9454        let end_position = if head != tail {
 9455            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9456                return;
 9457            };
 9458            Some(pos)
 9459        } else {
 9460            None
 9461        };
 9462
 9463        let url_finder = cx.spawn(|editor, mut cx| async move {
 9464            let url = if let Some(end_pos) = end_position {
 9465                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9466            } else {
 9467                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9468            };
 9469
 9470            if let Some(url) = url {
 9471                editor.update(&mut cx, |_, cx| {
 9472                    cx.open_url(&url);
 9473                })
 9474            } else {
 9475                Ok(())
 9476            }
 9477        });
 9478
 9479        url_finder.detach();
 9480    }
 9481
 9482    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9483        let Some(workspace) = self.workspace() else {
 9484            return;
 9485        };
 9486
 9487        let position = self.selections.newest_anchor().head();
 9488
 9489        let Some((buffer, buffer_position)) =
 9490            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9491        else {
 9492            return;
 9493        };
 9494
 9495        let project = self.project.clone();
 9496
 9497        cx.spawn(|_, mut cx| async move {
 9498            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9499
 9500            if let Some((_, path)) = result {
 9501                workspace
 9502                    .update(&mut cx, |workspace, cx| {
 9503                        workspace.open_resolved_path(path, cx)
 9504                    })?
 9505                    .await?;
 9506            }
 9507            anyhow::Ok(())
 9508        })
 9509        .detach();
 9510    }
 9511
 9512    pub(crate) fn navigate_to_hover_links(
 9513        &mut self,
 9514        kind: Option<GotoDefinitionKind>,
 9515        mut definitions: Vec<HoverLink>,
 9516        split: bool,
 9517        cx: &mut ViewContext<Editor>,
 9518    ) -> Task<Result<Navigated>> {
 9519        // If there is one definition, just open it directly
 9520        if definitions.len() == 1 {
 9521            let definition = definitions.pop().unwrap();
 9522
 9523            enum TargetTaskResult {
 9524                Location(Option<Location>),
 9525                AlreadyNavigated,
 9526            }
 9527
 9528            let target_task = match definition {
 9529                HoverLink::Text(link) => {
 9530                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9531                }
 9532                HoverLink::InlayHint(lsp_location, server_id) => {
 9533                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9534                    cx.background_executor().spawn(async move {
 9535                        let location = computation.await?;
 9536                        Ok(TargetTaskResult::Location(location))
 9537                    })
 9538                }
 9539                HoverLink::Url(url) => {
 9540                    cx.open_url(&url);
 9541                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9542                }
 9543                HoverLink::File(path) => {
 9544                    if let Some(workspace) = self.workspace() {
 9545                        cx.spawn(|_, mut cx| async move {
 9546                            workspace
 9547                                .update(&mut cx, |workspace, cx| {
 9548                                    workspace.open_resolved_path(path, cx)
 9549                                })?
 9550                                .await
 9551                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9552                        })
 9553                    } else {
 9554                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9555                    }
 9556                }
 9557            };
 9558            cx.spawn(|editor, mut cx| async move {
 9559                let target = match target_task.await.context("target resolution task")? {
 9560                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9561                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9562                    TargetTaskResult::Location(Some(target)) => target,
 9563                };
 9564
 9565                editor.update(&mut cx, |editor, cx| {
 9566                    let Some(workspace) = editor.workspace() else {
 9567                        return Navigated::No;
 9568                    };
 9569                    let pane = workspace.read(cx).active_pane().clone();
 9570
 9571                    let range = target.range.to_offset(target.buffer.read(cx));
 9572                    let range = editor.range_for_match(&range);
 9573
 9574                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9575                        let buffer = target.buffer.read(cx);
 9576                        let range = check_multiline_range(buffer, range);
 9577                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9578                            s.select_ranges([range]);
 9579                        });
 9580                    } else {
 9581                        cx.window_context().defer(move |cx| {
 9582                            let target_editor: View<Self> =
 9583                                workspace.update(cx, |workspace, cx| {
 9584                                    let pane = if split {
 9585                                        workspace.adjacent_pane(cx)
 9586                                    } else {
 9587                                        workspace.active_pane().clone()
 9588                                    };
 9589
 9590                                    workspace.open_project_item(
 9591                                        pane,
 9592                                        target.buffer.clone(),
 9593                                        true,
 9594                                        true,
 9595                                        cx,
 9596                                    )
 9597                                });
 9598                            target_editor.update(cx, |target_editor, cx| {
 9599                                // When selecting a definition in a different buffer, disable the nav history
 9600                                // to avoid creating a history entry at the previous cursor location.
 9601                                pane.update(cx, |pane, _| pane.disable_history());
 9602                                let buffer = target.buffer.read(cx);
 9603                                let range = check_multiline_range(buffer, range);
 9604                                target_editor.change_selections(
 9605                                    Some(Autoscroll::focused()),
 9606                                    cx,
 9607                                    |s| {
 9608                                        s.select_ranges([range]);
 9609                                    },
 9610                                );
 9611                                pane.update(cx, |pane, _| pane.enable_history());
 9612                            });
 9613                        });
 9614                    }
 9615                    Navigated::Yes
 9616                })
 9617            })
 9618        } else if !definitions.is_empty() {
 9619            cx.spawn(|editor, mut cx| async move {
 9620                let (title, location_tasks, workspace) = editor
 9621                    .update(&mut cx, |editor, cx| {
 9622                        let tab_kind = match kind {
 9623                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9624                            _ => "Definitions",
 9625                        };
 9626                        let title = definitions
 9627                            .iter()
 9628                            .find_map(|definition| match definition {
 9629                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9630                                    let buffer = origin.buffer.read(cx);
 9631                                    format!(
 9632                                        "{} for {}",
 9633                                        tab_kind,
 9634                                        buffer
 9635                                            .text_for_range(origin.range.clone())
 9636                                            .collect::<String>()
 9637                                    )
 9638                                }),
 9639                                HoverLink::InlayHint(_, _) => None,
 9640                                HoverLink::Url(_) => None,
 9641                                HoverLink::File(_) => None,
 9642                            })
 9643                            .unwrap_or(tab_kind.to_string());
 9644                        let location_tasks = definitions
 9645                            .into_iter()
 9646                            .map(|definition| match definition {
 9647                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9648                                HoverLink::InlayHint(lsp_location, server_id) => {
 9649                                    editor.compute_target_location(lsp_location, server_id, cx)
 9650                                }
 9651                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9652                                HoverLink::File(_) => Task::ready(Ok(None)),
 9653                            })
 9654                            .collect::<Vec<_>>();
 9655                        (title, location_tasks, editor.workspace().clone())
 9656                    })
 9657                    .context("location tasks preparation")?;
 9658
 9659                let locations = future::join_all(location_tasks)
 9660                    .await
 9661                    .into_iter()
 9662                    .filter_map(|location| location.transpose())
 9663                    .collect::<Result<_>>()
 9664                    .context("location tasks")?;
 9665
 9666                let Some(workspace) = workspace else {
 9667                    return Ok(Navigated::No);
 9668                };
 9669                let opened = workspace
 9670                    .update(&mut cx, |workspace, cx| {
 9671                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9672                    })
 9673                    .ok();
 9674
 9675                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9676            })
 9677        } else {
 9678            Task::ready(Ok(Navigated::No))
 9679        }
 9680    }
 9681
 9682    fn compute_target_location(
 9683        &self,
 9684        lsp_location: lsp::Location,
 9685        server_id: LanguageServerId,
 9686        cx: &mut ViewContext<Self>,
 9687    ) -> Task<anyhow::Result<Option<Location>>> {
 9688        let Some(project) = self.project.clone() else {
 9689            return Task::ready(Ok(None));
 9690        };
 9691
 9692        cx.spawn(move |editor, mut cx| async move {
 9693            let location_task = editor.update(&mut cx, |_, cx| {
 9694                project.update(cx, |project, cx| {
 9695                    let language_server_name = project
 9696                        .language_server_statuses(cx)
 9697                        .find(|(id, _)| server_id == *id)
 9698                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9699                    language_server_name.map(|language_server_name| {
 9700                        project.open_local_buffer_via_lsp(
 9701                            lsp_location.uri.clone(),
 9702                            server_id,
 9703                            language_server_name,
 9704                            cx,
 9705                        )
 9706                    })
 9707                })
 9708            })?;
 9709            let location = match location_task {
 9710                Some(task) => Some({
 9711                    let target_buffer_handle = task.await.context("open local buffer")?;
 9712                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9713                        let target_start = target_buffer
 9714                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9715                        let target_end = target_buffer
 9716                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9717                        target_buffer.anchor_after(target_start)
 9718                            ..target_buffer.anchor_before(target_end)
 9719                    })?;
 9720                    Location {
 9721                        buffer: target_buffer_handle,
 9722                        range,
 9723                    }
 9724                }),
 9725                None => None,
 9726            };
 9727            Ok(location)
 9728        })
 9729    }
 9730
 9731    pub fn find_all_references(
 9732        &mut self,
 9733        _: &FindAllReferences,
 9734        cx: &mut ViewContext<Self>,
 9735    ) -> Option<Task<Result<Navigated>>> {
 9736        let selection = self.selections.newest::<usize>(cx);
 9737        let multi_buffer = self.buffer.read(cx);
 9738        let head = selection.head();
 9739
 9740        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9741        let head_anchor = multi_buffer_snapshot.anchor_at(
 9742            head,
 9743            if head < selection.tail() {
 9744                Bias::Right
 9745            } else {
 9746                Bias::Left
 9747            },
 9748        );
 9749
 9750        match self
 9751            .find_all_references_task_sources
 9752            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9753        {
 9754            Ok(_) => {
 9755                log::info!(
 9756                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9757                );
 9758                return None;
 9759            }
 9760            Err(i) => {
 9761                self.find_all_references_task_sources.insert(i, head_anchor);
 9762            }
 9763        }
 9764
 9765        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9766        let workspace = self.workspace()?;
 9767        let project = workspace.read(cx).project().clone();
 9768        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9769        Some(cx.spawn(|editor, mut cx| async move {
 9770            let _cleanup = defer({
 9771                let mut cx = cx.clone();
 9772                move || {
 9773                    let _ = editor.update(&mut cx, |editor, _| {
 9774                        if let Ok(i) =
 9775                            editor
 9776                                .find_all_references_task_sources
 9777                                .binary_search_by(|anchor| {
 9778                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9779                                })
 9780                        {
 9781                            editor.find_all_references_task_sources.remove(i);
 9782                        }
 9783                    });
 9784                }
 9785            });
 9786
 9787            let locations = references.await?;
 9788            if locations.is_empty() {
 9789                return anyhow::Ok(Navigated::No);
 9790            }
 9791
 9792            workspace.update(&mut cx, |workspace, cx| {
 9793                let title = locations
 9794                    .first()
 9795                    .as_ref()
 9796                    .map(|location| {
 9797                        let buffer = location.buffer.read(cx);
 9798                        format!(
 9799                            "References to `{}`",
 9800                            buffer
 9801                                .text_for_range(location.range.clone())
 9802                                .collect::<String>()
 9803                        )
 9804                    })
 9805                    .unwrap();
 9806                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9807                Navigated::Yes
 9808            })
 9809        }))
 9810    }
 9811
 9812    /// Opens a multibuffer with the given project locations in it
 9813    pub fn open_locations_in_multibuffer(
 9814        workspace: &mut Workspace,
 9815        mut locations: Vec<Location>,
 9816        title: String,
 9817        split: bool,
 9818        cx: &mut ViewContext<Workspace>,
 9819    ) {
 9820        // If there are multiple definitions, open them in a multibuffer
 9821        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9822        let mut locations = locations.into_iter().peekable();
 9823        let mut ranges_to_highlight = Vec::new();
 9824        let capability = workspace.project().read(cx).capability();
 9825
 9826        let excerpt_buffer = cx.new_model(|cx| {
 9827            let mut multibuffer = MultiBuffer::new(capability);
 9828            while let Some(location) = locations.next() {
 9829                let buffer = location.buffer.read(cx);
 9830                let mut ranges_for_buffer = Vec::new();
 9831                let range = location.range.to_offset(buffer);
 9832                ranges_for_buffer.push(range.clone());
 9833
 9834                while let Some(next_location) = locations.peek() {
 9835                    if next_location.buffer == location.buffer {
 9836                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9837                        locations.next();
 9838                    } else {
 9839                        break;
 9840                    }
 9841                }
 9842
 9843                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9844                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9845                    location.buffer.clone(),
 9846                    ranges_for_buffer,
 9847                    DEFAULT_MULTIBUFFER_CONTEXT,
 9848                    cx,
 9849                ))
 9850            }
 9851
 9852            multibuffer.with_title(title)
 9853        });
 9854
 9855        let editor = cx.new_view(|cx| {
 9856            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9857        });
 9858        editor.update(cx, |editor, cx| {
 9859            if let Some(first_range) = ranges_to_highlight.first() {
 9860                editor.change_selections(None, cx, |selections| {
 9861                    selections.clear_disjoint();
 9862                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9863                });
 9864            }
 9865            editor.highlight_background::<Self>(
 9866                &ranges_to_highlight,
 9867                |theme| theme.editor_highlighted_line_background,
 9868                cx,
 9869            );
 9870            editor.register_buffers_with_language_servers(cx);
 9871        });
 9872
 9873        let item = Box::new(editor);
 9874        let item_id = item.item_id();
 9875
 9876        if split {
 9877            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9878        } else {
 9879            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9880                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9881                    pane.close_current_preview_item(cx)
 9882                } else {
 9883                    None
 9884                }
 9885            });
 9886            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9887        }
 9888        workspace.active_pane().update(cx, |pane, cx| {
 9889            pane.set_preview_item_id(Some(item_id), cx);
 9890        });
 9891    }
 9892
 9893    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9894        use language::ToOffset as _;
 9895
 9896        let provider = self.semantics_provider.clone()?;
 9897        let selection = self.selections.newest_anchor().clone();
 9898        let (cursor_buffer, cursor_buffer_position) = self
 9899            .buffer
 9900            .read(cx)
 9901            .text_anchor_for_position(selection.head(), cx)?;
 9902        let (tail_buffer, cursor_buffer_position_end) = self
 9903            .buffer
 9904            .read(cx)
 9905            .text_anchor_for_position(selection.tail(), cx)?;
 9906        if tail_buffer != cursor_buffer {
 9907            return None;
 9908        }
 9909
 9910        let snapshot = cursor_buffer.read(cx).snapshot();
 9911        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9912        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9913        let prepare_rename = provider
 9914            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9915            .unwrap_or_else(|| Task::ready(Ok(None)));
 9916        drop(snapshot);
 9917
 9918        Some(cx.spawn(|this, mut cx| async move {
 9919            let rename_range = if let Some(range) = prepare_rename.await? {
 9920                Some(range)
 9921            } else {
 9922                this.update(&mut cx, |this, cx| {
 9923                    let buffer = this.buffer.read(cx).snapshot(cx);
 9924                    let mut buffer_highlights = this
 9925                        .document_highlights_for_position(selection.head(), &buffer)
 9926                        .filter(|highlight| {
 9927                            highlight.start.excerpt_id == selection.head().excerpt_id
 9928                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9929                        });
 9930                    buffer_highlights
 9931                        .next()
 9932                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9933                })?
 9934            };
 9935            if let Some(rename_range) = rename_range {
 9936                this.update(&mut cx, |this, cx| {
 9937                    let snapshot = cursor_buffer.read(cx).snapshot();
 9938                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9939                    let cursor_offset_in_rename_range =
 9940                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9941                    let cursor_offset_in_rename_range_end =
 9942                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9943
 9944                    this.take_rename(false, cx);
 9945                    let buffer = this.buffer.read(cx).read(cx);
 9946                    let cursor_offset = selection.head().to_offset(&buffer);
 9947                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9948                    let rename_end = rename_start + rename_buffer_range.len();
 9949                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9950                    let mut old_highlight_id = None;
 9951                    let old_name: Arc<str> = buffer
 9952                        .chunks(rename_start..rename_end, true)
 9953                        .map(|chunk| {
 9954                            if old_highlight_id.is_none() {
 9955                                old_highlight_id = chunk.syntax_highlight_id;
 9956                            }
 9957                            chunk.text
 9958                        })
 9959                        .collect::<String>()
 9960                        .into();
 9961
 9962                    drop(buffer);
 9963
 9964                    // Position the selection in the rename editor so that it matches the current selection.
 9965                    this.show_local_selections = false;
 9966                    let rename_editor = cx.new_view(|cx| {
 9967                        let mut editor = Editor::single_line(cx);
 9968                        editor.buffer.update(cx, |buffer, cx| {
 9969                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9970                        });
 9971                        let rename_selection_range = match cursor_offset_in_rename_range
 9972                            .cmp(&cursor_offset_in_rename_range_end)
 9973                        {
 9974                            Ordering::Equal => {
 9975                                editor.select_all(&SelectAll, cx);
 9976                                return editor;
 9977                            }
 9978                            Ordering::Less => {
 9979                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9980                            }
 9981                            Ordering::Greater => {
 9982                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9983                            }
 9984                        };
 9985                        if rename_selection_range.end > old_name.len() {
 9986                            editor.select_all(&SelectAll, cx);
 9987                        } else {
 9988                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9989                                s.select_ranges([rename_selection_range]);
 9990                            });
 9991                        }
 9992                        editor
 9993                    });
 9994                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
 9995                        if e == &EditorEvent::Focused {
 9996                            cx.emit(EditorEvent::FocusedIn)
 9997                        }
 9998                    })
 9999                    .detach();
10000
10001                    let write_highlights =
10002                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10003                    let read_highlights =
10004                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10005                    let ranges = write_highlights
10006                        .iter()
10007                        .flat_map(|(_, ranges)| ranges.iter())
10008                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10009                        .cloned()
10010                        .collect();
10011
10012                    this.highlight_text::<Rename>(
10013                        ranges,
10014                        HighlightStyle {
10015                            fade_out: Some(0.6),
10016                            ..Default::default()
10017                        },
10018                        cx,
10019                    );
10020                    let rename_focus_handle = rename_editor.focus_handle(cx);
10021                    cx.focus(&rename_focus_handle);
10022                    let block_id = this.insert_blocks(
10023                        [BlockProperties {
10024                            style: BlockStyle::Flex,
10025                            placement: BlockPlacement::Below(range.start),
10026                            height: 1,
10027                            render: Arc::new({
10028                                let rename_editor = rename_editor.clone();
10029                                move |cx: &mut BlockContext| {
10030                                    let mut text_style = cx.editor_style.text.clone();
10031                                    if let Some(highlight_style) = old_highlight_id
10032                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10033                                    {
10034                                        text_style = text_style.highlight(highlight_style);
10035                                    }
10036                                    div()
10037                                        .block_mouse_down()
10038                                        .pl(cx.anchor_x)
10039                                        .child(EditorElement::new(
10040                                            &rename_editor,
10041                                            EditorStyle {
10042                                                background: cx.theme().system().transparent,
10043                                                local_player: cx.editor_style.local_player,
10044                                                text: text_style,
10045                                                scrollbar_width: cx.editor_style.scrollbar_width,
10046                                                syntax: cx.editor_style.syntax.clone(),
10047                                                status: cx.editor_style.status.clone(),
10048                                                inlay_hints_style: HighlightStyle {
10049                                                    font_weight: Some(FontWeight::BOLD),
10050                                                    ..make_inlay_hints_style(cx)
10051                                                },
10052                                                inline_completion_styles: make_suggestion_styles(
10053                                                    cx,
10054                                                ),
10055                                                ..EditorStyle::default()
10056                                            },
10057                                        ))
10058                                        .into_any_element()
10059                                }
10060                            }),
10061                            priority: 0,
10062                        }],
10063                        Some(Autoscroll::fit()),
10064                        cx,
10065                    )[0];
10066                    this.pending_rename = Some(RenameState {
10067                        range,
10068                        old_name,
10069                        editor: rename_editor,
10070                        block_id,
10071                    });
10072                })?;
10073            }
10074
10075            Ok(())
10076        }))
10077    }
10078
10079    pub fn confirm_rename(
10080        &mut self,
10081        _: &ConfirmRename,
10082        cx: &mut ViewContext<Self>,
10083    ) -> Option<Task<Result<()>>> {
10084        let rename = self.take_rename(false, cx)?;
10085        let workspace = self.workspace()?.downgrade();
10086        let (buffer, start) = self
10087            .buffer
10088            .read(cx)
10089            .text_anchor_for_position(rename.range.start, cx)?;
10090        let (end_buffer, _) = self
10091            .buffer
10092            .read(cx)
10093            .text_anchor_for_position(rename.range.end, cx)?;
10094        if buffer != end_buffer {
10095            return None;
10096        }
10097
10098        let old_name = rename.old_name;
10099        let new_name = rename.editor.read(cx).text(cx);
10100
10101        let rename = self.semantics_provider.as_ref()?.perform_rename(
10102            &buffer,
10103            start,
10104            new_name.clone(),
10105            cx,
10106        )?;
10107
10108        Some(cx.spawn(|editor, mut cx| async move {
10109            let project_transaction = rename.await?;
10110            Self::open_project_transaction(
10111                &editor,
10112                workspace,
10113                project_transaction,
10114                format!("Rename: {}{}", old_name, new_name),
10115                cx.clone(),
10116            )
10117            .await?;
10118
10119            editor.update(&mut cx, |editor, cx| {
10120                editor.refresh_document_highlights(cx);
10121            })?;
10122            Ok(())
10123        }))
10124    }
10125
10126    fn take_rename(
10127        &mut self,
10128        moving_cursor: bool,
10129        cx: &mut ViewContext<Self>,
10130    ) -> Option<RenameState> {
10131        let rename = self.pending_rename.take()?;
10132        if rename.editor.focus_handle(cx).is_focused(cx) {
10133            cx.focus(&self.focus_handle);
10134        }
10135
10136        self.remove_blocks(
10137            [rename.block_id].into_iter().collect(),
10138            Some(Autoscroll::fit()),
10139            cx,
10140        );
10141        self.clear_highlights::<Rename>(cx);
10142        self.show_local_selections = true;
10143
10144        if moving_cursor {
10145            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10146                editor.selections.newest::<usize>(cx).head()
10147            });
10148
10149            // Update the selection to match the position of the selection inside
10150            // the rename editor.
10151            let snapshot = self.buffer.read(cx).read(cx);
10152            let rename_range = rename.range.to_offset(&snapshot);
10153            let cursor_in_editor = snapshot
10154                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10155                .min(rename_range.end);
10156            drop(snapshot);
10157
10158            self.change_selections(None, cx, |s| {
10159                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10160            });
10161        } else {
10162            self.refresh_document_highlights(cx);
10163        }
10164
10165        Some(rename)
10166    }
10167
10168    pub fn pending_rename(&self) -> Option<&RenameState> {
10169        self.pending_rename.as_ref()
10170    }
10171
10172    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10173        let project = match &self.project {
10174            Some(project) => project.clone(),
10175            None => return None,
10176        };
10177
10178        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10179    }
10180
10181    fn format_selections(
10182        &mut self,
10183        _: &FormatSelections,
10184        cx: &mut ViewContext<Self>,
10185    ) -> Option<Task<Result<()>>> {
10186        let project = match &self.project {
10187            Some(project) => project.clone(),
10188            None => return None,
10189        };
10190
10191        let selections = self
10192            .selections
10193            .all_adjusted(cx)
10194            .into_iter()
10195            .filter(|s| !s.is_empty())
10196            .collect_vec();
10197
10198        Some(self.perform_format(
10199            project,
10200            FormatTrigger::Manual,
10201            FormatTarget::Ranges(selections),
10202            cx,
10203        ))
10204    }
10205
10206    fn perform_format(
10207        &mut self,
10208        project: Model<Project>,
10209        trigger: FormatTrigger,
10210        target: FormatTarget,
10211        cx: &mut ViewContext<Self>,
10212    ) -> Task<Result<()>> {
10213        let buffer = self.buffer().clone();
10214        let mut buffers = buffer.read(cx).all_buffers();
10215        if trigger == FormatTrigger::Save {
10216            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10217        }
10218
10219        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10220        let format = project.update(cx, |project, cx| {
10221            project.format(buffers, true, trigger, target, cx)
10222        });
10223
10224        cx.spawn(|_, mut cx| async move {
10225            let transaction = futures::select_biased! {
10226                () = timeout => {
10227                    log::warn!("timed out waiting for formatting");
10228                    None
10229                }
10230                transaction = format.log_err().fuse() => transaction,
10231            };
10232
10233            buffer
10234                .update(&mut cx, |buffer, cx| {
10235                    if let Some(transaction) = transaction {
10236                        if !buffer.is_singleton() {
10237                            buffer.push_transaction(&transaction.0, cx);
10238                        }
10239                    }
10240
10241                    cx.notify();
10242                })
10243                .ok();
10244
10245            Ok(())
10246        })
10247    }
10248
10249    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10250        if let Some(project) = self.project.clone() {
10251            self.buffer.update(cx, |multi_buffer, cx| {
10252                project.update(cx, |project, cx| {
10253                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10254                });
10255            })
10256        }
10257    }
10258
10259    fn cancel_language_server_work(
10260        &mut self,
10261        _: &actions::CancelLanguageServerWork,
10262        cx: &mut ViewContext<Self>,
10263    ) {
10264        if let Some(project) = self.project.clone() {
10265            self.buffer.update(cx, |multi_buffer, cx| {
10266                project.update(cx, |project, cx| {
10267                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10268                });
10269            })
10270        }
10271    }
10272
10273    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10274        cx.show_character_palette();
10275    }
10276
10277    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10278        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10279            let buffer = self.buffer.read(cx).snapshot(cx);
10280            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10281            let is_valid = buffer
10282                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10283                .any(|entry| {
10284                    entry.diagnostic.is_primary
10285                        && !entry.range.is_empty()
10286                        && entry.range.start == primary_range_start
10287                        && entry.diagnostic.message == active_diagnostics.primary_message
10288                });
10289
10290            if is_valid != active_diagnostics.is_valid {
10291                active_diagnostics.is_valid = is_valid;
10292                let mut new_styles = HashMap::default();
10293                for (block_id, diagnostic) in &active_diagnostics.blocks {
10294                    new_styles.insert(
10295                        *block_id,
10296                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10297                    );
10298                }
10299                self.display_map.update(cx, |display_map, _cx| {
10300                    display_map.replace_blocks(new_styles)
10301                });
10302            }
10303        }
10304    }
10305
10306    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10307        self.dismiss_diagnostics(cx);
10308        let snapshot = self.snapshot(cx);
10309        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10310            let buffer = self.buffer.read(cx).snapshot(cx);
10311
10312            let mut primary_range = None;
10313            let mut primary_message = None;
10314            let mut group_end = Point::zero();
10315            let diagnostic_group = buffer
10316                .diagnostic_group::<MultiBufferPoint>(group_id)
10317                .filter_map(|entry| {
10318                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10319                        && (entry.range.start.row == entry.range.end.row
10320                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10321                    {
10322                        return None;
10323                    }
10324                    if entry.range.end > group_end {
10325                        group_end = entry.range.end;
10326                    }
10327                    if entry.diagnostic.is_primary {
10328                        primary_range = Some(entry.range.clone());
10329                        primary_message = Some(entry.diagnostic.message.clone());
10330                    }
10331                    Some(entry)
10332                })
10333                .collect::<Vec<_>>();
10334            let primary_range = primary_range?;
10335            let primary_message = primary_message?;
10336            let primary_range =
10337                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10338
10339            let blocks = display_map
10340                .insert_blocks(
10341                    diagnostic_group.iter().map(|entry| {
10342                        let diagnostic = entry.diagnostic.clone();
10343                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10344                        BlockProperties {
10345                            style: BlockStyle::Fixed,
10346                            placement: BlockPlacement::Below(
10347                                buffer.anchor_after(entry.range.start),
10348                            ),
10349                            height: message_height,
10350                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10351                            priority: 0,
10352                        }
10353                    }),
10354                    cx,
10355                )
10356                .into_iter()
10357                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10358                .collect();
10359
10360            Some(ActiveDiagnosticGroup {
10361                primary_range,
10362                primary_message,
10363                group_id,
10364                blocks,
10365                is_valid: true,
10366            })
10367        });
10368        self.active_diagnostics.is_some()
10369    }
10370
10371    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10372        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10373            self.display_map.update(cx, |display_map, cx| {
10374                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10375            });
10376            cx.notify();
10377        }
10378    }
10379
10380    pub fn set_selections_from_remote(
10381        &mut self,
10382        selections: Vec<Selection<Anchor>>,
10383        pending_selection: Option<Selection<Anchor>>,
10384        cx: &mut ViewContext<Self>,
10385    ) {
10386        let old_cursor_position = self.selections.newest_anchor().head();
10387        self.selections.change_with(cx, |s| {
10388            s.select_anchors(selections);
10389            if let Some(pending_selection) = pending_selection {
10390                s.set_pending(pending_selection, SelectMode::Character);
10391            } else {
10392                s.clear_pending();
10393            }
10394        });
10395        self.selections_did_change(false, &old_cursor_position, true, cx);
10396    }
10397
10398    fn push_to_selection_history(&mut self) {
10399        self.selection_history.push(SelectionHistoryEntry {
10400            selections: self.selections.disjoint_anchors(),
10401            select_next_state: self.select_next_state.clone(),
10402            select_prev_state: self.select_prev_state.clone(),
10403            add_selections_state: self.add_selections_state.clone(),
10404        });
10405    }
10406
10407    pub fn transact(
10408        &mut self,
10409        cx: &mut ViewContext<Self>,
10410        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10411    ) -> Option<TransactionId> {
10412        self.start_transaction_at(Instant::now(), cx);
10413        update(self, cx);
10414        self.end_transaction_at(Instant::now(), cx)
10415    }
10416
10417    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10418        self.end_selection(cx);
10419        if let Some(tx_id) = self
10420            .buffer
10421            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10422        {
10423            self.selection_history
10424                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10425            cx.emit(EditorEvent::TransactionBegun {
10426                transaction_id: tx_id,
10427            })
10428        }
10429    }
10430
10431    pub fn end_transaction_at(
10432        &mut self,
10433        now: Instant,
10434        cx: &mut ViewContext<Self>,
10435    ) -> Option<TransactionId> {
10436        if let Some(transaction_id) = self
10437            .buffer
10438            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10439        {
10440            if let Some((_, end_selections)) =
10441                self.selection_history.transaction_mut(transaction_id)
10442            {
10443                *end_selections = Some(self.selections.disjoint_anchors());
10444            } else {
10445                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10446            }
10447
10448            cx.emit(EditorEvent::Edited { transaction_id });
10449            Some(transaction_id)
10450        } else {
10451            None
10452        }
10453    }
10454
10455    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10456        if self.is_singleton(cx) {
10457            let selection = self.selections.newest::<Point>(cx);
10458
10459            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10460            let range = if selection.is_empty() {
10461                let point = selection.head().to_display_point(&display_map);
10462                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10463                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10464                    .to_point(&display_map);
10465                start..end
10466            } else {
10467                selection.range()
10468            };
10469            if display_map.folds_in_range(range).next().is_some() {
10470                self.unfold_lines(&Default::default(), cx)
10471            } else {
10472                self.fold(&Default::default(), cx)
10473            }
10474        } else {
10475            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10476            let mut toggled_buffers = HashSet::default();
10477            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10478                self.selections
10479                    .disjoint_anchors()
10480                    .into_iter()
10481                    .map(|selection| selection.range()),
10482            ) {
10483                let buffer_id = buffer_snapshot.remote_id();
10484                if toggled_buffers.insert(buffer_id) {
10485                    if self.buffer_folded(buffer_id, cx) {
10486                        self.unfold_buffer(buffer_id, cx);
10487                    } else {
10488                        self.fold_buffer(buffer_id, cx);
10489                    }
10490                }
10491            }
10492        }
10493    }
10494
10495    pub fn toggle_fold_recursive(
10496        &mut self,
10497        _: &actions::ToggleFoldRecursive,
10498        cx: &mut ViewContext<Self>,
10499    ) {
10500        let selection = self.selections.newest::<Point>(cx);
10501
10502        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10503        let range = if selection.is_empty() {
10504            let point = selection.head().to_display_point(&display_map);
10505            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10506            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10507                .to_point(&display_map);
10508            start..end
10509        } else {
10510            selection.range()
10511        };
10512        if display_map.folds_in_range(range).next().is_some() {
10513            self.unfold_recursive(&Default::default(), cx)
10514        } else {
10515            self.fold_recursive(&Default::default(), cx)
10516        }
10517    }
10518
10519    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10520        if self.is_singleton(cx) {
10521            let mut to_fold = Vec::new();
10522            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10523            let selections = self.selections.all_adjusted(cx);
10524
10525            for selection in selections {
10526                let range = selection.range().sorted();
10527                let buffer_start_row = range.start.row;
10528
10529                if range.start.row != range.end.row {
10530                    let mut found = false;
10531                    let mut row = range.start.row;
10532                    while row <= range.end.row {
10533                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10534                        {
10535                            found = true;
10536                            row = crease.range().end.row + 1;
10537                            to_fold.push(crease);
10538                        } else {
10539                            row += 1
10540                        }
10541                    }
10542                    if found {
10543                        continue;
10544                    }
10545                }
10546
10547                for row in (0..=range.start.row).rev() {
10548                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10549                        if crease.range().end.row >= buffer_start_row {
10550                            to_fold.push(crease);
10551                            if row <= range.start.row {
10552                                break;
10553                            }
10554                        }
10555                    }
10556                }
10557            }
10558
10559            self.fold_creases(to_fold, true, cx);
10560        } else {
10561            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10562            let mut folded_buffers = HashSet::default();
10563            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10564                self.selections
10565                    .disjoint_anchors()
10566                    .into_iter()
10567                    .map(|selection| selection.range()),
10568            ) {
10569                let buffer_id = buffer_snapshot.remote_id();
10570                if folded_buffers.insert(buffer_id) {
10571                    self.fold_buffer(buffer_id, cx);
10572                }
10573            }
10574        }
10575    }
10576
10577    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10578        if !self.buffer.read(cx).is_singleton() {
10579            return;
10580        }
10581
10582        let fold_at_level = fold_at.level;
10583        let snapshot = self.buffer.read(cx).snapshot(cx);
10584        let mut to_fold = Vec::new();
10585        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10586
10587        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10588            while start_row < end_row {
10589                match self
10590                    .snapshot(cx)
10591                    .crease_for_buffer_row(MultiBufferRow(start_row))
10592                {
10593                    Some(crease) => {
10594                        let nested_start_row = crease.range().start.row + 1;
10595                        let nested_end_row = crease.range().end.row;
10596
10597                        if current_level < fold_at_level {
10598                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10599                        } else if current_level == fold_at_level {
10600                            to_fold.push(crease);
10601                        }
10602
10603                        start_row = nested_end_row + 1;
10604                    }
10605                    None => start_row += 1,
10606                }
10607            }
10608        }
10609
10610        self.fold_creases(to_fold, true, cx);
10611    }
10612
10613    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10614        if self.buffer.read(cx).is_singleton() {
10615            let mut fold_ranges = Vec::new();
10616            let snapshot = self.buffer.read(cx).snapshot(cx);
10617
10618            for row in 0..snapshot.max_row().0 {
10619                if let Some(foldable_range) =
10620                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10621                {
10622                    fold_ranges.push(foldable_range);
10623                }
10624            }
10625
10626            self.fold_creases(fold_ranges, true, cx);
10627        } else {
10628            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10629                editor
10630                    .update(&mut cx, |editor, cx| {
10631                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10632                            editor.fold_buffer(buffer_id, cx);
10633                        }
10634                    })
10635                    .ok();
10636            });
10637        }
10638    }
10639
10640    pub fn fold_function_bodies(
10641        &mut self,
10642        _: &actions::FoldFunctionBodies,
10643        cx: &mut ViewContext<Self>,
10644    ) {
10645        let snapshot = self.buffer.read(cx).snapshot(cx);
10646        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10647            return;
10648        };
10649        let creases = buffer
10650            .function_body_fold_ranges(0..buffer.len())
10651            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10652            .collect();
10653
10654        self.fold_creases(creases, true, cx);
10655    }
10656
10657    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10658        let mut to_fold = Vec::new();
10659        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10660        let selections = self.selections.all_adjusted(cx);
10661
10662        for selection in selections {
10663            let range = selection.range().sorted();
10664            let buffer_start_row = range.start.row;
10665
10666            if range.start.row != range.end.row {
10667                let mut found = false;
10668                for row in range.start.row..=range.end.row {
10669                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10670                        found = true;
10671                        to_fold.push(crease);
10672                    }
10673                }
10674                if found {
10675                    continue;
10676                }
10677            }
10678
10679            for row in (0..=range.start.row).rev() {
10680                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10681                    if crease.range().end.row >= buffer_start_row {
10682                        to_fold.push(crease);
10683                    } else {
10684                        break;
10685                    }
10686                }
10687            }
10688        }
10689
10690        self.fold_creases(to_fold, true, cx);
10691    }
10692
10693    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10694        let buffer_row = fold_at.buffer_row;
10695        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10696
10697        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10698            let autoscroll = self
10699                .selections
10700                .all::<Point>(cx)
10701                .iter()
10702                .any(|selection| crease.range().overlaps(&selection.range()));
10703
10704            self.fold_creases(vec![crease], autoscroll, cx);
10705        }
10706    }
10707
10708    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10709        if self.is_singleton(cx) {
10710            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10711            let buffer = &display_map.buffer_snapshot;
10712            let selections = self.selections.all::<Point>(cx);
10713            let ranges = selections
10714                .iter()
10715                .map(|s| {
10716                    let range = s.display_range(&display_map).sorted();
10717                    let mut start = range.start.to_point(&display_map);
10718                    let mut end = range.end.to_point(&display_map);
10719                    start.column = 0;
10720                    end.column = buffer.line_len(MultiBufferRow(end.row));
10721                    start..end
10722                })
10723                .collect::<Vec<_>>();
10724
10725            self.unfold_ranges(&ranges, true, true, cx);
10726        } else {
10727            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10728            let mut unfolded_buffers = HashSet::default();
10729            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10730                self.selections
10731                    .disjoint_anchors()
10732                    .into_iter()
10733                    .map(|selection| selection.range()),
10734            ) {
10735                let buffer_id = buffer_snapshot.remote_id();
10736                if unfolded_buffers.insert(buffer_id) {
10737                    self.unfold_buffer(buffer_id, cx);
10738                }
10739            }
10740        }
10741    }
10742
10743    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10744        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10745        let selections = self.selections.all::<Point>(cx);
10746        let ranges = selections
10747            .iter()
10748            .map(|s| {
10749                let mut range = s.display_range(&display_map).sorted();
10750                *range.start.column_mut() = 0;
10751                *range.end.column_mut() = display_map.line_len(range.end.row());
10752                let start = range.start.to_point(&display_map);
10753                let end = range.end.to_point(&display_map);
10754                start..end
10755            })
10756            .collect::<Vec<_>>();
10757
10758        self.unfold_ranges(&ranges, true, true, cx);
10759    }
10760
10761    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10762        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10763
10764        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10765            ..Point::new(
10766                unfold_at.buffer_row.0,
10767                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10768            );
10769
10770        let autoscroll = self
10771            .selections
10772            .all::<Point>(cx)
10773            .iter()
10774            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10775
10776        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10777    }
10778
10779    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10780        if self.buffer.read(cx).is_singleton() {
10781            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10782            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10783        } else {
10784            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10785                editor
10786                    .update(&mut cx, |editor, cx| {
10787                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10788                            editor.unfold_buffer(buffer_id, cx);
10789                        }
10790                    })
10791                    .ok();
10792            });
10793        }
10794    }
10795
10796    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10797        let selections = self.selections.all::<Point>(cx);
10798        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10799        let line_mode = self.selections.line_mode;
10800        let ranges = selections
10801            .into_iter()
10802            .map(|s| {
10803                if line_mode {
10804                    let start = Point::new(s.start.row, 0);
10805                    let end = Point::new(
10806                        s.end.row,
10807                        display_map
10808                            .buffer_snapshot
10809                            .line_len(MultiBufferRow(s.end.row)),
10810                    );
10811                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10812                } else {
10813                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10814                }
10815            })
10816            .collect::<Vec<_>>();
10817        self.fold_creases(ranges, true, cx);
10818    }
10819
10820    pub fn fold_creases<T: ToOffset + Clone>(
10821        &mut self,
10822        creases: Vec<Crease<T>>,
10823        auto_scroll: bool,
10824        cx: &mut ViewContext<Self>,
10825    ) {
10826        if creases.is_empty() {
10827            return;
10828        }
10829
10830        let mut buffers_affected = HashSet::default();
10831        let multi_buffer = self.buffer().read(cx);
10832        for crease in &creases {
10833            if let Some((_, buffer, _)) =
10834                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10835            {
10836                buffers_affected.insert(buffer.read(cx).remote_id());
10837            };
10838        }
10839
10840        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10841
10842        if auto_scroll {
10843            self.request_autoscroll(Autoscroll::fit(), cx);
10844        }
10845
10846        for buffer_id in buffers_affected {
10847            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10848        }
10849
10850        cx.notify();
10851
10852        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10853            // Clear diagnostics block when folding a range that contains it.
10854            let snapshot = self.snapshot(cx);
10855            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10856                drop(snapshot);
10857                self.active_diagnostics = Some(active_diagnostics);
10858                self.dismiss_diagnostics(cx);
10859            } else {
10860                self.active_diagnostics = Some(active_diagnostics);
10861            }
10862        }
10863
10864        self.scrollbar_marker_state.dirty = true;
10865    }
10866
10867    /// Removes any folds whose ranges intersect any of the given ranges.
10868    pub fn unfold_ranges<T: ToOffset + Clone>(
10869        &mut self,
10870        ranges: &[Range<T>],
10871        inclusive: bool,
10872        auto_scroll: bool,
10873        cx: &mut ViewContext<Self>,
10874    ) {
10875        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10876            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10877        });
10878    }
10879
10880    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10881        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10882            return;
10883        }
10884        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10885            return;
10886        };
10887        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10888        self.display_map
10889            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10890        cx.emit(EditorEvent::BufferFoldToggled {
10891            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10892            folded: true,
10893        });
10894        cx.notify();
10895    }
10896
10897    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10898        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10899            return;
10900        }
10901        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10902            return;
10903        };
10904        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10905        self.display_map.update(cx, |display_map, cx| {
10906            display_map.unfold_buffer(buffer_id, cx);
10907        });
10908        cx.emit(EditorEvent::BufferFoldToggled {
10909            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10910            folded: false,
10911        });
10912        cx.notify();
10913    }
10914
10915    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10916        self.display_map.read(cx).buffer_folded(buffer)
10917    }
10918
10919    /// Removes any folds with the given ranges.
10920    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10921        &mut self,
10922        ranges: &[Range<T>],
10923        type_id: TypeId,
10924        auto_scroll: bool,
10925        cx: &mut ViewContext<Self>,
10926    ) {
10927        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10928            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10929        });
10930    }
10931
10932    fn remove_folds_with<T: ToOffset + Clone>(
10933        &mut self,
10934        ranges: &[Range<T>],
10935        auto_scroll: bool,
10936        cx: &mut ViewContext<Self>,
10937        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10938    ) {
10939        if ranges.is_empty() {
10940            return;
10941        }
10942
10943        let mut buffers_affected = HashSet::default();
10944        let multi_buffer = self.buffer().read(cx);
10945        for range in ranges {
10946            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10947                buffers_affected.insert(buffer.read(cx).remote_id());
10948            };
10949        }
10950
10951        self.display_map.update(cx, update);
10952
10953        if auto_scroll {
10954            self.request_autoscroll(Autoscroll::fit(), cx);
10955        }
10956
10957        for buffer_id in buffers_affected {
10958            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10959        }
10960
10961        cx.notify();
10962        self.scrollbar_marker_state.dirty = true;
10963        self.active_indent_guides_state.dirty = true;
10964    }
10965
10966    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10967        self.display_map.read(cx).fold_placeholder.clone()
10968    }
10969
10970    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10971        if hovered != self.gutter_hovered {
10972            self.gutter_hovered = hovered;
10973            cx.notify();
10974        }
10975    }
10976
10977    pub fn insert_blocks(
10978        &mut self,
10979        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10980        autoscroll: Option<Autoscroll>,
10981        cx: &mut ViewContext<Self>,
10982    ) -> Vec<CustomBlockId> {
10983        let blocks = self
10984            .display_map
10985            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10986        if let Some(autoscroll) = autoscroll {
10987            self.request_autoscroll(autoscroll, cx);
10988        }
10989        cx.notify();
10990        blocks
10991    }
10992
10993    pub fn resize_blocks(
10994        &mut self,
10995        heights: HashMap<CustomBlockId, u32>,
10996        autoscroll: Option<Autoscroll>,
10997        cx: &mut ViewContext<Self>,
10998    ) {
10999        self.display_map
11000            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11001        if let Some(autoscroll) = autoscroll {
11002            self.request_autoscroll(autoscroll, cx);
11003        }
11004        cx.notify();
11005    }
11006
11007    pub fn replace_blocks(
11008        &mut self,
11009        renderers: HashMap<CustomBlockId, RenderBlock>,
11010        autoscroll: Option<Autoscroll>,
11011        cx: &mut ViewContext<Self>,
11012    ) {
11013        self.display_map
11014            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11015        if let Some(autoscroll) = autoscroll {
11016            self.request_autoscroll(autoscroll, cx);
11017        }
11018        cx.notify();
11019    }
11020
11021    pub fn remove_blocks(
11022        &mut self,
11023        block_ids: HashSet<CustomBlockId>,
11024        autoscroll: Option<Autoscroll>,
11025        cx: &mut ViewContext<Self>,
11026    ) {
11027        self.display_map.update(cx, |display_map, cx| {
11028            display_map.remove_blocks(block_ids, cx)
11029        });
11030        if let Some(autoscroll) = autoscroll {
11031            self.request_autoscroll(autoscroll, cx);
11032        }
11033        cx.notify();
11034    }
11035
11036    pub fn row_for_block(
11037        &self,
11038        block_id: CustomBlockId,
11039        cx: &mut ViewContext<Self>,
11040    ) -> Option<DisplayRow> {
11041        self.display_map
11042            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11043    }
11044
11045    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11046        self.focused_block = Some(focused_block);
11047    }
11048
11049    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11050        self.focused_block.take()
11051    }
11052
11053    pub fn insert_creases(
11054        &mut self,
11055        creases: impl IntoIterator<Item = Crease<Anchor>>,
11056        cx: &mut ViewContext<Self>,
11057    ) -> Vec<CreaseId> {
11058        self.display_map
11059            .update(cx, |map, cx| map.insert_creases(creases, cx))
11060    }
11061
11062    pub fn remove_creases(
11063        &mut self,
11064        ids: impl IntoIterator<Item = CreaseId>,
11065        cx: &mut ViewContext<Self>,
11066    ) {
11067        self.display_map
11068            .update(cx, |map, cx| map.remove_creases(ids, cx));
11069    }
11070
11071    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11072        self.display_map
11073            .update(cx, |map, cx| map.snapshot(cx))
11074            .longest_row()
11075    }
11076
11077    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11078        self.display_map
11079            .update(cx, |map, cx| map.snapshot(cx))
11080            .max_point()
11081    }
11082
11083    pub fn text(&self, cx: &AppContext) -> String {
11084        self.buffer.read(cx).read(cx).text()
11085    }
11086
11087    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11088        let text = self.text(cx);
11089        let text = text.trim();
11090
11091        if text.is_empty() {
11092            return None;
11093        }
11094
11095        Some(text.to_string())
11096    }
11097
11098    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11099        self.transact(cx, |this, cx| {
11100            this.buffer
11101                .read(cx)
11102                .as_singleton()
11103                .expect("you can only call set_text on editors for singleton buffers")
11104                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11105        });
11106    }
11107
11108    pub fn display_text(&self, cx: &mut AppContext) -> String {
11109        self.display_map
11110            .update(cx, |map, cx| map.snapshot(cx))
11111            .text()
11112    }
11113
11114    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11115        let mut wrap_guides = smallvec::smallvec![];
11116
11117        if self.show_wrap_guides == Some(false) {
11118            return wrap_guides;
11119        }
11120
11121        let settings = self.buffer.read(cx).settings_at(0, cx);
11122        if settings.show_wrap_guides {
11123            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11124                wrap_guides.push((soft_wrap as usize, true));
11125            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11126                wrap_guides.push((soft_wrap as usize, true));
11127            }
11128            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11129        }
11130
11131        wrap_guides
11132    }
11133
11134    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11135        let settings = self.buffer.read(cx).settings_at(0, cx);
11136        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11137        match mode {
11138            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11139                SoftWrap::None
11140            }
11141            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11142            language_settings::SoftWrap::PreferredLineLength => {
11143                SoftWrap::Column(settings.preferred_line_length)
11144            }
11145            language_settings::SoftWrap::Bounded => {
11146                SoftWrap::Bounded(settings.preferred_line_length)
11147            }
11148        }
11149    }
11150
11151    pub fn set_soft_wrap_mode(
11152        &mut self,
11153        mode: language_settings::SoftWrap,
11154        cx: &mut ViewContext<Self>,
11155    ) {
11156        self.soft_wrap_mode_override = Some(mode);
11157        cx.notify();
11158    }
11159
11160    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11161        self.text_style_refinement = Some(style);
11162    }
11163
11164    /// called by the Element so we know what style we were most recently rendered with.
11165    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11166        let rem_size = cx.rem_size();
11167        self.display_map.update(cx, |map, cx| {
11168            map.set_font(
11169                style.text.font(),
11170                style.text.font_size.to_pixels(rem_size),
11171                cx,
11172            )
11173        });
11174        self.style = Some(style);
11175    }
11176
11177    pub fn style(&self) -> Option<&EditorStyle> {
11178        self.style.as_ref()
11179    }
11180
11181    // Called by the element. This method is not designed to be called outside of the editor
11182    // element's layout code because it does not notify when rewrapping is computed synchronously.
11183    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11184        self.display_map
11185            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11186    }
11187
11188    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11189        if self.soft_wrap_mode_override.is_some() {
11190            self.soft_wrap_mode_override.take();
11191        } else {
11192            let soft_wrap = match self.soft_wrap_mode(cx) {
11193                SoftWrap::GitDiff => return,
11194                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11195                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11196                    language_settings::SoftWrap::None
11197                }
11198            };
11199            self.soft_wrap_mode_override = Some(soft_wrap);
11200        }
11201        cx.notify();
11202    }
11203
11204    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11205        let Some(workspace) = self.workspace() else {
11206            return;
11207        };
11208        let fs = workspace.read(cx).app_state().fs.clone();
11209        let current_show = TabBarSettings::get_global(cx).show;
11210        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11211            setting.show = Some(!current_show);
11212        });
11213    }
11214
11215    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11216        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11217            self.buffer
11218                .read(cx)
11219                .settings_at(0, cx)
11220                .indent_guides
11221                .enabled
11222        });
11223        self.show_indent_guides = Some(!currently_enabled);
11224        cx.notify();
11225    }
11226
11227    fn should_show_indent_guides(&self) -> Option<bool> {
11228        self.show_indent_guides
11229    }
11230
11231    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11232        let mut editor_settings = EditorSettings::get_global(cx).clone();
11233        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11234        EditorSettings::override_global(editor_settings, cx);
11235    }
11236
11237    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11238        self.use_relative_line_numbers
11239            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11240    }
11241
11242    pub fn toggle_relative_line_numbers(
11243        &mut self,
11244        _: &ToggleRelativeLineNumbers,
11245        cx: &mut ViewContext<Self>,
11246    ) {
11247        let is_relative = self.should_use_relative_line_numbers(cx);
11248        self.set_relative_line_number(Some(!is_relative), cx)
11249    }
11250
11251    pub fn set_relative_line_number(
11252        &mut self,
11253        is_relative: Option<bool>,
11254        cx: &mut ViewContext<Self>,
11255    ) {
11256        self.use_relative_line_numbers = is_relative;
11257        cx.notify();
11258    }
11259
11260    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11261        self.show_gutter = show_gutter;
11262        cx.notify();
11263    }
11264
11265    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11266        self.show_scrollbars = show_scrollbars;
11267        cx.notify();
11268    }
11269
11270    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11271        self.show_line_numbers = Some(show_line_numbers);
11272        cx.notify();
11273    }
11274
11275    pub fn set_show_git_diff_gutter(
11276        &mut self,
11277        show_git_diff_gutter: bool,
11278        cx: &mut ViewContext<Self>,
11279    ) {
11280        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11281        cx.notify();
11282    }
11283
11284    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11285        self.show_code_actions = Some(show_code_actions);
11286        cx.notify();
11287    }
11288
11289    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11290        self.show_runnables = Some(show_runnables);
11291        cx.notify();
11292    }
11293
11294    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11295        if self.display_map.read(cx).masked != masked {
11296            self.display_map.update(cx, |map, _| map.masked = masked);
11297        }
11298        cx.notify()
11299    }
11300
11301    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11302        self.show_wrap_guides = Some(show_wrap_guides);
11303        cx.notify();
11304    }
11305
11306    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11307        self.show_indent_guides = Some(show_indent_guides);
11308        cx.notify();
11309    }
11310
11311    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11312        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11313            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11314                if let Some(dir) = file.abs_path(cx).parent() {
11315                    return Some(dir.to_owned());
11316                }
11317            }
11318
11319            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11320                return Some(project_path.path.to_path_buf());
11321            }
11322        }
11323
11324        None
11325    }
11326
11327    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11328        self.active_excerpt(cx)?
11329            .1
11330            .read(cx)
11331            .file()
11332            .and_then(|f| f.as_local())
11333    }
11334
11335    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11336        if let Some(target) = self.target_file(cx) {
11337            cx.reveal_path(&target.abs_path(cx));
11338        }
11339    }
11340
11341    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11342        if let Some(file) = self.target_file(cx) {
11343            if let Some(path) = file.abs_path(cx).to_str() {
11344                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11345            }
11346        }
11347    }
11348
11349    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11350        if let Some(file) = self.target_file(cx) {
11351            if let Some(path) = file.path().to_str() {
11352                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11353            }
11354        }
11355    }
11356
11357    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11358        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11359
11360        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11361            self.start_git_blame(true, cx);
11362        }
11363
11364        cx.notify();
11365    }
11366
11367    pub fn toggle_git_blame_inline(
11368        &mut self,
11369        _: &ToggleGitBlameInline,
11370        cx: &mut ViewContext<Self>,
11371    ) {
11372        self.toggle_git_blame_inline_internal(true, cx);
11373        cx.notify();
11374    }
11375
11376    pub fn git_blame_inline_enabled(&self) -> bool {
11377        self.git_blame_inline_enabled
11378    }
11379
11380    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11381        self.show_selection_menu = self
11382            .show_selection_menu
11383            .map(|show_selections_menu| !show_selections_menu)
11384            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11385
11386        cx.notify();
11387    }
11388
11389    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11390        self.show_selection_menu
11391            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11392    }
11393
11394    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11395        if let Some(project) = self.project.as_ref() {
11396            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11397                return;
11398            };
11399
11400            if buffer.read(cx).file().is_none() {
11401                return;
11402            }
11403
11404            let focused = self.focus_handle(cx).contains_focused(cx);
11405
11406            let project = project.clone();
11407            let blame =
11408                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11409            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11410            self.blame = Some(blame);
11411        }
11412    }
11413
11414    fn toggle_git_blame_inline_internal(
11415        &mut self,
11416        user_triggered: bool,
11417        cx: &mut ViewContext<Self>,
11418    ) {
11419        if self.git_blame_inline_enabled {
11420            self.git_blame_inline_enabled = false;
11421            self.show_git_blame_inline = false;
11422            self.show_git_blame_inline_delay_task.take();
11423        } else {
11424            self.git_blame_inline_enabled = true;
11425            self.start_git_blame_inline(user_triggered, cx);
11426        }
11427
11428        cx.notify();
11429    }
11430
11431    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11432        self.start_git_blame(user_triggered, cx);
11433
11434        if ProjectSettings::get_global(cx)
11435            .git
11436            .inline_blame_delay()
11437            .is_some()
11438        {
11439            self.start_inline_blame_timer(cx);
11440        } else {
11441            self.show_git_blame_inline = true
11442        }
11443    }
11444
11445    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11446        self.blame.as_ref()
11447    }
11448
11449    pub fn show_git_blame_gutter(&self) -> bool {
11450        self.show_git_blame_gutter
11451    }
11452
11453    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11454        self.show_git_blame_gutter && self.has_blame_entries(cx)
11455    }
11456
11457    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11458        self.show_git_blame_inline
11459            && self.focus_handle.is_focused(cx)
11460            && !self.newest_selection_head_on_empty_line(cx)
11461            && self.has_blame_entries(cx)
11462    }
11463
11464    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11465        self.blame()
11466            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11467    }
11468
11469    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11470        let cursor_anchor = self.selections.newest_anchor().head();
11471
11472        let snapshot = self.buffer.read(cx).snapshot(cx);
11473        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11474
11475        snapshot.line_len(buffer_row) == 0
11476    }
11477
11478    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11479        let buffer_and_selection = maybe!({
11480            let selection = self.selections.newest::<Point>(cx);
11481            let selection_range = selection.range();
11482
11483            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11484                (buffer, selection_range.start.row..selection_range.end.row)
11485            } else {
11486                let buffer_ranges = self
11487                    .buffer()
11488                    .read(cx)
11489                    .range_to_buffer_ranges(selection_range, cx);
11490
11491                let (buffer, range, _) = if selection.reversed {
11492                    buffer_ranges.first()
11493                } else {
11494                    buffer_ranges.last()
11495                }?;
11496
11497                let snapshot = buffer.read(cx).snapshot();
11498                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11499                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11500                (buffer.clone(), selection)
11501            };
11502
11503            Some((buffer, selection))
11504        });
11505
11506        let Some((buffer, selection)) = buffer_and_selection else {
11507            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11508        };
11509
11510        let Some(project) = self.project.as_ref() else {
11511            return Task::ready(Err(anyhow!("editor does not have project")));
11512        };
11513
11514        project.update(cx, |project, cx| {
11515            project.get_permalink_to_line(&buffer, selection, cx)
11516        })
11517    }
11518
11519    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11520        let permalink_task = self.get_permalink_to_line(cx);
11521        let workspace = self.workspace();
11522
11523        cx.spawn(|_, mut cx| async move {
11524            match permalink_task.await {
11525                Ok(permalink) => {
11526                    cx.update(|cx| {
11527                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11528                    })
11529                    .ok();
11530                }
11531                Err(err) => {
11532                    let message = format!("Failed to copy permalink: {err}");
11533
11534                    Err::<(), anyhow::Error>(err).log_err();
11535
11536                    if let Some(workspace) = workspace {
11537                        workspace
11538                            .update(&mut cx, |workspace, cx| {
11539                                struct CopyPermalinkToLine;
11540
11541                                workspace.show_toast(
11542                                    Toast::new(
11543                                        NotificationId::unique::<CopyPermalinkToLine>(),
11544                                        message,
11545                                    ),
11546                                    cx,
11547                                )
11548                            })
11549                            .ok();
11550                    }
11551                }
11552            }
11553        })
11554        .detach();
11555    }
11556
11557    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11558        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11559        if let Some(file) = self.target_file(cx) {
11560            if let Some(path) = file.path().to_str() {
11561                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11562            }
11563        }
11564    }
11565
11566    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11567        let permalink_task = self.get_permalink_to_line(cx);
11568        let workspace = self.workspace();
11569
11570        cx.spawn(|_, mut cx| async move {
11571            match permalink_task.await {
11572                Ok(permalink) => {
11573                    cx.update(|cx| {
11574                        cx.open_url(permalink.as_ref());
11575                    })
11576                    .ok();
11577                }
11578                Err(err) => {
11579                    let message = format!("Failed to open permalink: {err}");
11580
11581                    Err::<(), anyhow::Error>(err).log_err();
11582
11583                    if let Some(workspace) = workspace {
11584                        workspace
11585                            .update(&mut cx, |workspace, cx| {
11586                                struct OpenPermalinkToLine;
11587
11588                                workspace.show_toast(
11589                                    Toast::new(
11590                                        NotificationId::unique::<OpenPermalinkToLine>(),
11591                                        message,
11592                                    ),
11593                                    cx,
11594                                )
11595                            })
11596                            .ok();
11597                    }
11598                }
11599            }
11600        })
11601        .detach();
11602    }
11603
11604    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11605        self.insert_uuid(UuidVersion::V4, cx);
11606    }
11607
11608    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11609        self.insert_uuid(UuidVersion::V7, cx);
11610    }
11611
11612    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11613        self.transact(cx, |this, cx| {
11614            let edits = this
11615                .selections
11616                .all::<Point>(cx)
11617                .into_iter()
11618                .map(|selection| {
11619                    let uuid = match version {
11620                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11621                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11622                    };
11623
11624                    (selection.range(), uuid.to_string())
11625                });
11626            this.edit(edits, cx);
11627            this.refresh_inline_completion(true, false, cx);
11628        });
11629    }
11630
11631    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11632    /// last highlight added will be used.
11633    ///
11634    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11635    pub fn highlight_rows<T: 'static>(
11636        &mut self,
11637        range: Range<Anchor>,
11638        color: Hsla,
11639        should_autoscroll: bool,
11640        cx: &mut ViewContext<Self>,
11641    ) {
11642        let snapshot = self.buffer().read(cx).snapshot(cx);
11643        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11644        let ix = row_highlights.binary_search_by(|highlight| {
11645            Ordering::Equal
11646                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11647                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11648        });
11649
11650        if let Err(mut ix) = ix {
11651            let index = post_inc(&mut self.highlight_order);
11652
11653            // If this range intersects with the preceding highlight, then merge it with
11654            // the preceding highlight. Otherwise insert a new highlight.
11655            let mut merged = false;
11656            if ix > 0 {
11657                let prev_highlight = &mut row_highlights[ix - 1];
11658                if prev_highlight
11659                    .range
11660                    .end
11661                    .cmp(&range.start, &snapshot)
11662                    .is_ge()
11663                {
11664                    ix -= 1;
11665                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11666                        prev_highlight.range.end = range.end;
11667                    }
11668                    merged = true;
11669                    prev_highlight.index = index;
11670                    prev_highlight.color = color;
11671                    prev_highlight.should_autoscroll = should_autoscroll;
11672                }
11673            }
11674
11675            if !merged {
11676                row_highlights.insert(
11677                    ix,
11678                    RowHighlight {
11679                        range: range.clone(),
11680                        index,
11681                        color,
11682                        should_autoscroll,
11683                    },
11684                );
11685            }
11686
11687            // If any of the following highlights intersect with this one, merge them.
11688            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11689                let highlight = &row_highlights[ix];
11690                if next_highlight
11691                    .range
11692                    .start
11693                    .cmp(&highlight.range.end, &snapshot)
11694                    .is_le()
11695                {
11696                    if next_highlight
11697                        .range
11698                        .end
11699                        .cmp(&highlight.range.end, &snapshot)
11700                        .is_gt()
11701                    {
11702                        row_highlights[ix].range.end = next_highlight.range.end;
11703                    }
11704                    row_highlights.remove(ix + 1);
11705                } else {
11706                    break;
11707                }
11708            }
11709        }
11710    }
11711
11712    /// Remove any highlighted row ranges of the given type that intersect the
11713    /// given ranges.
11714    pub fn remove_highlighted_rows<T: 'static>(
11715        &mut self,
11716        ranges_to_remove: Vec<Range<Anchor>>,
11717        cx: &mut ViewContext<Self>,
11718    ) {
11719        let snapshot = self.buffer().read(cx).snapshot(cx);
11720        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11721        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11722        row_highlights.retain(|highlight| {
11723            while let Some(range_to_remove) = ranges_to_remove.peek() {
11724                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11725                    Ordering::Less | Ordering::Equal => {
11726                        ranges_to_remove.next();
11727                    }
11728                    Ordering::Greater => {
11729                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11730                            Ordering::Less | Ordering::Equal => {
11731                                return false;
11732                            }
11733                            Ordering::Greater => break,
11734                        }
11735                    }
11736                }
11737            }
11738
11739            true
11740        })
11741    }
11742
11743    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11744    pub fn clear_row_highlights<T: 'static>(&mut self) {
11745        self.highlighted_rows.remove(&TypeId::of::<T>());
11746    }
11747
11748    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11749    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11750        self.highlighted_rows
11751            .get(&TypeId::of::<T>())
11752            .map_or(&[] as &[_], |vec| vec.as_slice())
11753            .iter()
11754            .map(|highlight| (highlight.range.clone(), highlight.color))
11755    }
11756
11757    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11758    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11759    /// Allows to ignore certain kinds of highlights.
11760    pub fn highlighted_display_rows(
11761        &mut self,
11762        cx: &mut WindowContext,
11763    ) -> BTreeMap<DisplayRow, Hsla> {
11764        let snapshot = self.snapshot(cx);
11765        let mut used_highlight_orders = HashMap::default();
11766        self.highlighted_rows
11767            .iter()
11768            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11769            .fold(
11770                BTreeMap::<DisplayRow, Hsla>::new(),
11771                |mut unique_rows, highlight| {
11772                    let start = highlight.range.start.to_display_point(&snapshot);
11773                    let end = highlight.range.end.to_display_point(&snapshot);
11774                    let start_row = start.row().0;
11775                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11776                        && end.column() == 0
11777                    {
11778                        end.row().0.saturating_sub(1)
11779                    } else {
11780                        end.row().0
11781                    };
11782                    for row in start_row..=end_row {
11783                        let used_index =
11784                            used_highlight_orders.entry(row).or_insert(highlight.index);
11785                        if highlight.index >= *used_index {
11786                            *used_index = highlight.index;
11787                            unique_rows.insert(DisplayRow(row), highlight.color);
11788                        }
11789                    }
11790                    unique_rows
11791                },
11792            )
11793    }
11794
11795    pub fn highlighted_display_row_for_autoscroll(
11796        &self,
11797        snapshot: &DisplaySnapshot,
11798    ) -> Option<DisplayRow> {
11799        self.highlighted_rows
11800            .values()
11801            .flat_map(|highlighted_rows| highlighted_rows.iter())
11802            .filter_map(|highlight| {
11803                if highlight.should_autoscroll {
11804                    Some(highlight.range.start.to_display_point(snapshot).row())
11805                } else {
11806                    None
11807                }
11808            })
11809            .min()
11810    }
11811
11812    pub fn set_search_within_ranges(
11813        &mut self,
11814        ranges: &[Range<Anchor>],
11815        cx: &mut ViewContext<Self>,
11816    ) {
11817        self.highlight_background::<SearchWithinRange>(
11818            ranges,
11819            |colors| colors.editor_document_highlight_read_background,
11820            cx,
11821        )
11822    }
11823
11824    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11825        self.breadcrumb_header = Some(new_header);
11826    }
11827
11828    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11829        self.clear_background_highlights::<SearchWithinRange>(cx);
11830    }
11831
11832    pub fn highlight_background<T: 'static>(
11833        &mut self,
11834        ranges: &[Range<Anchor>],
11835        color_fetcher: fn(&ThemeColors) -> Hsla,
11836        cx: &mut ViewContext<Self>,
11837    ) {
11838        self.background_highlights
11839            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11840        self.scrollbar_marker_state.dirty = true;
11841        cx.notify();
11842    }
11843
11844    pub fn clear_background_highlights<T: 'static>(
11845        &mut self,
11846        cx: &mut ViewContext<Self>,
11847    ) -> Option<BackgroundHighlight> {
11848        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11849        if !text_highlights.1.is_empty() {
11850            self.scrollbar_marker_state.dirty = true;
11851            cx.notify();
11852        }
11853        Some(text_highlights)
11854    }
11855
11856    pub fn highlight_gutter<T: 'static>(
11857        &mut self,
11858        ranges: &[Range<Anchor>],
11859        color_fetcher: fn(&AppContext) -> Hsla,
11860        cx: &mut ViewContext<Self>,
11861    ) {
11862        self.gutter_highlights
11863            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11864        cx.notify();
11865    }
11866
11867    pub fn clear_gutter_highlights<T: 'static>(
11868        &mut self,
11869        cx: &mut ViewContext<Self>,
11870    ) -> Option<GutterHighlight> {
11871        cx.notify();
11872        self.gutter_highlights.remove(&TypeId::of::<T>())
11873    }
11874
11875    #[cfg(feature = "test-support")]
11876    pub fn all_text_background_highlights(
11877        &mut self,
11878        cx: &mut ViewContext<Self>,
11879    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11880        let snapshot = self.snapshot(cx);
11881        let buffer = &snapshot.buffer_snapshot;
11882        let start = buffer.anchor_before(0);
11883        let end = buffer.anchor_after(buffer.len());
11884        let theme = cx.theme().colors();
11885        self.background_highlights_in_range(start..end, &snapshot, theme)
11886    }
11887
11888    #[cfg(feature = "test-support")]
11889    pub fn search_background_highlights(
11890        &mut self,
11891        cx: &mut ViewContext<Self>,
11892    ) -> Vec<Range<Point>> {
11893        let snapshot = self.buffer().read(cx).snapshot(cx);
11894
11895        let highlights = self
11896            .background_highlights
11897            .get(&TypeId::of::<items::BufferSearchHighlights>());
11898
11899        if let Some((_color, ranges)) = highlights {
11900            ranges
11901                .iter()
11902                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11903                .collect_vec()
11904        } else {
11905            vec![]
11906        }
11907    }
11908
11909    fn document_highlights_for_position<'a>(
11910        &'a self,
11911        position: Anchor,
11912        buffer: &'a MultiBufferSnapshot,
11913    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11914        let read_highlights = self
11915            .background_highlights
11916            .get(&TypeId::of::<DocumentHighlightRead>())
11917            .map(|h| &h.1);
11918        let write_highlights = self
11919            .background_highlights
11920            .get(&TypeId::of::<DocumentHighlightWrite>())
11921            .map(|h| &h.1);
11922        let left_position = position.bias_left(buffer);
11923        let right_position = position.bias_right(buffer);
11924        read_highlights
11925            .into_iter()
11926            .chain(write_highlights)
11927            .flat_map(move |ranges| {
11928                let start_ix = match ranges.binary_search_by(|probe| {
11929                    let cmp = probe.end.cmp(&left_position, buffer);
11930                    if cmp.is_ge() {
11931                        Ordering::Greater
11932                    } else {
11933                        Ordering::Less
11934                    }
11935                }) {
11936                    Ok(i) | Err(i) => i,
11937                };
11938
11939                ranges[start_ix..]
11940                    .iter()
11941                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11942            })
11943    }
11944
11945    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11946        self.background_highlights
11947            .get(&TypeId::of::<T>())
11948            .map_or(false, |(_, highlights)| !highlights.is_empty())
11949    }
11950
11951    pub fn background_highlights_in_range(
11952        &self,
11953        search_range: Range<Anchor>,
11954        display_snapshot: &DisplaySnapshot,
11955        theme: &ThemeColors,
11956    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11957        let mut results = Vec::new();
11958        for (color_fetcher, ranges) in self.background_highlights.values() {
11959            let color = color_fetcher(theme);
11960            let start_ix = match ranges.binary_search_by(|probe| {
11961                let cmp = probe
11962                    .end
11963                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11964                if cmp.is_gt() {
11965                    Ordering::Greater
11966                } else {
11967                    Ordering::Less
11968                }
11969            }) {
11970                Ok(i) | Err(i) => i,
11971            };
11972            for range in &ranges[start_ix..] {
11973                if range
11974                    .start
11975                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11976                    .is_ge()
11977                {
11978                    break;
11979                }
11980
11981                let start = range.start.to_display_point(display_snapshot);
11982                let end = range.end.to_display_point(display_snapshot);
11983                results.push((start..end, color))
11984            }
11985        }
11986        results
11987    }
11988
11989    pub fn background_highlight_row_ranges<T: 'static>(
11990        &self,
11991        search_range: Range<Anchor>,
11992        display_snapshot: &DisplaySnapshot,
11993        count: usize,
11994    ) -> Vec<RangeInclusive<DisplayPoint>> {
11995        let mut results = Vec::new();
11996        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11997            return vec![];
11998        };
11999
12000        let start_ix = match ranges.binary_search_by(|probe| {
12001            let cmp = probe
12002                .end
12003                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12004            if cmp.is_gt() {
12005                Ordering::Greater
12006            } else {
12007                Ordering::Less
12008            }
12009        }) {
12010            Ok(i) | Err(i) => i,
12011        };
12012        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12013            if let (Some(start_display), Some(end_display)) = (start, end) {
12014                results.push(
12015                    start_display.to_display_point(display_snapshot)
12016                        ..=end_display.to_display_point(display_snapshot),
12017                );
12018            }
12019        };
12020        let mut start_row: Option<Point> = None;
12021        let mut end_row: Option<Point> = None;
12022        if ranges.len() > count {
12023            return Vec::new();
12024        }
12025        for range in &ranges[start_ix..] {
12026            if range
12027                .start
12028                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12029                .is_ge()
12030            {
12031                break;
12032            }
12033            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12034            if let Some(current_row) = &end_row {
12035                if end.row == current_row.row {
12036                    continue;
12037                }
12038            }
12039            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12040            if start_row.is_none() {
12041                assert_eq!(end_row, None);
12042                start_row = Some(start);
12043                end_row = Some(end);
12044                continue;
12045            }
12046            if let Some(current_end) = end_row.as_mut() {
12047                if start.row > current_end.row + 1 {
12048                    push_region(start_row, end_row);
12049                    start_row = Some(start);
12050                    end_row = Some(end);
12051                } else {
12052                    // Merge two hunks.
12053                    *current_end = end;
12054                }
12055            } else {
12056                unreachable!();
12057            }
12058        }
12059        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12060        push_region(start_row, end_row);
12061        results
12062    }
12063
12064    pub fn gutter_highlights_in_range(
12065        &self,
12066        search_range: Range<Anchor>,
12067        display_snapshot: &DisplaySnapshot,
12068        cx: &AppContext,
12069    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12070        let mut results = Vec::new();
12071        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12072            let color = color_fetcher(cx);
12073            let start_ix = match ranges.binary_search_by(|probe| {
12074                let cmp = probe
12075                    .end
12076                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12077                if cmp.is_gt() {
12078                    Ordering::Greater
12079                } else {
12080                    Ordering::Less
12081                }
12082            }) {
12083                Ok(i) | Err(i) => i,
12084            };
12085            for range in &ranges[start_ix..] {
12086                if range
12087                    .start
12088                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12089                    .is_ge()
12090                {
12091                    break;
12092                }
12093
12094                let start = range.start.to_display_point(display_snapshot);
12095                let end = range.end.to_display_point(display_snapshot);
12096                results.push((start..end, color))
12097            }
12098        }
12099        results
12100    }
12101
12102    /// Get the text ranges corresponding to the redaction query
12103    pub fn redacted_ranges(
12104        &self,
12105        search_range: Range<Anchor>,
12106        display_snapshot: &DisplaySnapshot,
12107        cx: &WindowContext,
12108    ) -> Vec<Range<DisplayPoint>> {
12109        display_snapshot
12110            .buffer_snapshot
12111            .redacted_ranges(search_range, |file| {
12112                if let Some(file) = file {
12113                    file.is_private()
12114                        && EditorSettings::get(
12115                            Some(SettingsLocation {
12116                                worktree_id: file.worktree_id(cx),
12117                                path: file.path().as_ref(),
12118                            }),
12119                            cx,
12120                        )
12121                        .redact_private_values
12122                } else {
12123                    false
12124                }
12125            })
12126            .map(|range| {
12127                range.start.to_display_point(display_snapshot)
12128                    ..range.end.to_display_point(display_snapshot)
12129            })
12130            .collect()
12131    }
12132
12133    pub fn highlight_text<T: 'static>(
12134        &mut self,
12135        ranges: Vec<Range<Anchor>>,
12136        style: HighlightStyle,
12137        cx: &mut ViewContext<Self>,
12138    ) {
12139        self.display_map.update(cx, |map, _| {
12140            map.highlight_text(TypeId::of::<T>(), ranges, style)
12141        });
12142        cx.notify();
12143    }
12144
12145    pub(crate) fn highlight_inlays<T: 'static>(
12146        &mut self,
12147        highlights: Vec<InlayHighlight>,
12148        style: HighlightStyle,
12149        cx: &mut ViewContext<Self>,
12150    ) {
12151        self.display_map.update(cx, |map, _| {
12152            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12153        });
12154        cx.notify();
12155    }
12156
12157    pub fn text_highlights<'a, T: 'static>(
12158        &'a self,
12159        cx: &'a AppContext,
12160    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12161        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12162    }
12163
12164    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12165        let cleared = self
12166            .display_map
12167            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12168        if cleared {
12169            cx.notify();
12170        }
12171    }
12172
12173    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12174        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12175            && self.focus_handle.is_focused(cx)
12176    }
12177
12178    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12179        self.show_cursor_when_unfocused = is_enabled;
12180        cx.notify();
12181    }
12182
12183    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12184        self.project
12185            .as_ref()
12186            .map(|project| project.read(cx).lsp_store())
12187    }
12188
12189    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12190        cx.notify();
12191    }
12192
12193    fn on_buffer_event(
12194        &mut self,
12195        multibuffer: Model<MultiBuffer>,
12196        event: &multi_buffer::Event,
12197        cx: &mut ViewContext<Self>,
12198    ) {
12199        match event {
12200            multi_buffer::Event::Edited {
12201                singleton_buffer_edited,
12202                edited_buffer: buffer_edited,
12203            } => {
12204                self.scrollbar_marker_state.dirty = true;
12205                self.active_indent_guides_state.dirty = true;
12206                self.refresh_active_diagnostics(cx);
12207                self.refresh_code_actions(cx);
12208                if self.has_active_inline_completion() {
12209                    self.update_visible_inline_completion(cx);
12210                }
12211                if let Some(buffer) = buffer_edited {
12212                    let buffer_id = buffer.read(cx).remote_id();
12213                    if !self.registered_buffers.contains_key(&buffer_id) {
12214                        if let Some(lsp_store) = self.lsp_store(cx) {
12215                            lsp_store.update(cx, |lsp_store, cx| {
12216                                self.registered_buffers.insert(
12217                                    buffer_id,
12218                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12219                                );
12220                            })
12221                        }
12222                    }
12223                }
12224                cx.emit(EditorEvent::BufferEdited);
12225                cx.emit(SearchEvent::MatchesInvalidated);
12226                if *singleton_buffer_edited {
12227                    if let Some(project) = &self.project {
12228                        let project = project.read(cx);
12229                        #[allow(clippy::mutable_key_type)]
12230                        let languages_affected = multibuffer
12231                            .read(cx)
12232                            .all_buffers()
12233                            .into_iter()
12234                            .filter_map(|buffer| {
12235                                let buffer = buffer.read(cx);
12236                                let language = buffer.language()?;
12237                                if project.is_local()
12238                                    && project
12239                                        .language_servers_for_local_buffer(buffer, cx)
12240                                        .count()
12241                                        == 0
12242                                {
12243                                    None
12244                                } else {
12245                                    Some(language)
12246                                }
12247                            })
12248                            .cloned()
12249                            .collect::<HashSet<_>>();
12250                        if !languages_affected.is_empty() {
12251                            self.refresh_inlay_hints(
12252                                InlayHintRefreshReason::BufferEdited(languages_affected),
12253                                cx,
12254                            );
12255                        }
12256                    }
12257                }
12258
12259                let Some(project) = &self.project else { return };
12260                let (telemetry, is_via_ssh) = {
12261                    let project = project.read(cx);
12262                    let telemetry = project.client().telemetry().clone();
12263                    let is_via_ssh = project.is_via_ssh();
12264                    (telemetry, is_via_ssh)
12265                };
12266                refresh_linked_ranges(self, cx);
12267                telemetry.log_edit_event("editor", is_via_ssh);
12268            }
12269            multi_buffer::Event::ExcerptsAdded {
12270                buffer,
12271                predecessor,
12272                excerpts,
12273            } => {
12274                self.tasks_update_task = Some(self.refresh_runnables(cx));
12275                let buffer_id = buffer.read(cx).remote_id();
12276                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12277                    if let Some(project) = &self.project {
12278                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12279                    }
12280                }
12281                cx.emit(EditorEvent::ExcerptsAdded {
12282                    buffer: buffer.clone(),
12283                    predecessor: *predecessor,
12284                    excerpts: excerpts.clone(),
12285                });
12286                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12287            }
12288            multi_buffer::Event::ExcerptsRemoved { ids } => {
12289                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12290                let buffer = self.buffer.read(cx);
12291                self.registered_buffers
12292                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12293                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12294            }
12295            multi_buffer::Event::ExcerptsEdited { ids } => {
12296                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12297            }
12298            multi_buffer::Event::ExcerptsExpanded { ids } => {
12299                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12300            }
12301            multi_buffer::Event::Reparsed(buffer_id) => {
12302                self.tasks_update_task = Some(self.refresh_runnables(cx));
12303
12304                cx.emit(EditorEvent::Reparsed(*buffer_id));
12305            }
12306            multi_buffer::Event::LanguageChanged(buffer_id) => {
12307                linked_editing_ranges::refresh_linked_ranges(self, cx);
12308                cx.emit(EditorEvent::Reparsed(*buffer_id));
12309                cx.notify();
12310            }
12311            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12312            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12313            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12314                cx.emit(EditorEvent::TitleChanged)
12315            }
12316            // multi_buffer::Event::DiffBaseChanged => {
12317            //     self.scrollbar_marker_state.dirty = true;
12318            //     cx.emit(EditorEvent::DiffBaseChanged);
12319            //     cx.notify();
12320            // }
12321            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12322            multi_buffer::Event::DiagnosticsUpdated => {
12323                self.refresh_active_diagnostics(cx);
12324                self.scrollbar_marker_state.dirty = true;
12325                cx.notify();
12326            }
12327            _ => {}
12328        };
12329    }
12330
12331    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12332        cx.notify();
12333    }
12334
12335    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12336        self.tasks_update_task = Some(self.refresh_runnables(cx));
12337        self.refresh_inline_completion(true, false, cx);
12338        self.refresh_inlay_hints(
12339            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12340                self.selections.newest_anchor().head(),
12341                &self.buffer.read(cx).snapshot(cx),
12342                cx,
12343            )),
12344            cx,
12345        );
12346
12347        let old_cursor_shape = self.cursor_shape;
12348
12349        {
12350            let editor_settings = EditorSettings::get_global(cx);
12351            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12352            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12353            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12354        }
12355
12356        if old_cursor_shape != self.cursor_shape {
12357            cx.emit(EditorEvent::CursorShapeChanged);
12358        }
12359
12360        let project_settings = ProjectSettings::get_global(cx);
12361        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12362
12363        if self.mode == EditorMode::Full {
12364            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12365            if self.git_blame_inline_enabled != inline_blame_enabled {
12366                self.toggle_git_blame_inline_internal(false, cx);
12367            }
12368        }
12369
12370        cx.notify();
12371    }
12372
12373    pub fn set_searchable(&mut self, searchable: bool) {
12374        self.searchable = searchable;
12375    }
12376
12377    pub fn searchable(&self) -> bool {
12378        self.searchable
12379    }
12380
12381    fn open_proposed_changes_editor(
12382        &mut self,
12383        _: &OpenProposedChangesEditor,
12384        cx: &mut ViewContext<Self>,
12385    ) {
12386        let Some(workspace) = self.workspace() else {
12387            cx.propagate();
12388            return;
12389        };
12390
12391        let selections = self.selections.all::<usize>(cx);
12392        let buffer = self.buffer.read(cx);
12393        let mut new_selections_by_buffer = HashMap::default();
12394        for selection in selections {
12395            for (buffer, range, _) in
12396                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12397            {
12398                let mut range = range.to_point(buffer.read(cx));
12399                range.start.column = 0;
12400                range.end.column = buffer.read(cx).line_len(range.end.row);
12401                new_selections_by_buffer
12402                    .entry(buffer)
12403                    .or_insert(Vec::new())
12404                    .push(range)
12405            }
12406        }
12407
12408        let proposed_changes_buffers = new_selections_by_buffer
12409            .into_iter()
12410            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12411            .collect::<Vec<_>>();
12412        let proposed_changes_editor = cx.new_view(|cx| {
12413            ProposedChangesEditor::new(
12414                "Proposed changes",
12415                proposed_changes_buffers,
12416                self.project.clone(),
12417                cx,
12418            )
12419        });
12420
12421        cx.window_context().defer(move |cx| {
12422            workspace.update(cx, |workspace, cx| {
12423                workspace.active_pane().update(cx, |pane, cx| {
12424                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12425                });
12426            });
12427        });
12428    }
12429
12430    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12431        self.open_excerpts_common(None, true, cx)
12432    }
12433
12434    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12435        self.open_excerpts_common(None, false, cx)
12436    }
12437
12438    fn open_excerpts_common(
12439        &mut self,
12440        jump_data: Option<JumpData>,
12441        split: bool,
12442        cx: &mut ViewContext<Self>,
12443    ) {
12444        let Some(workspace) = self.workspace() else {
12445            cx.propagate();
12446            return;
12447        };
12448
12449        if self.buffer.read(cx).is_singleton() {
12450            cx.propagate();
12451            return;
12452        }
12453
12454        let mut new_selections_by_buffer = HashMap::default();
12455        match &jump_data {
12456            Some(jump_data) => {
12457                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12458                if let Some(buffer) = multi_buffer_snapshot
12459                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12460                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12461                {
12462                    let buffer_snapshot = buffer.read(cx).snapshot();
12463                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12464                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12465                    } else {
12466                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12467                    };
12468                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12469                    new_selections_by_buffer.insert(
12470                        buffer,
12471                        (
12472                            vec![jump_to_offset..jump_to_offset],
12473                            Some(jump_data.line_offset_from_top),
12474                        ),
12475                    );
12476                }
12477            }
12478            None => {
12479                let selections = self.selections.all::<usize>(cx);
12480                let buffer = self.buffer.read(cx);
12481                for selection in selections {
12482                    for (mut buffer_handle, mut range, _) in
12483                        buffer.range_to_buffer_ranges(selection.range(), cx)
12484                    {
12485                        // When editing branch buffers, jump to the corresponding location
12486                        // in their base buffer.
12487                        let buffer = buffer_handle.read(cx);
12488                        if let Some(base_buffer) = buffer.base_buffer() {
12489                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12490                            buffer_handle = base_buffer;
12491                        }
12492
12493                        if selection.reversed {
12494                            mem::swap(&mut range.start, &mut range.end);
12495                        }
12496                        new_selections_by_buffer
12497                            .entry(buffer_handle)
12498                            .or_insert((Vec::new(), None))
12499                            .0
12500                            .push(range)
12501                    }
12502                }
12503            }
12504        }
12505
12506        if new_selections_by_buffer.is_empty() {
12507            return;
12508        }
12509
12510        // We defer the pane interaction because we ourselves are a workspace item
12511        // and activating a new item causes the pane to call a method on us reentrantly,
12512        // which panics if we're on the stack.
12513        cx.window_context().defer(move |cx| {
12514            workspace.update(cx, |workspace, cx| {
12515                let pane = if split {
12516                    workspace.adjacent_pane(cx)
12517                } else {
12518                    workspace.active_pane().clone()
12519                };
12520
12521                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12522                    let editor = buffer
12523                        .read(cx)
12524                        .file()
12525                        .is_none()
12526                        .then(|| {
12527                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12528                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12529                            // Instead, we try to activate the existing editor in the pane first.
12530                            let (editor, pane_item_index) =
12531                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12532                                    let editor = item.downcast::<Editor>()?;
12533                                    let singleton_buffer =
12534                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12535                                    if singleton_buffer == buffer {
12536                                        Some((editor, i))
12537                                    } else {
12538                                        None
12539                                    }
12540                                })?;
12541                            pane.update(cx, |pane, cx| {
12542                                pane.activate_item(pane_item_index, true, true, cx)
12543                            });
12544                            Some(editor)
12545                        })
12546                        .flatten()
12547                        .unwrap_or_else(|| {
12548                            workspace.open_project_item::<Self>(
12549                                pane.clone(),
12550                                buffer,
12551                                true,
12552                                true,
12553                                cx,
12554                            )
12555                        });
12556
12557                    editor.update(cx, |editor, cx| {
12558                        let autoscroll = match scroll_offset {
12559                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12560                            None => Autoscroll::newest(),
12561                        };
12562                        let nav_history = editor.nav_history.take();
12563                        editor.change_selections(Some(autoscroll), cx, |s| {
12564                            s.select_ranges(ranges);
12565                        });
12566                        editor.nav_history = nav_history;
12567                    });
12568                }
12569            })
12570        });
12571    }
12572
12573    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12574        let snapshot = self.buffer.read(cx).read(cx);
12575        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12576        Some(
12577            ranges
12578                .iter()
12579                .map(move |range| {
12580                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12581                })
12582                .collect(),
12583        )
12584    }
12585
12586    fn selection_replacement_ranges(
12587        &self,
12588        range: Range<OffsetUtf16>,
12589        cx: &mut AppContext,
12590    ) -> Vec<Range<OffsetUtf16>> {
12591        let selections = self.selections.all::<OffsetUtf16>(cx);
12592        let newest_selection = selections
12593            .iter()
12594            .max_by_key(|selection| selection.id)
12595            .unwrap();
12596        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12597        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12598        let snapshot = self.buffer.read(cx).read(cx);
12599        selections
12600            .into_iter()
12601            .map(|mut selection| {
12602                selection.start.0 =
12603                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12604                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12605                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12606                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12607            })
12608            .collect()
12609    }
12610
12611    fn report_editor_event(
12612        &self,
12613        event_type: &'static str,
12614        file_extension: Option<String>,
12615        cx: &AppContext,
12616    ) {
12617        if cfg!(any(test, feature = "test-support")) {
12618            return;
12619        }
12620
12621        let Some(project) = &self.project else { return };
12622
12623        // If None, we are in a file without an extension
12624        let file = self
12625            .buffer
12626            .read(cx)
12627            .as_singleton()
12628            .and_then(|b| b.read(cx).file());
12629        let file_extension = file_extension.or(file
12630            .as_ref()
12631            .and_then(|file| Path::new(file.file_name(cx)).extension())
12632            .and_then(|e| e.to_str())
12633            .map(|a| a.to_string()));
12634
12635        let vim_mode = cx
12636            .global::<SettingsStore>()
12637            .raw_user_settings()
12638            .get("vim_mode")
12639            == Some(&serde_json::Value::Bool(true));
12640
12641        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12642            == language::language_settings::InlineCompletionProvider::Copilot;
12643        let copilot_enabled_for_language = self
12644            .buffer
12645            .read(cx)
12646            .settings_at(0, cx)
12647            .show_inline_completions;
12648
12649        let project = project.read(cx);
12650        telemetry::event!(
12651            event_type,
12652            file_extension,
12653            vim_mode,
12654            copilot_enabled,
12655            copilot_enabled_for_language,
12656            is_via_ssh = project.is_via_ssh(),
12657        );
12658    }
12659
12660    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12661    /// with each line being an array of {text, highlight} objects.
12662    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12663        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12664            return;
12665        };
12666
12667        #[derive(Serialize)]
12668        struct Chunk<'a> {
12669            text: String,
12670            highlight: Option<&'a str>,
12671        }
12672
12673        let snapshot = buffer.read(cx).snapshot();
12674        let range = self
12675            .selected_text_range(false, cx)
12676            .and_then(|selection| {
12677                if selection.range.is_empty() {
12678                    None
12679                } else {
12680                    Some(selection.range)
12681                }
12682            })
12683            .unwrap_or_else(|| 0..snapshot.len());
12684
12685        let chunks = snapshot.chunks(range, true);
12686        let mut lines = Vec::new();
12687        let mut line: VecDeque<Chunk> = VecDeque::new();
12688
12689        let Some(style) = self.style.as_ref() else {
12690            return;
12691        };
12692
12693        for chunk in chunks {
12694            let highlight = chunk
12695                .syntax_highlight_id
12696                .and_then(|id| id.name(&style.syntax));
12697            let mut chunk_lines = chunk.text.split('\n').peekable();
12698            while let Some(text) = chunk_lines.next() {
12699                let mut merged_with_last_token = false;
12700                if let Some(last_token) = line.back_mut() {
12701                    if last_token.highlight == highlight {
12702                        last_token.text.push_str(text);
12703                        merged_with_last_token = true;
12704                    }
12705                }
12706
12707                if !merged_with_last_token {
12708                    line.push_back(Chunk {
12709                        text: text.into(),
12710                        highlight,
12711                    });
12712                }
12713
12714                if chunk_lines.peek().is_some() {
12715                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12716                        line.pop_front();
12717                    }
12718                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12719                        line.pop_back();
12720                    }
12721
12722                    lines.push(mem::take(&mut line));
12723                }
12724            }
12725        }
12726
12727        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12728            return;
12729        };
12730        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12731    }
12732
12733    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12734        self.request_autoscroll(Autoscroll::newest(), cx);
12735        let position = self.selections.newest_display(cx).start;
12736        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12737    }
12738
12739    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12740        &self.inlay_hint_cache
12741    }
12742
12743    pub fn replay_insert_event(
12744        &mut self,
12745        text: &str,
12746        relative_utf16_range: Option<Range<isize>>,
12747        cx: &mut ViewContext<Self>,
12748    ) {
12749        if !self.input_enabled {
12750            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12751            return;
12752        }
12753        if let Some(relative_utf16_range) = relative_utf16_range {
12754            let selections = self.selections.all::<OffsetUtf16>(cx);
12755            self.change_selections(None, cx, |s| {
12756                let new_ranges = selections.into_iter().map(|range| {
12757                    let start = OffsetUtf16(
12758                        range
12759                            .head()
12760                            .0
12761                            .saturating_add_signed(relative_utf16_range.start),
12762                    );
12763                    let end = OffsetUtf16(
12764                        range
12765                            .head()
12766                            .0
12767                            .saturating_add_signed(relative_utf16_range.end),
12768                    );
12769                    start..end
12770                });
12771                s.select_ranges(new_ranges);
12772            });
12773        }
12774
12775        self.handle_input(text, cx);
12776    }
12777
12778    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12779        let Some(provider) = self.semantics_provider.as_ref() else {
12780            return false;
12781        };
12782
12783        let mut supports = false;
12784        self.buffer().read(cx).for_each_buffer(|buffer| {
12785            supports |= provider.supports_inlay_hints(buffer, cx);
12786        });
12787        supports
12788    }
12789
12790    pub fn focus(&self, cx: &mut WindowContext) {
12791        cx.focus(&self.focus_handle)
12792    }
12793
12794    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12795        self.focus_handle.is_focused(cx)
12796    }
12797
12798    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12799        cx.emit(EditorEvent::Focused);
12800
12801        if let Some(descendant) = self
12802            .last_focused_descendant
12803            .take()
12804            .and_then(|descendant| descendant.upgrade())
12805        {
12806            cx.focus(&descendant);
12807        } else {
12808            if let Some(blame) = self.blame.as_ref() {
12809                blame.update(cx, GitBlame::focus)
12810            }
12811
12812            self.blink_manager.update(cx, BlinkManager::enable);
12813            self.show_cursor_names(cx);
12814            self.buffer.update(cx, |buffer, cx| {
12815                buffer.finalize_last_transaction(cx);
12816                if self.leader_peer_id.is_none() {
12817                    buffer.set_active_selections(
12818                        &self.selections.disjoint_anchors(),
12819                        self.selections.line_mode,
12820                        self.cursor_shape,
12821                        cx,
12822                    );
12823                }
12824            });
12825        }
12826    }
12827
12828    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12829        cx.emit(EditorEvent::FocusedIn)
12830    }
12831
12832    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12833        if event.blurred != self.focus_handle {
12834            self.last_focused_descendant = Some(event.blurred);
12835        }
12836    }
12837
12838    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12839        self.blink_manager.update(cx, BlinkManager::disable);
12840        self.buffer
12841            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12842
12843        if let Some(blame) = self.blame.as_ref() {
12844            blame.update(cx, GitBlame::blur)
12845        }
12846        if !self.hover_state.focused(cx) {
12847            hide_hover(self, cx);
12848        }
12849
12850        self.hide_context_menu(cx);
12851        cx.emit(EditorEvent::Blurred);
12852        cx.notify();
12853    }
12854
12855    pub fn register_action<A: Action>(
12856        &mut self,
12857        listener: impl Fn(&A, &mut WindowContext) + 'static,
12858    ) -> Subscription {
12859        let id = self.next_editor_action_id.post_inc();
12860        let listener = Arc::new(listener);
12861        self.editor_actions.borrow_mut().insert(
12862            id,
12863            Box::new(move |cx| {
12864                let cx = cx.window_context();
12865                let listener = listener.clone();
12866                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12867                    let action = action.downcast_ref().unwrap();
12868                    if phase == DispatchPhase::Bubble {
12869                        listener(action, cx)
12870                    }
12871                })
12872            }),
12873        );
12874
12875        let editor_actions = self.editor_actions.clone();
12876        Subscription::new(move || {
12877            editor_actions.borrow_mut().remove(&id);
12878        })
12879    }
12880
12881    pub fn file_header_size(&self) -> u32 {
12882        FILE_HEADER_HEIGHT
12883    }
12884
12885    pub fn revert(
12886        &mut self,
12887        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12888        cx: &mut ViewContext<Self>,
12889    ) {
12890        self.buffer().update(cx, |multi_buffer, cx| {
12891            for (buffer_id, changes) in revert_changes {
12892                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12893                    buffer.update(cx, |buffer, cx| {
12894                        buffer.edit(
12895                            changes.into_iter().map(|(range, text)| {
12896                                (range, text.to_string().map(Arc::<str>::from))
12897                            }),
12898                            None,
12899                            cx,
12900                        );
12901                    });
12902                }
12903            }
12904        });
12905        self.change_selections(None, cx, |selections| selections.refresh());
12906    }
12907
12908    pub fn to_pixel_point(
12909        &mut self,
12910        source: multi_buffer::Anchor,
12911        editor_snapshot: &EditorSnapshot,
12912        cx: &mut ViewContext<Self>,
12913    ) -> Option<gpui::Point<Pixels>> {
12914        let source_point = source.to_display_point(editor_snapshot);
12915        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12916    }
12917
12918    pub fn display_to_pixel_point(
12919        &self,
12920        source: DisplayPoint,
12921        editor_snapshot: &EditorSnapshot,
12922        cx: &WindowContext,
12923    ) -> Option<gpui::Point<Pixels>> {
12924        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12925        let text_layout_details = self.text_layout_details(cx);
12926        let scroll_top = text_layout_details
12927            .scroll_anchor
12928            .scroll_position(editor_snapshot)
12929            .y;
12930
12931        if source.row().as_f32() < scroll_top.floor() {
12932            return None;
12933        }
12934        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12935        let source_y = line_height * (source.row().as_f32() - scroll_top);
12936        Some(gpui::Point::new(source_x, source_y))
12937    }
12938
12939    pub fn has_active_completions_menu(&self) -> bool {
12940        self.context_menu.borrow().as_ref().map_or(false, |menu| {
12941            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12942        })
12943    }
12944
12945    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12946        self.addons
12947            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12948    }
12949
12950    pub fn unregister_addon<T: Addon>(&mut self) {
12951        self.addons.remove(&std::any::TypeId::of::<T>());
12952    }
12953
12954    pub fn addon<T: Addon>(&self) -> Option<&T> {
12955        let type_id = std::any::TypeId::of::<T>();
12956        self.addons
12957            .get(&type_id)
12958            .and_then(|item| item.to_any().downcast_ref::<T>())
12959    }
12960
12961    pub fn add_change_set(
12962        &mut self,
12963        change_set: Model<BufferChangeSet>,
12964        cx: &mut ViewContext<Self>,
12965    ) {
12966        self.diff_map.add_change_set(change_set, cx);
12967    }
12968
12969    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12970        let text_layout_details = self.text_layout_details(cx);
12971        let style = &text_layout_details.editor_style;
12972        let font_id = cx.text_system().resolve_font(&style.text.font());
12973        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12974        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12975
12976        let em_width = cx
12977            .text_system()
12978            .typographic_bounds(font_id, font_size, 'm')
12979            .unwrap()
12980            .size
12981            .width;
12982
12983        gpui::Point::new(em_width, line_height)
12984    }
12985}
12986
12987fn get_unstaged_changes_for_buffers(
12988    project: &Model<Project>,
12989    buffers: impl IntoIterator<Item = Model<Buffer>>,
12990    cx: &mut ViewContext<Editor>,
12991) {
12992    let mut tasks = Vec::new();
12993    project.update(cx, |project, cx| {
12994        for buffer in buffers {
12995            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12996        }
12997    });
12998    cx.spawn(|this, mut cx| async move {
12999        let change_sets = futures::future::join_all(tasks).await;
13000        this.update(&mut cx, |this, cx| {
13001            for change_set in change_sets {
13002                if let Some(change_set) = change_set.log_err() {
13003                    this.diff_map.add_change_set(change_set, cx);
13004                }
13005            }
13006        })
13007        .ok();
13008    })
13009    .detach();
13010}
13011
13012fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13013    let tab_size = tab_size.get() as usize;
13014    let mut width = offset;
13015
13016    for ch in text.chars() {
13017        width += if ch == '\t' {
13018            tab_size - (width % tab_size)
13019        } else {
13020            1
13021        };
13022    }
13023
13024    width - offset
13025}
13026
13027#[cfg(test)]
13028mod tests {
13029    use super::*;
13030
13031    #[test]
13032    fn test_string_size_with_expanded_tabs() {
13033        let nz = |val| NonZeroU32::new(val).unwrap();
13034        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13035        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13036        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13037        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13038        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13039        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13040        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13041        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13042    }
13043}
13044
13045/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13046struct WordBreakingTokenizer<'a> {
13047    input: &'a str,
13048}
13049
13050impl<'a> WordBreakingTokenizer<'a> {
13051    fn new(input: &'a str) -> Self {
13052        Self { input }
13053    }
13054}
13055
13056fn is_char_ideographic(ch: char) -> bool {
13057    use unicode_script::Script::*;
13058    use unicode_script::UnicodeScript;
13059    matches!(ch.script(), Han | Tangut | Yi)
13060}
13061
13062fn is_grapheme_ideographic(text: &str) -> bool {
13063    text.chars().any(is_char_ideographic)
13064}
13065
13066fn is_grapheme_whitespace(text: &str) -> bool {
13067    text.chars().any(|x| x.is_whitespace())
13068}
13069
13070fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13071    text.chars().next().map_or(false, |ch| {
13072        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13073    })
13074}
13075
13076#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13077struct WordBreakToken<'a> {
13078    token: &'a str,
13079    grapheme_len: usize,
13080    is_whitespace: bool,
13081}
13082
13083impl<'a> Iterator for WordBreakingTokenizer<'a> {
13084    /// Yields a span, the count of graphemes in the token, and whether it was
13085    /// whitespace. Note that it also breaks at word boundaries.
13086    type Item = WordBreakToken<'a>;
13087
13088    fn next(&mut self) -> Option<Self::Item> {
13089        use unicode_segmentation::UnicodeSegmentation;
13090        if self.input.is_empty() {
13091            return None;
13092        }
13093
13094        let mut iter = self.input.graphemes(true).peekable();
13095        let mut offset = 0;
13096        let mut graphemes = 0;
13097        if let Some(first_grapheme) = iter.next() {
13098            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13099            offset += first_grapheme.len();
13100            graphemes += 1;
13101            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13102                if let Some(grapheme) = iter.peek().copied() {
13103                    if should_stay_with_preceding_ideograph(grapheme) {
13104                        offset += grapheme.len();
13105                        graphemes += 1;
13106                    }
13107                }
13108            } else {
13109                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13110                let mut next_word_bound = words.peek().copied();
13111                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13112                    next_word_bound = words.next();
13113                }
13114                while let Some(grapheme) = iter.peek().copied() {
13115                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13116                        break;
13117                    };
13118                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13119                        break;
13120                    };
13121                    offset += grapheme.len();
13122                    graphemes += 1;
13123                    iter.next();
13124                }
13125            }
13126            let token = &self.input[..offset];
13127            self.input = &self.input[offset..];
13128            if is_whitespace {
13129                Some(WordBreakToken {
13130                    token: " ",
13131                    grapheme_len: 1,
13132                    is_whitespace: true,
13133                })
13134            } else {
13135                Some(WordBreakToken {
13136                    token,
13137                    grapheme_len: graphemes,
13138                    is_whitespace: false,
13139                })
13140            }
13141        } else {
13142            None
13143        }
13144    }
13145}
13146
13147#[test]
13148fn test_word_breaking_tokenizer() {
13149    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13150        ("", &[]),
13151        ("  ", &[(" ", 1, true)]),
13152        ("Ʒ", &[("Ʒ", 1, false)]),
13153        ("Ǽ", &[("Ǽ", 1, false)]),
13154        ("", &[("", 1, false)]),
13155        ("⋑⋑", &[("⋑⋑", 2, false)]),
13156        (
13157            "原理,进而",
13158            &[
13159                ("", 1, false),
13160                ("理,", 2, false),
13161                ("", 1, false),
13162                ("", 1, false),
13163            ],
13164        ),
13165        (
13166            "hello world",
13167            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13168        ),
13169        (
13170            "hello, world",
13171            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13172        ),
13173        (
13174            "  hello world",
13175            &[
13176                (" ", 1, true),
13177                ("hello", 5, false),
13178                (" ", 1, true),
13179                ("world", 5, false),
13180            ],
13181        ),
13182        (
13183            "这是什么 \n 钢笔",
13184            &[
13185                ("", 1, false),
13186                ("", 1, false),
13187                ("", 1, false),
13188                ("", 1, false),
13189                (" ", 1, true),
13190                ("", 1, false),
13191                ("", 1, false),
13192            ],
13193        ),
13194        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13195    ];
13196
13197    for (input, result) in tests {
13198        assert_eq!(
13199            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13200            result
13201                .iter()
13202                .copied()
13203                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13204                    token,
13205                    grapheme_len,
13206                    is_whitespace,
13207                })
13208                .collect::<Vec<_>>()
13209        );
13210    }
13211}
13212
13213fn wrap_with_prefix(
13214    line_prefix: String,
13215    unwrapped_text: String,
13216    wrap_column: usize,
13217    tab_size: NonZeroU32,
13218) -> String {
13219    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13220    let mut wrapped_text = String::new();
13221    let mut current_line = line_prefix.clone();
13222
13223    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13224    let mut current_line_len = line_prefix_len;
13225    for WordBreakToken {
13226        token,
13227        grapheme_len,
13228        is_whitespace,
13229    } in tokenizer
13230    {
13231        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13232            wrapped_text.push_str(current_line.trim_end());
13233            wrapped_text.push('\n');
13234            current_line.truncate(line_prefix.len());
13235            current_line_len = line_prefix_len;
13236            if !is_whitespace {
13237                current_line.push_str(token);
13238                current_line_len += grapheme_len;
13239            }
13240        } else if !is_whitespace {
13241            current_line.push_str(token);
13242            current_line_len += grapheme_len;
13243        } else if current_line_len != line_prefix_len {
13244            current_line.push(' ');
13245            current_line_len += 1;
13246        }
13247    }
13248
13249    if !current_line.is_empty() {
13250        wrapped_text.push_str(&current_line);
13251    }
13252    wrapped_text
13253}
13254
13255#[test]
13256fn test_wrap_with_prefix() {
13257    assert_eq!(
13258        wrap_with_prefix(
13259            "# ".to_string(),
13260            "abcdefg".to_string(),
13261            4,
13262            NonZeroU32::new(4).unwrap()
13263        ),
13264        "# abcdefg"
13265    );
13266    assert_eq!(
13267        wrap_with_prefix(
13268            "".to_string(),
13269            "\thello world".to_string(),
13270            8,
13271            NonZeroU32::new(4).unwrap()
13272        ),
13273        "hello\nworld"
13274    );
13275    assert_eq!(
13276        wrap_with_prefix(
13277            "// ".to_string(),
13278            "xx \nyy zz aa bb cc".to_string(),
13279            12,
13280            NonZeroU32::new(4).unwrap()
13281        ),
13282        "// xx yy zz\n// aa bb cc"
13283    );
13284    assert_eq!(
13285        wrap_with_prefix(
13286            String::new(),
13287            "这是什么 \n 钢笔".to_string(),
13288            3,
13289            NonZeroU32::new(4).unwrap()
13290        ),
13291        "这是什\n么 钢\n"
13292    );
13293}
13294
13295fn hunks_for_selections(
13296    snapshot: &EditorSnapshot,
13297    selections: &[Selection<Point>],
13298) -> Vec<MultiBufferDiffHunk> {
13299    hunks_for_ranges(
13300        selections.iter().map(|selection| selection.range()),
13301        snapshot,
13302    )
13303}
13304
13305pub fn hunks_for_ranges(
13306    ranges: impl Iterator<Item = Range<Point>>,
13307    snapshot: &EditorSnapshot,
13308) -> Vec<MultiBufferDiffHunk> {
13309    let mut hunks = Vec::new();
13310    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13311        HashMap::default();
13312    for query_range in ranges {
13313        let query_rows =
13314            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13315        for hunk in snapshot.diff_map.diff_hunks_in_range(
13316            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13317            &snapshot.buffer_snapshot,
13318        ) {
13319            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13320            // when the caret is just above or just below the deleted hunk.
13321            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13322            let related_to_selection = if allow_adjacent {
13323                hunk.row_range.overlaps(&query_rows)
13324                    || hunk.row_range.start == query_rows.end
13325                    || hunk.row_range.end == query_rows.start
13326            } else {
13327                hunk.row_range.overlaps(&query_rows)
13328            };
13329            if related_to_selection {
13330                if !processed_buffer_rows
13331                    .entry(hunk.buffer_id)
13332                    .or_default()
13333                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13334                {
13335                    continue;
13336                }
13337                hunks.push(hunk);
13338            }
13339        }
13340    }
13341
13342    hunks
13343}
13344
13345pub trait CollaborationHub {
13346    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13347    fn user_participant_indices<'a>(
13348        &self,
13349        cx: &'a AppContext,
13350    ) -> &'a HashMap<u64, ParticipantIndex>;
13351    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13352}
13353
13354impl CollaborationHub for Model<Project> {
13355    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13356        self.read(cx).collaborators()
13357    }
13358
13359    fn user_participant_indices<'a>(
13360        &self,
13361        cx: &'a AppContext,
13362    ) -> &'a HashMap<u64, ParticipantIndex> {
13363        self.read(cx).user_store().read(cx).participant_indices()
13364    }
13365
13366    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13367        let this = self.read(cx);
13368        let user_ids = this.collaborators().values().map(|c| c.user_id);
13369        this.user_store().read_with(cx, |user_store, cx| {
13370            user_store.participant_names(user_ids, cx)
13371        })
13372    }
13373}
13374
13375pub trait SemanticsProvider {
13376    fn hover(
13377        &self,
13378        buffer: &Model<Buffer>,
13379        position: text::Anchor,
13380        cx: &mut AppContext,
13381    ) -> Option<Task<Vec<project::Hover>>>;
13382
13383    fn inlay_hints(
13384        &self,
13385        buffer_handle: Model<Buffer>,
13386        range: Range<text::Anchor>,
13387        cx: &mut AppContext,
13388    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13389
13390    fn resolve_inlay_hint(
13391        &self,
13392        hint: InlayHint,
13393        buffer_handle: Model<Buffer>,
13394        server_id: LanguageServerId,
13395        cx: &mut AppContext,
13396    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13397
13398    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13399
13400    fn document_highlights(
13401        &self,
13402        buffer: &Model<Buffer>,
13403        position: text::Anchor,
13404        cx: &mut AppContext,
13405    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13406
13407    fn definitions(
13408        &self,
13409        buffer: &Model<Buffer>,
13410        position: text::Anchor,
13411        kind: GotoDefinitionKind,
13412        cx: &mut AppContext,
13413    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13414
13415    fn range_for_rename(
13416        &self,
13417        buffer: &Model<Buffer>,
13418        position: text::Anchor,
13419        cx: &mut AppContext,
13420    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13421
13422    fn perform_rename(
13423        &self,
13424        buffer: &Model<Buffer>,
13425        position: text::Anchor,
13426        new_name: String,
13427        cx: &mut AppContext,
13428    ) -> Option<Task<Result<ProjectTransaction>>>;
13429}
13430
13431pub trait CompletionProvider {
13432    fn completions(
13433        &self,
13434        buffer: &Model<Buffer>,
13435        buffer_position: text::Anchor,
13436        trigger: CompletionContext,
13437        cx: &mut ViewContext<Editor>,
13438    ) -> Task<Result<Vec<Completion>>>;
13439
13440    fn resolve_completions(
13441        &self,
13442        buffer: Model<Buffer>,
13443        completion_indices: Vec<usize>,
13444        completions: Rc<RefCell<Box<[Completion]>>>,
13445        cx: &mut ViewContext<Editor>,
13446    ) -> Task<Result<bool>>;
13447
13448    fn apply_additional_edits_for_completion(
13449        &self,
13450        buffer: Model<Buffer>,
13451        completion: Completion,
13452        push_to_history: bool,
13453        cx: &mut ViewContext<Editor>,
13454    ) -> Task<Result<Option<language::Transaction>>>;
13455
13456    fn is_completion_trigger(
13457        &self,
13458        buffer: &Model<Buffer>,
13459        position: language::Anchor,
13460        text: &str,
13461        trigger_in_words: bool,
13462        cx: &mut ViewContext<Editor>,
13463    ) -> bool;
13464
13465    fn sort_completions(&self) -> bool {
13466        true
13467    }
13468}
13469
13470pub trait CodeActionProvider {
13471    fn code_actions(
13472        &self,
13473        buffer: &Model<Buffer>,
13474        range: Range<text::Anchor>,
13475        cx: &mut WindowContext,
13476    ) -> Task<Result<Vec<CodeAction>>>;
13477
13478    fn apply_code_action(
13479        &self,
13480        buffer_handle: Model<Buffer>,
13481        action: CodeAction,
13482        excerpt_id: ExcerptId,
13483        push_to_history: bool,
13484        cx: &mut WindowContext,
13485    ) -> Task<Result<ProjectTransaction>>;
13486}
13487
13488impl CodeActionProvider for Model<Project> {
13489    fn code_actions(
13490        &self,
13491        buffer: &Model<Buffer>,
13492        range: Range<text::Anchor>,
13493        cx: &mut WindowContext,
13494    ) -> Task<Result<Vec<CodeAction>>> {
13495        self.update(cx, |project, cx| {
13496            project.code_actions(buffer, range, None, cx)
13497        })
13498    }
13499
13500    fn apply_code_action(
13501        &self,
13502        buffer_handle: Model<Buffer>,
13503        action: CodeAction,
13504        _excerpt_id: ExcerptId,
13505        push_to_history: bool,
13506        cx: &mut WindowContext,
13507    ) -> Task<Result<ProjectTransaction>> {
13508        self.update(cx, |project, cx| {
13509            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13510        })
13511    }
13512}
13513
13514fn snippet_completions(
13515    project: &Project,
13516    buffer: &Model<Buffer>,
13517    buffer_position: text::Anchor,
13518    cx: &mut AppContext,
13519) -> Task<Result<Vec<Completion>>> {
13520    let language = buffer.read(cx).language_at(buffer_position);
13521    let language_name = language.as_ref().map(|language| language.lsp_id());
13522    let snippet_store = project.snippets().read(cx);
13523    let snippets = snippet_store.snippets_for(language_name, cx);
13524
13525    if snippets.is_empty() {
13526        return Task::ready(Ok(vec![]));
13527    }
13528    let snapshot = buffer.read(cx).text_snapshot();
13529    let chars: String = snapshot
13530        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13531        .collect();
13532
13533    let scope = language.map(|language| language.default_scope());
13534    let executor = cx.background_executor().clone();
13535
13536    cx.background_executor().spawn(async move {
13537        let classifier = CharClassifier::new(scope).for_completion(true);
13538        let mut last_word = chars
13539            .chars()
13540            .take_while(|c| classifier.is_word(*c))
13541            .collect::<String>();
13542        last_word = last_word.chars().rev().collect();
13543
13544        if last_word.is_empty() {
13545            return Ok(vec![]);
13546        }
13547
13548        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13549        let to_lsp = |point: &text::Anchor| {
13550            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13551            point_to_lsp(end)
13552        };
13553        let lsp_end = to_lsp(&buffer_position);
13554
13555        let candidates = snippets
13556            .iter()
13557            .enumerate()
13558            .flat_map(|(ix, snippet)| {
13559                snippet
13560                    .prefix
13561                    .iter()
13562                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13563            })
13564            .collect::<Vec<StringMatchCandidate>>();
13565
13566        let mut matches = fuzzy::match_strings(
13567            &candidates,
13568            &last_word,
13569            last_word.chars().any(|c| c.is_uppercase()),
13570            100,
13571            &Default::default(),
13572            executor,
13573        )
13574        .await;
13575
13576        // Remove all candidates where the query's start does not match the start of any word in the candidate
13577        if let Some(query_start) = last_word.chars().next() {
13578            matches.retain(|string_match| {
13579                split_words(&string_match.string).any(|word| {
13580                    // Check that the first codepoint of the word as lowercase matches the first
13581                    // codepoint of the query as lowercase
13582                    word.chars()
13583                        .flat_map(|codepoint| codepoint.to_lowercase())
13584                        .zip(query_start.to_lowercase())
13585                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13586                })
13587            });
13588        }
13589
13590        let matched_strings = matches
13591            .into_iter()
13592            .map(|m| m.string)
13593            .collect::<HashSet<_>>();
13594
13595        let result: Vec<Completion> = snippets
13596            .into_iter()
13597            .filter_map(|snippet| {
13598                let matching_prefix = snippet
13599                    .prefix
13600                    .iter()
13601                    .find(|prefix| matched_strings.contains(*prefix))?;
13602                let start = as_offset - last_word.len();
13603                let start = snapshot.anchor_before(start);
13604                let range = start..buffer_position;
13605                let lsp_start = to_lsp(&start);
13606                let lsp_range = lsp::Range {
13607                    start: lsp_start,
13608                    end: lsp_end,
13609                };
13610                Some(Completion {
13611                    old_range: range,
13612                    new_text: snippet.body.clone(),
13613                    label: CodeLabel {
13614                        text: matching_prefix.clone(),
13615                        runs: vec![],
13616                        filter_range: 0..matching_prefix.len(),
13617                    },
13618                    server_id: LanguageServerId(usize::MAX),
13619                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13620                    lsp_completion: lsp::CompletionItem {
13621                        label: snippet.prefix.first().unwrap().clone(),
13622                        kind: Some(CompletionItemKind::SNIPPET),
13623                        label_details: snippet.description.as_ref().map(|description| {
13624                            lsp::CompletionItemLabelDetails {
13625                                detail: Some(description.clone()),
13626                                description: None,
13627                            }
13628                        }),
13629                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13630                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13631                            lsp::InsertReplaceEdit {
13632                                new_text: snippet.body.clone(),
13633                                insert: lsp_range,
13634                                replace: lsp_range,
13635                            },
13636                        )),
13637                        filter_text: Some(snippet.body.clone()),
13638                        sort_text: Some(char::MAX.to_string()),
13639                        ..Default::default()
13640                    },
13641                    confirm: None,
13642                })
13643            })
13644            .collect();
13645
13646        Ok(result)
13647    })
13648}
13649
13650impl CompletionProvider for Model<Project> {
13651    fn completions(
13652        &self,
13653        buffer: &Model<Buffer>,
13654        buffer_position: text::Anchor,
13655        options: CompletionContext,
13656        cx: &mut ViewContext<Editor>,
13657    ) -> Task<Result<Vec<Completion>>> {
13658        self.update(cx, |project, cx| {
13659            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13660            let project_completions = project.completions(buffer, buffer_position, options, cx);
13661            cx.background_executor().spawn(async move {
13662                let mut completions = project_completions.await?;
13663                let snippets_completions = snippets.await?;
13664                completions.extend(snippets_completions);
13665                Ok(completions)
13666            })
13667        })
13668    }
13669
13670    fn resolve_completions(
13671        &self,
13672        buffer: Model<Buffer>,
13673        completion_indices: Vec<usize>,
13674        completions: Rc<RefCell<Box<[Completion]>>>,
13675        cx: &mut ViewContext<Editor>,
13676    ) -> Task<Result<bool>> {
13677        self.update(cx, |project, cx| {
13678            project.resolve_completions(buffer, completion_indices, completions, cx)
13679        })
13680    }
13681
13682    fn apply_additional_edits_for_completion(
13683        &self,
13684        buffer: Model<Buffer>,
13685        completion: Completion,
13686        push_to_history: bool,
13687        cx: &mut ViewContext<Editor>,
13688    ) -> Task<Result<Option<language::Transaction>>> {
13689        self.update(cx, |project, cx| {
13690            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13691        })
13692    }
13693
13694    fn is_completion_trigger(
13695        &self,
13696        buffer: &Model<Buffer>,
13697        position: language::Anchor,
13698        text: &str,
13699        trigger_in_words: bool,
13700        cx: &mut ViewContext<Editor>,
13701    ) -> bool {
13702        let mut chars = text.chars();
13703        let char = if let Some(char) = chars.next() {
13704            char
13705        } else {
13706            return false;
13707        };
13708        if chars.next().is_some() {
13709            return false;
13710        }
13711
13712        let buffer = buffer.read(cx);
13713        let snapshot = buffer.snapshot();
13714        if !snapshot.settings_at(position, cx).show_completions_on_input {
13715            return false;
13716        }
13717        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13718        if trigger_in_words && classifier.is_word(char) {
13719            return true;
13720        }
13721
13722        buffer.completion_triggers().contains(text)
13723    }
13724}
13725
13726impl SemanticsProvider for Model<Project> {
13727    fn hover(
13728        &self,
13729        buffer: &Model<Buffer>,
13730        position: text::Anchor,
13731        cx: &mut AppContext,
13732    ) -> Option<Task<Vec<project::Hover>>> {
13733        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13734    }
13735
13736    fn document_highlights(
13737        &self,
13738        buffer: &Model<Buffer>,
13739        position: text::Anchor,
13740        cx: &mut AppContext,
13741    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13742        Some(self.update(cx, |project, cx| {
13743            project.document_highlights(buffer, position, cx)
13744        }))
13745    }
13746
13747    fn definitions(
13748        &self,
13749        buffer: &Model<Buffer>,
13750        position: text::Anchor,
13751        kind: GotoDefinitionKind,
13752        cx: &mut AppContext,
13753    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13754        Some(self.update(cx, |project, cx| match kind {
13755            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13756            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13757            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13758            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13759        }))
13760    }
13761
13762    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13763        // TODO: make this work for remote projects
13764        self.read(cx)
13765            .language_servers_for_local_buffer(buffer.read(cx), cx)
13766            .any(
13767                |(_, server)| match server.capabilities().inlay_hint_provider {
13768                    Some(lsp::OneOf::Left(enabled)) => enabled,
13769                    Some(lsp::OneOf::Right(_)) => true,
13770                    None => false,
13771                },
13772            )
13773    }
13774
13775    fn inlay_hints(
13776        &self,
13777        buffer_handle: Model<Buffer>,
13778        range: Range<text::Anchor>,
13779        cx: &mut AppContext,
13780    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13781        Some(self.update(cx, |project, cx| {
13782            project.inlay_hints(buffer_handle, range, cx)
13783        }))
13784    }
13785
13786    fn resolve_inlay_hint(
13787        &self,
13788        hint: InlayHint,
13789        buffer_handle: Model<Buffer>,
13790        server_id: LanguageServerId,
13791        cx: &mut AppContext,
13792    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13793        Some(self.update(cx, |project, cx| {
13794            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13795        }))
13796    }
13797
13798    fn range_for_rename(
13799        &self,
13800        buffer: &Model<Buffer>,
13801        position: text::Anchor,
13802        cx: &mut AppContext,
13803    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13804        Some(self.update(cx, |project, cx| {
13805            project.prepare_rename(buffer.clone(), position, cx)
13806        }))
13807    }
13808
13809    fn perform_rename(
13810        &self,
13811        buffer: &Model<Buffer>,
13812        position: text::Anchor,
13813        new_name: String,
13814        cx: &mut AppContext,
13815    ) -> Option<Task<Result<ProjectTransaction>>> {
13816        Some(self.update(cx, |project, cx| {
13817            project.perform_rename(buffer.clone(), position, new_name, cx)
13818        }))
13819    }
13820}
13821
13822fn inlay_hint_settings(
13823    location: Anchor,
13824    snapshot: &MultiBufferSnapshot,
13825    cx: &mut ViewContext<'_, Editor>,
13826) -> InlayHintSettings {
13827    let file = snapshot.file_at(location);
13828    let language = snapshot.language_at(location).map(|l| l.name());
13829    language_settings(language, file, cx).inlay_hints
13830}
13831
13832fn consume_contiguous_rows(
13833    contiguous_row_selections: &mut Vec<Selection<Point>>,
13834    selection: &Selection<Point>,
13835    display_map: &DisplaySnapshot,
13836    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13837) -> (MultiBufferRow, MultiBufferRow) {
13838    contiguous_row_selections.push(selection.clone());
13839    let start_row = MultiBufferRow(selection.start.row);
13840    let mut end_row = ending_row(selection, display_map);
13841
13842    while let Some(next_selection) = selections.peek() {
13843        if next_selection.start.row <= end_row.0 {
13844            end_row = ending_row(next_selection, display_map);
13845            contiguous_row_selections.push(selections.next().unwrap().clone());
13846        } else {
13847            break;
13848        }
13849    }
13850    (start_row, end_row)
13851}
13852
13853fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13854    if next_selection.end.column > 0 || next_selection.is_empty() {
13855        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13856    } else {
13857        MultiBufferRow(next_selection.end.row)
13858    }
13859}
13860
13861impl EditorSnapshot {
13862    pub fn remote_selections_in_range<'a>(
13863        &'a self,
13864        range: &'a Range<Anchor>,
13865        collaboration_hub: &dyn CollaborationHub,
13866        cx: &'a AppContext,
13867    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13868        let participant_names = collaboration_hub.user_names(cx);
13869        let participant_indices = collaboration_hub.user_participant_indices(cx);
13870        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13871        let collaborators_by_replica_id = collaborators_by_peer_id
13872            .iter()
13873            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13874            .collect::<HashMap<_, _>>();
13875        self.buffer_snapshot
13876            .selections_in_range(range, false)
13877            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13878                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13879                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13880                let user_name = participant_names.get(&collaborator.user_id).cloned();
13881                Some(RemoteSelection {
13882                    replica_id,
13883                    selection,
13884                    cursor_shape,
13885                    line_mode,
13886                    participant_index,
13887                    peer_id: collaborator.peer_id,
13888                    user_name,
13889                })
13890            })
13891    }
13892
13893    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13894        self.display_snapshot.buffer_snapshot.language_at(position)
13895    }
13896
13897    pub fn is_focused(&self) -> bool {
13898        self.is_focused
13899    }
13900
13901    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13902        self.placeholder_text.as_ref()
13903    }
13904
13905    pub fn scroll_position(&self) -> gpui::Point<f32> {
13906        self.scroll_anchor.scroll_position(&self.display_snapshot)
13907    }
13908
13909    fn gutter_dimensions(
13910        &self,
13911        font_id: FontId,
13912        font_size: Pixels,
13913        em_width: Pixels,
13914        em_advance: Pixels,
13915        max_line_number_width: Pixels,
13916        cx: &AppContext,
13917    ) -> GutterDimensions {
13918        if !self.show_gutter {
13919            return GutterDimensions::default();
13920        }
13921        let descent = cx.text_system().descent(font_id, font_size);
13922
13923        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13924            matches!(
13925                ProjectSettings::get_global(cx).git.git_gutter,
13926                Some(GitGutterSetting::TrackedFiles)
13927            )
13928        });
13929        let gutter_settings = EditorSettings::get_global(cx).gutter;
13930        let show_line_numbers = self
13931            .show_line_numbers
13932            .unwrap_or(gutter_settings.line_numbers);
13933        let line_gutter_width = if show_line_numbers {
13934            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13935            let min_width_for_number_on_gutter = em_advance * 4.0;
13936            max_line_number_width.max(min_width_for_number_on_gutter)
13937        } else {
13938            0.0.into()
13939        };
13940
13941        let show_code_actions = self
13942            .show_code_actions
13943            .unwrap_or(gutter_settings.code_actions);
13944
13945        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13946
13947        let git_blame_entries_width =
13948            self.git_blame_gutter_max_author_length
13949                .map(|max_author_length| {
13950                    // Length of the author name, but also space for the commit hash,
13951                    // the spacing and the timestamp.
13952                    let max_char_count = max_author_length
13953                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13954                        + 7 // length of commit sha
13955                        + 14 // length of max relative timestamp ("60 minutes ago")
13956                        + 4; // gaps and margins
13957
13958                    em_advance * max_char_count
13959                });
13960
13961        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13962        left_padding += if show_code_actions || show_runnables {
13963            em_width * 3.0
13964        } else if show_git_gutter && show_line_numbers {
13965            em_width * 2.0
13966        } else if show_git_gutter || show_line_numbers {
13967            em_width
13968        } else {
13969            px(0.)
13970        };
13971
13972        let right_padding = if gutter_settings.folds && show_line_numbers {
13973            em_width * 4.0
13974        } else if gutter_settings.folds {
13975            em_width * 3.0
13976        } else if show_line_numbers {
13977            em_width
13978        } else {
13979            px(0.)
13980        };
13981
13982        GutterDimensions {
13983            left_padding,
13984            right_padding,
13985            width: line_gutter_width + left_padding + right_padding,
13986            margin: -descent,
13987            git_blame_entries_width,
13988        }
13989    }
13990
13991    pub fn render_crease_toggle(
13992        &self,
13993        buffer_row: MultiBufferRow,
13994        row_contains_cursor: bool,
13995        editor: View<Editor>,
13996        cx: &mut WindowContext,
13997    ) -> Option<AnyElement> {
13998        let folded = self.is_line_folded(buffer_row);
13999        let mut is_foldable = false;
14000
14001        if let Some(crease) = self
14002            .crease_snapshot
14003            .query_row(buffer_row, &self.buffer_snapshot)
14004        {
14005            is_foldable = true;
14006            match crease {
14007                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14008                    if let Some(render_toggle) = render_toggle {
14009                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14010                            if folded {
14011                                editor.update(cx, |editor, cx| {
14012                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14013                                });
14014                            } else {
14015                                editor.update(cx, |editor, cx| {
14016                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14017                                });
14018                            }
14019                        });
14020                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14021                    }
14022                }
14023            }
14024        }
14025
14026        is_foldable |= self.starts_indent(buffer_row);
14027
14028        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14029            Some(
14030                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14031                    .toggle_state(folded)
14032                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14033                        if folded {
14034                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14035                        } else {
14036                            this.fold_at(&FoldAt { buffer_row }, cx);
14037                        }
14038                    }))
14039                    .into_any_element(),
14040            )
14041        } else {
14042            None
14043        }
14044    }
14045
14046    pub fn render_crease_trailer(
14047        &self,
14048        buffer_row: MultiBufferRow,
14049        cx: &mut WindowContext,
14050    ) -> Option<AnyElement> {
14051        let folded = self.is_line_folded(buffer_row);
14052        if let Crease::Inline { render_trailer, .. } = self
14053            .crease_snapshot
14054            .query_row(buffer_row, &self.buffer_snapshot)?
14055        {
14056            let render_trailer = render_trailer.as_ref()?;
14057            Some(render_trailer(buffer_row, folded, cx))
14058        } else {
14059            None
14060        }
14061    }
14062}
14063
14064impl Deref for EditorSnapshot {
14065    type Target = DisplaySnapshot;
14066
14067    fn deref(&self) -> &Self::Target {
14068        &self.display_snapshot
14069    }
14070}
14071
14072#[derive(Clone, Debug, PartialEq, Eq)]
14073pub enum EditorEvent {
14074    InputIgnored {
14075        text: Arc<str>,
14076    },
14077    InputHandled {
14078        utf16_range_to_replace: Option<Range<isize>>,
14079        text: Arc<str>,
14080    },
14081    ExcerptsAdded {
14082        buffer: Model<Buffer>,
14083        predecessor: ExcerptId,
14084        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14085    },
14086    ExcerptsRemoved {
14087        ids: Vec<ExcerptId>,
14088    },
14089    BufferFoldToggled {
14090        ids: Vec<ExcerptId>,
14091        folded: bool,
14092    },
14093    ExcerptsEdited {
14094        ids: Vec<ExcerptId>,
14095    },
14096    ExcerptsExpanded {
14097        ids: Vec<ExcerptId>,
14098    },
14099    BufferEdited,
14100    Edited {
14101        transaction_id: clock::Lamport,
14102    },
14103    Reparsed(BufferId),
14104    Focused,
14105    FocusedIn,
14106    Blurred,
14107    DirtyChanged,
14108    Saved,
14109    TitleChanged,
14110    DiffBaseChanged,
14111    SelectionsChanged {
14112        local: bool,
14113    },
14114    ScrollPositionChanged {
14115        local: bool,
14116        autoscroll: bool,
14117    },
14118    Closed,
14119    TransactionUndone {
14120        transaction_id: clock::Lamport,
14121    },
14122    TransactionBegun {
14123        transaction_id: clock::Lamport,
14124    },
14125    Reloaded,
14126    CursorShapeChanged,
14127}
14128
14129impl EventEmitter<EditorEvent> for Editor {}
14130
14131impl FocusableView for Editor {
14132    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14133        self.focus_handle.clone()
14134    }
14135}
14136
14137impl Render for Editor {
14138    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14139        let settings = ThemeSettings::get_global(cx);
14140
14141        let mut text_style = match self.mode {
14142            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14143                color: cx.theme().colors().editor_foreground,
14144                font_family: settings.ui_font.family.clone(),
14145                font_features: settings.ui_font.features.clone(),
14146                font_fallbacks: settings.ui_font.fallbacks.clone(),
14147                font_size: rems(0.875).into(),
14148                font_weight: settings.ui_font.weight,
14149                line_height: relative(settings.buffer_line_height.value()),
14150                ..Default::default()
14151            },
14152            EditorMode::Full => TextStyle {
14153                color: cx.theme().colors().editor_foreground,
14154                font_family: settings.buffer_font.family.clone(),
14155                font_features: settings.buffer_font.features.clone(),
14156                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14157                font_size: settings.buffer_font_size(cx).into(),
14158                font_weight: settings.buffer_font.weight,
14159                line_height: relative(settings.buffer_line_height.value()),
14160                ..Default::default()
14161            },
14162        };
14163        if let Some(text_style_refinement) = &self.text_style_refinement {
14164            text_style.refine(text_style_refinement)
14165        }
14166
14167        let background = match self.mode {
14168            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14169            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14170            EditorMode::Full => cx.theme().colors().editor_background,
14171        };
14172
14173        EditorElement::new(
14174            cx.view(),
14175            EditorStyle {
14176                background,
14177                local_player: cx.theme().players().local(),
14178                text: text_style,
14179                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14180                syntax: cx.theme().syntax().clone(),
14181                status: cx.theme().status().clone(),
14182                inlay_hints_style: make_inlay_hints_style(cx),
14183                inline_completion_styles: make_suggestion_styles(cx),
14184                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14185            },
14186        )
14187    }
14188}
14189
14190impl ViewInputHandler for Editor {
14191    fn text_for_range(
14192        &mut self,
14193        range_utf16: Range<usize>,
14194        adjusted_range: &mut Option<Range<usize>>,
14195        cx: &mut ViewContext<Self>,
14196    ) -> Option<String> {
14197        let snapshot = self.buffer.read(cx).read(cx);
14198        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14199        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14200        if (start.0..end.0) != range_utf16 {
14201            adjusted_range.replace(start.0..end.0);
14202        }
14203        Some(snapshot.text_for_range(start..end).collect())
14204    }
14205
14206    fn selected_text_range(
14207        &mut self,
14208        ignore_disabled_input: bool,
14209        cx: &mut ViewContext<Self>,
14210    ) -> Option<UTF16Selection> {
14211        // Prevent the IME menu from appearing when holding down an alphabetic key
14212        // while input is disabled.
14213        if !ignore_disabled_input && !self.input_enabled {
14214            return None;
14215        }
14216
14217        let selection = self.selections.newest::<OffsetUtf16>(cx);
14218        let range = selection.range();
14219
14220        Some(UTF16Selection {
14221            range: range.start.0..range.end.0,
14222            reversed: selection.reversed,
14223        })
14224    }
14225
14226    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14227        let snapshot = self.buffer.read(cx).read(cx);
14228        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14229        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14230    }
14231
14232    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14233        self.clear_highlights::<InputComposition>(cx);
14234        self.ime_transaction.take();
14235    }
14236
14237    fn replace_text_in_range(
14238        &mut self,
14239        range_utf16: Option<Range<usize>>,
14240        text: &str,
14241        cx: &mut ViewContext<Self>,
14242    ) {
14243        if !self.input_enabled {
14244            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14245            return;
14246        }
14247
14248        self.transact(cx, |this, cx| {
14249            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14250                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14251                Some(this.selection_replacement_ranges(range_utf16, cx))
14252            } else {
14253                this.marked_text_ranges(cx)
14254            };
14255
14256            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14257                let newest_selection_id = this.selections.newest_anchor().id;
14258                this.selections
14259                    .all::<OffsetUtf16>(cx)
14260                    .iter()
14261                    .zip(ranges_to_replace.iter())
14262                    .find_map(|(selection, range)| {
14263                        if selection.id == newest_selection_id {
14264                            Some(
14265                                (range.start.0 as isize - selection.head().0 as isize)
14266                                    ..(range.end.0 as isize - selection.head().0 as isize),
14267                            )
14268                        } else {
14269                            None
14270                        }
14271                    })
14272            });
14273
14274            cx.emit(EditorEvent::InputHandled {
14275                utf16_range_to_replace: range_to_replace,
14276                text: text.into(),
14277            });
14278
14279            if let Some(new_selected_ranges) = new_selected_ranges {
14280                this.change_selections(None, cx, |selections| {
14281                    selections.select_ranges(new_selected_ranges)
14282                });
14283                this.backspace(&Default::default(), cx);
14284            }
14285
14286            this.handle_input(text, cx);
14287        });
14288
14289        if let Some(transaction) = self.ime_transaction {
14290            self.buffer.update(cx, |buffer, cx| {
14291                buffer.group_until_transaction(transaction, cx);
14292            });
14293        }
14294
14295        self.unmark_text(cx);
14296    }
14297
14298    fn replace_and_mark_text_in_range(
14299        &mut self,
14300        range_utf16: Option<Range<usize>>,
14301        text: &str,
14302        new_selected_range_utf16: Option<Range<usize>>,
14303        cx: &mut ViewContext<Self>,
14304    ) {
14305        if !self.input_enabled {
14306            return;
14307        }
14308
14309        let transaction = self.transact(cx, |this, cx| {
14310            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14311                let snapshot = this.buffer.read(cx).read(cx);
14312                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14313                    for marked_range in &mut marked_ranges {
14314                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14315                        marked_range.start.0 += relative_range_utf16.start;
14316                        marked_range.start =
14317                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14318                        marked_range.end =
14319                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14320                    }
14321                }
14322                Some(marked_ranges)
14323            } else if let Some(range_utf16) = range_utf16 {
14324                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14325                Some(this.selection_replacement_ranges(range_utf16, cx))
14326            } else {
14327                None
14328            };
14329
14330            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14331                let newest_selection_id = this.selections.newest_anchor().id;
14332                this.selections
14333                    .all::<OffsetUtf16>(cx)
14334                    .iter()
14335                    .zip(ranges_to_replace.iter())
14336                    .find_map(|(selection, range)| {
14337                        if selection.id == newest_selection_id {
14338                            Some(
14339                                (range.start.0 as isize - selection.head().0 as isize)
14340                                    ..(range.end.0 as isize - selection.head().0 as isize),
14341                            )
14342                        } else {
14343                            None
14344                        }
14345                    })
14346            });
14347
14348            cx.emit(EditorEvent::InputHandled {
14349                utf16_range_to_replace: range_to_replace,
14350                text: text.into(),
14351            });
14352
14353            if let Some(ranges) = ranges_to_replace {
14354                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14355            }
14356
14357            let marked_ranges = {
14358                let snapshot = this.buffer.read(cx).read(cx);
14359                this.selections
14360                    .disjoint_anchors()
14361                    .iter()
14362                    .map(|selection| {
14363                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14364                    })
14365                    .collect::<Vec<_>>()
14366            };
14367
14368            if text.is_empty() {
14369                this.unmark_text(cx);
14370            } else {
14371                this.highlight_text::<InputComposition>(
14372                    marked_ranges.clone(),
14373                    HighlightStyle {
14374                        underline: Some(UnderlineStyle {
14375                            thickness: px(1.),
14376                            color: None,
14377                            wavy: false,
14378                        }),
14379                        ..Default::default()
14380                    },
14381                    cx,
14382                );
14383            }
14384
14385            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14386            let use_autoclose = this.use_autoclose;
14387            let use_auto_surround = this.use_auto_surround;
14388            this.set_use_autoclose(false);
14389            this.set_use_auto_surround(false);
14390            this.handle_input(text, cx);
14391            this.set_use_autoclose(use_autoclose);
14392            this.set_use_auto_surround(use_auto_surround);
14393
14394            if let Some(new_selected_range) = new_selected_range_utf16 {
14395                let snapshot = this.buffer.read(cx).read(cx);
14396                let new_selected_ranges = marked_ranges
14397                    .into_iter()
14398                    .map(|marked_range| {
14399                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14400                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14401                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14402                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14403                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14404                    })
14405                    .collect::<Vec<_>>();
14406
14407                drop(snapshot);
14408                this.change_selections(None, cx, |selections| {
14409                    selections.select_ranges(new_selected_ranges)
14410                });
14411            }
14412        });
14413
14414        self.ime_transaction = self.ime_transaction.or(transaction);
14415        if let Some(transaction) = self.ime_transaction {
14416            self.buffer.update(cx, |buffer, cx| {
14417                buffer.group_until_transaction(transaction, cx);
14418            });
14419        }
14420
14421        if self.text_highlights::<InputComposition>(cx).is_none() {
14422            self.ime_transaction.take();
14423        }
14424    }
14425
14426    fn bounds_for_range(
14427        &mut self,
14428        range_utf16: Range<usize>,
14429        element_bounds: gpui::Bounds<Pixels>,
14430        cx: &mut ViewContext<Self>,
14431    ) -> Option<gpui::Bounds<Pixels>> {
14432        let text_layout_details = self.text_layout_details(cx);
14433        let gpui::Point {
14434            x: em_width,
14435            y: line_height,
14436        } = self.character_size(cx);
14437
14438        let snapshot = self.snapshot(cx);
14439        let scroll_position = snapshot.scroll_position();
14440        let scroll_left = scroll_position.x * em_width;
14441
14442        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14443        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14444            + self.gutter_dimensions.width
14445            + self.gutter_dimensions.margin;
14446        let y = line_height * (start.row().as_f32() - scroll_position.y);
14447
14448        Some(Bounds {
14449            origin: element_bounds.origin + point(x, y),
14450            size: size(em_width, line_height),
14451        })
14452    }
14453}
14454
14455trait SelectionExt {
14456    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14457    fn spanned_rows(
14458        &self,
14459        include_end_if_at_line_start: bool,
14460        map: &DisplaySnapshot,
14461    ) -> Range<MultiBufferRow>;
14462}
14463
14464impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14465    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14466        let start = self
14467            .start
14468            .to_point(&map.buffer_snapshot)
14469            .to_display_point(map);
14470        let end = self
14471            .end
14472            .to_point(&map.buffer_snapshot)
14473            .to_display_point(map);
14474        if self.reversed {
14475            end..start
14476        } else {
14477            start..end
14478        }
14479    }
14480
14481    fn spanned_rows(
14482        &self,
14483        include_end_if_at_line_start: bool,
14484        map: &DisplaySnapshot,
14485    ) -> Range<MultiBufferRow> {
14486        let start = self.start.to_point(&map.buffer_snapshot);
14487        let mut end = self.end.to_point(&map.buffer_snapshot);
14488        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14489            end.row -= 1;
14490        }
14491
14492        let buffer_start = map.prev_line_boundary(start).0;
14493        let buffer_end = map.next_line_boundary(end).0;
14494        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14495    }
14496}
14497
14498impl<T: InvalidationRegion> InvalidationStack<T> {
14499    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14500    where
14501        S: Clone + ToOffset,
14502    {
14503        while let Some(region) = self.last() {
14504            let all_selections_inside_invalidation_ranges =
14505                if selections.len() == region.ranges().len() {
14506                    selections
14507                        .iter()
14508                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14509                        .all(|(selection, invalidation_range)| {
14510                            let head = selection.head().to_offset(buffer);
14511                            invalidation_range.start <= head && invalidation_range.end >= head
14512                        })
14513                } else {
14514                    false
14515                };
14516
14517            if all_selections_inside_invalidation_ranges {
14518                break;
14519            } else {
14520                self.pop();
14521            }
14522        }
14523    }
14524}
14525
14526impl<T> Default for InvalidationStack<T> {
14527    fn default() -> Self {
14528        Self(Default::default())
14529    }
14530}
14531
14532impl<T> Deref for InvalidationStack<T> {
14533    type Target = Vec<T>;
14534
14535    fn deref(&self) -> &Self::Target {
14536        &self.0
14537    }
14538}
14539
14540impl<T> DerefMut for InvalidationStack<T> {
14541    fn deref_mut(&mut self) -> &mut Self::Target {
14542        &mut self.0
14543    }
14544}
14545
14546impl InvalidationRegion for SnippetState {
14547    fn ranges(&self) -> &[Range<Anchor>] {
14548        &self.ranges[self.active_index]
14549    }
14550}
14551
14552pub fn diagnostic_block_renderer(
14553    diagnostic: Diagnostic,
14554    max_message_rows: Option<u8>,
14555    allow_closing: bool,
14556    _is_valid: bool,
14557) -> RenderBlock {
14558    let (text_without_backticks, code_ranges) =
14559        highlight_diagnostic_message(&diagnostic, max_message_rows);
14560
14561    Arc::new(move |cx: &mut BlockContext| {
14562        let group_id: SharedString = cx.block_id.to_string().into();
14563
14564        let mut text_style = cx.text_style().clone();
14565        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14566        let theme_settings = ThemeSettings::get_global(cx);
14567        text_style.font_family = theme_settings.buffer_font.family.clone();
14568        text_style.font_style = theme_settings.buffer_font.style;
14569        text_style.font_features = theme_settings.buffer_font.features.clone();
14570        text_style.font_weight = theme_settings.buffer_font.weight;
14571
14572        let multi_line_diagnostic = diagnostic.message.contains('\n');
14573
14574        let buttons = |diagnostic: &Diagnostic| {
14575            if multi_line_diagnostic {
14576                v_flex()
14577            } else {
14578                h_flex()
14579            }
14580            .when(allow_closing, |div| {
14581                div.children(diagnostic.is_primary.then(|| {
14582                    IconButton::new("close-block", IconName::XCircle)
14583                        .icon_color(Color::Muted)
14584                        .size(ButtonSize::Compact)
14585                        .style(ButtonStyle::Transparent)
14586                        .visible_on_hover(group_id.clone())
14587                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14588                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14589                }))
14590            })
14591            .child(
14592                IconButton::new("copy-block", IconName::Copy)
14593                    .icon_color(Color::Muted)
14594                    .size(ButtonSize::Compact)
14595                    .style(ButtonStyle::Transparent)
14596                    .visible_on_hover(group_id.clone())
14597                    .on_click({
14598                        let message = diagnostic.message.clone();
14599                        move |_click, cx| {
14600                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14601                        }
14602                    })
14603                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14604            )
14605        };
14606
14607        let icon_size = buttons(&diagnostic)
14608            .into_any_element()
14609            .layout_as_root(AvailableSpace::min_size(), cx);
14610
14611        h_flex()
14612            .id(cx.block_id)
14613            .group(group_id.clone())
14614            .relative()
14615            .size_full()
14616            .block_mouse_down()
14617            .pl(cx.gutter_dimensions.width)
14618            .w(cx.max_width - cx.gutter_dimensions.full_width())
14619            .child(
14620                div()
14621                    .flex()
14622                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14623                    .flex_shrink(),
14624            )
14625            .child(buttons(&diagnostic))
14626            .child(div().flex().flex_shrink_0().child(
14627                StyledText::new(text_without_backticks.clone()).with_highlights(
14628                    &text_style,
14629                    code_ranges.iter().map(|range| {
14630                        (
14631                            range.clone(),
14632                            HighlightStyle {
14633                                font_weight: Some(FontWeight::BOLD),
14634                                ..Default::default()
14635                            },
14636                        )
14637                    }),
14638                ),
14639            ))
14640            .into_any_element()
14641    })
14642}
14643
14644fn inline_completion_edit_text(
14645    editor_snapshot: &EditorSnapshot,
14646    edits: &Vec<(Range<Anchor>, String)>,
14647    include_deletions: bool,
14648    cx: &WindowContext,
14649) -> InlineCompletionText {
14650    let edit_start = edits
14651        .first()
14652        .unwrap()
14653        .0
14654        .start
14655        .to_display_point(editor_snapshot);
14656
14657    let mut text = String::new();
14658    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14659    let mut highlights = Vec::new();
14660    for (old_range, new_text) in edits {
14661        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14662        text.extend(
14663            editor_snapshot
14664                .buffer_snapshot
14665                .chunks(offset..old_offset_range.start, false)
14666                .map(|chunk| chunk.text),
14667        );
14668        offset = old_offset_range.end;
14669
14670        let start = text.len();
14671        let color = if include_deletions && new_text.is_empty() {
14672            text.extend(
14673                editor_snapshot
14674                    .buffer_snapshot
14675                    .chunks(old_offset_range.start..offset, false)
14676                    .map(|chunk| chunk.text),
14677            );
14678            cx.theme().status().deleted_background
14679        } else {
14680            text.push_str(new_text);
14681            cx.theme().status().created_background
14682        };
14683        let end = text.len();
14684
14685        highlights.push((
14686            start..end,
14687            HighlightStyle {
14688                background_color: Some(color),
14689                ..Default::default()
14690            },
14691        ));
14692    }
14693
14694    let edit_end = edits
14695        .last()
14696        .unwrap()
14697        .0
14698        .end
14699        .to_display_point(editor_snapshot);
14700    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14701        .to_offset(editor_snapshot, Bias::Right);
14702    text.extend(
14703        editor_snapshot
14704            .buffer_snapshot
14705            .chunks(offset..end_of_line, false)
14706            .map(|chunk| chunk.text),
14707    );
14708
14709    InlineCompletionText::Edit {
14710        text: text.into(),
14711        highlights,
14712    }
14713}
14714
14715pub fn highlight_diagnostic_message(
14716    diagnostic: &Diagnostic,
14717    mut max_message_rows: Option<u8>,
14718) -> (SharedString, Vec<Range<usize>>) {
14719    let mut text_without_backticks = String::new();
14720    let mut code_ranges = Vec::new();
14721
14722    if let Some(source) = &diagnostic.source {
14723        text_without_backticks.push_str(source);
14724        code_ranges.push(0..source.len());
14725        text_without_backticks.push_str(": ");
14726    }
14727
14728    let mut prev_offset = 0;
14729    let mut in_code_block = false;
14730    let has_row_limit = max_message_rows.is_some();
14731    let mut newline_indices = diagnostic
14732        .message
14733        .match_indices('\n')
14734        .filter(|_| has_row_limit)
14735        .map(|(ix, _)| ix)
14736        .fuse()
14737        .peekable();
14738
14739    for (quote_ix, _) in diagnostic
14740        .message
14741        .match_indices('`')
14742        .chain([(diagnostic.message.len(), "")])
14743    {
14744        let mut first_newline_ix = None;
14745        let mut last_newline_ix = None;
14746        while let Some(newline_ix) = newline_indices.peek() {
14747            if *newline_ix < quote_ix {
14748                if first_newline_ix.is_none() {
14749                    first_newline_ix = Some(*newline_ix);
14750                }
14751                last_newline_ix = Some(*newline_ix);
14752
14753                if let Some(rows_left) = &mut max_message_rows {
14754                    if *rows_left == 0 {
14755                        break;
14756                    } else {
14757                        *rows_left -= 1;
14758                    }
14759                }
14760                let _ = newline_indices.next();
14761            } else {
14762                break;
14763            }
14764        }
14765        let prev_len = text_without_backticks.len();
14766        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14767        text_without_backticks.push_str(new_text);
14768        if in_code_block {
14769            code_ranges.push(prev_len..text_without_backticks.len());
14770        }
14771        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14772        in_code_block = !in_code_block;
14773        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14774            text_without_backticks.push_str("...");
14775            break;
14776        }
14777    }
14778
14779    (text_without_backticks.into(), code_ranges)
14780}
14781
14782fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14783    match severity {
14784        DiagnosticSeverity::ERROR => colors.error,
14785        DiagnosticSeverity::WARNING => colors.warning,
14786        DiagnosticSeverity::INFORMATION => colors.info,
14787        DiagnosticSeverity::HINT => colors.info,
14788        _ => colors.ignored,
14789    }
14790}
14791
14792pub fn styled_runs_for_code_label<'a>(
14793    label: &'a CodeLabel,
14794    syntax_theme: &'a theme::SyntaxTheme,
14795) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14796    let fade_out = HighlightStyle {
14797        fade_out: Some(0.35),
14798        ..Default::default()
14799    };
14800
14801    let mut prev_end = label.filter_range.end;
14802    label
14803        .runs
14804        .iter()
14805        .enumerate()
14806        .flat_map(move |(ix, (range, highlight_id))| {
14807            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14808                style
14809            } else {
14810                return Default::default();
14811            };
14812            let mut muted_style = style;
14813            muted_style.highlight(fade_out);
14814
14815            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14816            if range.start >= label.filter_range.end {
14817                if range.start > prev_end {
14818                    runs.push((prev_end..range.start, fade_out));
14819                }
14820                runs.push((range.clone(), muted_style));
14821            } else if range.end <= label.filter_range.end {
14822                runs.push((range.clone(), style));
14823            } else {
14824                runs.push((range.start..label.filter_range.end, style));
14825                runs.push((label.filter_range.end..range.end, muted_style));
14826            }
14827            prev_end = cmp::max(prev_end, range.end);
14828
14829            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14830                runs.push((prev_end..label.text.len(), fade_out));
14831            }
14832
14833            runs
14834        })
14835}
14836
14837pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14838    let mut prev_index = 0;
14839    let mut prev_codepoint: Option<char> = None;
14840    text.char_indices()
14841        .chain([(text.len(), '\0')])
14842        .filter_map(move |(index, codepoint)| {
14843            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14844            let is_boundary = index == text.len()
14845                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14846                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14847            if is_boundary {
14848                let chunk = &text[prev_index..index];
14849                prev_index = index;
14850                Some(chunk)
14851            } else {
14852                None
14853            }
14854        })
14855}
14856
14857pub trait RangeToAnchorExt: Sized {
14858    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14859
14860    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14861        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14862        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14863    }
14864}
14865
14866impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14867    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14868        let start_offset = self.start.to_offset(snapshot);
14869        let end_offset = self.end.to_offset(snapshot);
14870        if start_offset == end_offset {
14871            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14872        } else {
14873            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14874        }
14875    }
14876}
14877
14878pub trait RowExt {
14879    fn as_f32(&self) -> f32;
14880
14881    fn next_row(&self) -> Self;
14882
14883    fn previous_row(&self) -> Self;
14884
14885    fn minus(&self, other: Self) -> u32;
14886}
14887
14888impl RowExt for DisplayRow {
14889    fn as_f32(&self) -> f32 {
14890        self.0 as f32
14891    }
14892
14893    fn next_row(&self) -> Self {
14894        Self(self.0 + 1)
14895    }
14896
14897    fn previous_row(&self) -> Self {
14898        Self(self.0.saturating_sub(1))
14899    }
14900
14901    fn minus(&self, other: Self) -> u32 {
14902        self.0 - other.0
14903    }
14904}
14905
14906impl RowExt for MultiBufferRow {
14907    fn as_f32(&self) -> f32 {
14908        self.0 as f32
14909    }
14910
14911    fn next_row(&self) -> Self {
14912        Self(self.0 + 1)
14913    }
14914
14915    fn previous_row(&self) -> Self {
14916        Self(self.0.saturating_sub(1))
14917    }
14918
14919    fn minus(&self, other: Self) -> u32 {
14920        self.0 - other.0
14921    }
14922}
14923
14924trait RowRangeExt {
14925    type Row;
14926
14927    fn len(&self) -> usize;
14928
14929    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14930}
14931
14932impl RowRangeExt for Range<MultiBufferRow> {
14933    type Row = MultiBufferRow;
14934
14935    fn len(&self) -> usize {
14936        (self.end.0 - self.start.0) as usize
14937    }
14938
14939    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14940        (self.start.0..self.end.0).map(MultiBufferRow)
14941    }
14942}
14943
14944impl RowRangeExt for Range<DisplayRow> {
14945    type Row = DisplayRow;
14946
14947    fn len(&self) -> usize {
14948        (self.end.0 - self.start.0) as usize
14949    }
14950
14951    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14952        (self.start.0..self.end.0).map(DisplayRow)
14953    }
14954}
14955
14956fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14957    if hunk.diff_base_byte_range.is_empty() {
14958        DiffHunkStatus::Added
14959    } else if hunk.row_range.is_empty() {
14960        DiffHunkStatus::Removed
14961    } else {
14962        DiffHunkStatus::Modified
14963    }
14964}
14965
14966/// If select range has more than one line, we
14967/// just point the cursor to range.start.
14968fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14969    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14970        range
14971    } else {
14972        range.start..range.start
14973    }
14974}
14975
14976pub struct KillRing(ClipboardItem);
14977impl Global for KillRing {}
14978
14979const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);