editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod code_context_menus;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51use ::git::diff::DiffHunkStatus;
   52pub(crate) use actions::*;
   53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{anyhow, Context as _, Result};
   56use blink_manager::BlinkManager;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::StringMatchCandidate;
   73
   74use code_context_menus::{
   75    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   76    CompletionEntry, CompletionsMenu, ContextMenuOrigin,
   77};
   78use git::blame::GitBlame;
   79use gpui::{
   80    div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
   81    AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
   82    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
   83    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
   84    MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
   85    Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   87    WeakView, WindowContext,
   88};
   89use highlight_matching_bracket::refresh_matching_bracket_highlights;
   90use hover_popover::{hide_hover, HoverState};
   91pub(crate) use hunk_diff::HoveredHunk;
   92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CursorShape, Diagnostic, DiagnosticEntry, Documentation, IndentKind, IndentSize, Language,
  103    OffsetRangeExt, Point, Selection, SelectionGoal, TransactionId,
  104};
  105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  106use linked_editing_ranges::refresh_linked_ranges;
  107use mouse_context_menu::MouseContextMenu;
  108pub use proposed_changes_editor::{
  109    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  110};
  111use similar::{ChangeTag, TextDiff};
  112use std::iter::Peekable;
  113use task::{ResolvedTask, TaskTemplate, TaskVariables};
  114
  115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  116pub use lsp::CompletionContext;
  117use lsp::{
  118    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  119    LanguageServerId, LanguageServerName,
  120};
  121
  122use movement::TextLayoutDetails;
  123pub use multi_buffer::{
  124    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  125    ToPoint,
  126};
  127use multi_buffer::{
  128    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  129};
  130use project::{
  131    buffer_store::BufferChangeSet,
  132    lsp_store::{FormatTarget, FormatTrigger, OpenLspBufferHandle},
  133    project_settings::{GitGutterSetting, ProjectSettings},
  134    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  135    LspStore, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  136};
  137use rand::prelude::*;
  138use rpc::{proto::*, ErrorExt};
  139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  140use selections_collection::{
  141    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  142};
  143use serde::{Deserialize, Serialize};
  144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  145use smallvec::SmallVec;
  146use snippet::Snippet;
  147use std::{
  148    any::TypeId,
  149    borrow::Cow,
  150    cell::RefCell,
  151    cmp::{self, Ordering, Reverse},
  152    mem,
  153    num::NonZeroU32,
  154    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  155    path::{Path, PathBuf},
  156    rc::Rc,
  157    sync::Arc,
  158    time::{Duration, Instant},
  159};
  160pub use sum_tree::Bias;
  161use sum_tree::TreeMap;
  162use text::{BufferId, OffsetUtf16, Rope};
  163use theme::{
  164    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  165    ThemeColors, ThemeSettings,
  166};
  167use ui::{
  168    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  169    PopoverMenuHandle, Tooltip,
  170};
  171use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  172use workspace::item::{ItemHandle, PreviewTabsSettings};
  173use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  174use workspace::{
  175    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  176};
  177use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  178
  179use crate::hover_links::{find_url, find_url_from_range};
  180use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  181
  182pub const FILE_HEADER_HEIGHT: u32 = 2;
  183pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  184pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  185pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  186const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  187const MAX_LINE_LEN: usize = 1024;
  188const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  189const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  190pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  191#[doc(hidden)]
  192pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  193
  194pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  195pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  196
  197pub fn render_parsed_markdown(
  198    element_id: impl Into<ElementId>,
  199    parsed: &language::ParsedMarkdown,
  200    editor_style: &EditorStyle,
  201    workspace: Option<WeakView<Workspace>>,
  202    cx: &mut WindowContext,
  203) -> InteractiveText {
  204    let code_span_background_color = cx
  205        .theme()
  206        .colors()
  207        .editor_document_highlight_read_background;
  208
  209    let highlights = gpui::combine_highlights(
  210        parsed.highlights.iter().filter_map(|(range, highlight)| {
  211            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  212            Some((range.clone(), highlight))
  213        }),
  214        parsed
  215            .regions
  216            .iter()
  217            .zip(&parsed.region_ranges)
  218            .filter_map(|(region, range)| {
  219                if region.code {
  220                    Some((
  221                        range.clone(),
  222                        HighlightStyle {
  223                            background_color: Some(code_span_background_color),
  224                            ..Default::default()
  225                        },
  226                    ))
  227                } else {
  228                    None
  229                }
  230            }),
  231    );
  232
  233    let mut links = Vec::new();
  234    let mut link_ranges = Vec::new();
  235    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  236        if let Some(link) = region.link.clone() {
  237            links.push(link);
  238            link_ranges.push(range.clone());
  239        }
  240    }
  241
  242    InteractiveText::new(
  243        element_id,
  244        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  245    )
  246    .on_click(link_ranges, move |clicked_range_ix, cx| {
  247        match &links[clicked_range_ix] {
  248            markdown::Link::Web { url } => cx.open_url(url),
  249            markdown::Link::Path { path } => {
  250                if let Some(workspace) = &workspace {
  251                    _ = workspace.update(cx, |workspace, cx| {
  252                        workspace.open_abs_path(path.clone(), false, cx).detach();
  253                    });
  254                }
  255            }
  256        }
  257    })
  258}
  259
  260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  261pub enum InlayId {
  262    InlineCompletion(usize),
  263    Hint(usize),
  264}
  265
  266impl InlayId {
  267    fn id(&self) -> usize {
  268        match self {
  269            Self::InlineCompletion(id) => *id,
  270            Self::Hint(id) => *id,
  271        }
  272    }
  273}
  274
  275enum DiffRowHighlight {}
  276enum DocumentHighlightRead {}
  277enum DocumentHighlightWrite {}
  278enum InputComposition {}
  279
  280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  281pub enum Navigated {
  282    Yes,
  283    No,
  284}
  285
  286impl Navigated {
  287    pub fn from_bool(yes: bool) -> Navigated {
  288        if yes {
  289            Navigated::Yes
  290        } else {
  291            Navigated::No
  292        }
  293    }
  294}
  295
  296pub fn init_settings(cx: &mut AppContext) {
  297    EditorSettings::register(cx);
  298}
  299
  300pub fn init(cx: &mut AppContext) {
  301    init_settings(cx);
  302
  303    workspace::register_project_item::<Editor>(cx);
  304    workspace::FollowableViewRegistry::register::<Editor>(cx);
  305    workspace::register_serializable_item::<Editor>(cx);
  306
  307    cx.observe_new_views(
  308        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  309            workspace.register_action(Editor::new_file);
  310            workspace.register_action(Editor::new_file_vertical);
  311            workspace.register_action(Editor::new_file_horizontal);
  312        },
  313    )
  314    .detach();
  315
  316    cx.on_action(move |_: &workspace::NewFile, cx| {
  317        let app_state = workspace::AppState::global(cx);
  318        if let Some(app_state) = app_state.upgrade() {
  319            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  320                Editor::new_file(workspace, &Default::default(), cx)
  321            })
  322            .detach();
  323        }
  324    });
  325    cx.on_action(move |_: &workspace::NewWindow, cx| {
  326        let app_state = workspace::AppState::global(cx);
  327        if let Some(app_state) = app_state.upgrade() {
  328            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  329                Editor::new_file(workspace, &Default::default(), cx)
  330            })
  331            .detach();
  332        }
  333    });
  334    git::project_diff::init(cx);
  335}
  336
  337pub struct SearchWithinRange;
  338
  339trait InvalidationRegion {
  340    fn ranges(&self) -> &[Range<Anchor>];
  341}
  342
  343#[derive(Clone, Debug, PartialEq)]
  344pub enum SelectPhase {
  345    Begin {
  346        position: DisplayPoint,
  347        add: bool,
  348        click_count: usize,
  349    },
  350    BeginColumnar {
  351        position: DisplayPoint,
  352        reset: bool,
  353        goal_column: u32,
  354    },
  355    Extend {
  356        position: DisplayPoint,
  357        click_count: usize,
  358    },
  359    Update {
  360        position: DisplayPoint,
  361        goal_column: u32,
  362        scroll_delta: gpui::Point<f32>,
  363    },
  364    End,
  365}
  366
  367#[derive(Clone, Debug)]
  368pub enum SelectMode {
  369    Character,
  370    Word(Range<Anchor>),
  371    Line(Range<Anchor>),
  372    All,
  373}
  374
  375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  376pub enum EditorMode {
  377    SingleLine { auto_width: bool },
  378    AutoHeight { max_lines: usize },
  379    Full,
  380}
  381
  382#[derive(Copy, Clone, Debug)]
  383pub enum SoftWrap {
  384    /// Prefer not to wrap at all.
  385    ///
  386    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  387    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  388    GitDiff,
  389    /// Prefer a single line generally, unless an overly long line is encountered.
  390    None,
  391    /// Soft wrap lines that exceed the editor width.
  392    EditorWidth,
  393    /// Soft wrap lines at the preferred line length.
  394    Column(u32),
  395    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  396    Bounded(u32),
  397}
  398
  399#[derive(Clone)]
  400pub struct EditorStyle {
  401    pub background: Hsla,
  402    pub local_player: PlayerColor,
  403    pub text: TextStyle,
  404    pub scrollbar_width: Pixels,
  405    pub syntax: Arc<SyntaxTheme>,
  406    pub status: StatusColors,
  407    pub inlay_hints_style: HighlightStyle,
  408    pub inline_completion_styles: InlineCompletionStyles,
  409    pub unnecessary_code_fade: f32,
  410}
  411
  412impl Default for EditorStyle {
  413    fn default() -> Self {
  414        Self {
  415            background: Hsla::default(),
  416            local_player: PlayerColor::default(),
  417            text: TextStyle::default(),
  418            scrollbar_width: Pixels::default(),
  419            syntax: Default::default(),
  420            // HACK: Status colors don't have a real default.
  421            // We should look into removing the status colors from the editor
  422            // style and retrieve them directly from the theme.
  423            status: StatusColors::dark(),
  424            inlay_hints_style: HighlightStyle::default(),
  425            inline_completion_styles: InlineCompletionStyles {
  426                insertion: HighlightStyle::default(),
  427                whitespace: HighlightStyle::default(),
  428            },
  429            unnecessary_code_fade: Default::default(),
  430        }
  431    }
  432}
  433
  434pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  435    let show_background = language_settings::language_settings(None, None, cx)
  436        .inlay_hints
  437        .show_background;
  438
  439    HighlightStyle {
  440        color: Some(cx.theme().status().hint),
  441        background_color: show_background.then(|| cx.theme().status().hint_background),
  442        ..HighlightStyle::default()
  443    }
  444}
  445
  446pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
  447    InlineCompletionStyles {
  448        insertion: HighlightStyle {
  449            color: Some(cx.theme().status().predictive),
  450            ..HighlightStyle::default()
  451        },
  452        whitespace: HighlightStyle {
  453            background_color: Some(cx.theme().status().created_background),
  454            ..HighlightStyle::default()
  455        },
  456    }
  457}
  458
  459type CompletionId = usize;
  460
  461#[derive(Debug, Clone)]
  462struct InlineCompletionMenuHint {
  463    provider_name: &'static str,
  464    text: InlineCompletionText,
  465}
  466
  467#[derive(Clone, Debug)]
  468enum InlineCompletionText {
  469    Move(SharedString),
  470    Edit {
  471        text: SharedString,
  472        highlights: Vec<(Range<usize>, HighlightStyle)>,
  473    },
  474}
  475
  476enum InlineCompletion {
  477    Edit(Vec<(Range<Anchor>, String)>),
  478    Move(Anchor),
  479}
  480
  481struct InlineCompletionState {
  482    inlay_ids: Vec<InlayId>,
  483    completion: InlineCompletion,
  484    invalidation_range: Range<Anchor>,
  485}
  486
  487enum InlineCompletionHighlight {}
  488
  489#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  490struct EditorActionId(usize);
  491
  492impl EditorActionId {
  493    pub fn post_inc(&mut self) -> Self {
  494        let answer = self.0;
  495
  496        *self = Self(answer + 1);
  497
  498        Self(answer)
  499    }
  500}
  501
  502// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  503// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  504
  505type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  506type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  507
  508#[derive(Default)]
  509struct ScrollbarMarkerState {
  510    scrollbar_size: Size<Pixels>,
  511    dirty: bool,
  512    markers: Arc<[PaintQuad]>,
  513    pending_refresh: Option<Task<Result<()>>>,
  514}
  515
  516impl ScrollbarMarkerState {
  517    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  518        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  519    }
  520}
  521
  522#[derive(Clone, Debug)]
  523struct RunnableTasks {
  524    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  525    offset: MultiBufferOffset,
  526    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  527    column: u32,
  528    // Values of all named captures, including those starting with '_'
  529    extra_variables: HashMap<String, String>,
  530    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  531    context_range: Range<BufferOffset>,
  532}
  533
  534impl RunnableTasks {
  535    fn resolve<'a>(
  536        &'a self,
  537        cx: &'a task::TaskContext,
  538    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  539        self.templates.iter().filter_map(|(kind, template)| {
  540            template
  541                .resolve_task(&kind.to_id_base(), cx)
  542                .map(|task| (kind.clone(), task))
  543        })
  544    }
  545}
  546
  547#[derive(Clone)]
  548struct ResolvedTasks {
  549    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  550    position: Anchor,
  551}
  552#[derive(Copy, Clone, Debug)]
  553struct MultiBufferOffset(usize);
  554#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  555struct BufferOffset(usize);
  556
  557// Addons allow storing per-editor state in other crates (e.g. Vim)
  558pub trait Addon: 'static {
  559    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  560
  561    fn to_any(&self) -> &dyn std::any::Any;
  562}
  563
  564#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  565pub enum IsVimMode {
  566    Yes,
  567    No,
  568}
  569
  570/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  571///
  572/// See the [module level documentation](self) for more information.
  573pub struct Editor {
  574    focus_handle: FocusHandle,
  575    last_focused_descendant: Option<WeakFocusHandle>,
  576    /// The text buffer being edited
  577    buffer: Model<MultiBuffer>,
  578    /// Map of how text in the buffer should be displayed.
  579    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  580    pub display_map: Model<DisplayMap>,
  581    pub selections: SelectionsCollection,
  582    pub scroll_manager: ScrollManager,
  583    /// When inline assist editors are linked, they all render cursors because
  584    /// typing enters text into each of them, even the ones that aren't focused.
  585    pub(crate) show_cursor_when_unfocused: bool,
  586    columnar_selection_tail: Option<Anchor>,
  587    add_selections_state: Option<AddSelectionsState>,
  588    select_next_state: Option<SelectNextState>,
  589    select_prev_state: Option<SelectNextState>,
  590    selection_history: SelectionHistory,
  591    autoclose_regions: Vec<AutocloseRegion>,
  592    snippet_stack: InvalidationStack<SnippetState>,
  593    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  594    ime_transaction: Option<TransactionId>,
  595    active_diagnostics: Option<ActiveDiagnosticGroup>,
  596    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  597
  598    project: Option<Model<Project>>,
  599    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  600    completion_provider: Option<Box<dyn CompletionProvider>>,
  601    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  602    blink_manager: Model<BlinkManager>,
  603    show_cursor_names: bool,
  604    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  605    pub show_local_selections: bool,
  606    mode: EditorMode,
  607    show_breadcrumbs: bool,
  608    show_gutter: bool,
  609    show_scrollbars: bool,
  610    show_line_numbers: Option<bool>,
  611    use_relative_line_numbers: Option<bool>,
  612    show_git_diff_gutter: Option<bool>,
  613    show_code_actions: Option<bool>,
  614    show_runnables: Option<bool>,
  615    show_wrap_guides: Option<bool>,
  616    show_indent_guides: Option<bool>,
  617    placeholder_text: Option<Arc<str>>,
  618    highlight_order: usize,
  619    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  620    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  621    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  622    scrollbar_marker_state: ScrollbarMarkerState,
  623    active_indent_guides_state: ActiveIndentGuidesState,
  624    nav_history: Option<ItemNavHistory>,
  625    context_menu: RefCell<Option<CodeContextMenu>>,
  626    mouse_context_menu: Option<MouseContextMenu>,
  627    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  628    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  629    signature_help_state: SignatureHelpState,
  630    auto_signature_help: Option<bool>,
  631    find_all_references_task_sources: Vec<Anchor>,
  632    next_completion_id: CompletionId,
  633    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  634    code_actions_task: Option<Task<Result<()>>>,
  635    document_highlights_task: Option<Task<()>>,
  636    linked_editing_range_task: Option<Task<Option<()>>>,
  637    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  638    pending_rename: Option<RenameState>,
  639    searchable: bool,
  640    cursor_shape: CursorShape,
  641    current_line_highlight: Option<CurrentLineHighlight>,
  642    collapse_matches: bool,
  643    autoindent_mode: Option<AutoindentMode>,
  644    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  645    input_enabled: bool,
  646    use_modal_editing: bool,
  647    read_only: bool,
  648    leader_peer_id: Option<PeerId>,
  649    remote_id: Option<ViewId>,
  650    hover_state: HoverState,
  651    gutter_hovered: bool,
  652    hovered_link_state: Option<HoveredLinkState>,
  653    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  654    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  655    active_inline_completion: Option<InlineCompletionState>,
  656    // enable_inline_completions is a switch that Vim can use to disable
  657    // inline completions based on its mode.
  658    enable_inline_completions: bool,
  659    show_inline_completions_override: Option<bool>,
  660    inlay_hint_cache: InlayHintCache,
  661    diff_map: DiffMap,
  662    next_inlay_id: usize,
  663    _subscriptions: Vec<Subscription>,
  664    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  665    gutter_dimensions: GutterDimensions,
  666    style: Option<EditorStyle>,
  667    text_style_refinement: Option<TextStyleRefinement>,
  668    next_editor_action_id: EditorActionId,
  669    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  670    use_autoclose: bool,
  671    use_auto_surround: bool,
  672    auto_replace_emoji_shortcode: bool,
  673    show_git_blame_gutter: bool,
  674    show_git_blame_inline: bool,
  675    show_git_blame_inline_delay_task: Option<Task<()>>,
  676    git_blame_inline_enabled: bool,
  677    serialize_dirty_buffers: bool,
  678    show_selection_menu: Option<bool>,
  679    blame: Option<Model<GitBlame>>,
  680    blame_subscription: Option<Subscription>,
  681    custom_context_menu: Option<
  682        Box<
  683            dyn 'static
  684                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  685        >,
  686    >,
  687    last_bounds: Option<Bounds<Pixels>>,
  688    expect_bounds_change: Option<Bounds<Pixels>>,
  689    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  690    tasks_update_task: Option<Task<()>>,
  691    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  692    breadcrumb_header: Option<String>,
  693    focused_block: Option<FocusedBlock>,
  694    next_scroll_position: NextScrollCursorCenterTopBottom,
  695    addons: HashMap<TypeId, Box<dyn Addon>>,
  696    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  697    toggle_fold_multiple_buffers: Task<()>,
  698    _scroll_cursor_center_top_bottom_task: Task<()>,
  699}
  700
  701#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  702enum NextScrollCursorCenterTopBottom {
  703    #[default]
  704    Center,
  705    Top,
  706    Bottom,
  707}
  708
  709impl NextScrollCursorCenterTopBottom {
  710    fn next(&self) -> Self {
  711        match self {
  712            Self::Center => Self::Top,
  713            Self::Top => Self::Bottom,
  714            Self::Bottom => Self::Center,
  715        }
  716    }
  717}
  718
  719#[derive(Clone)]
  720pub struct EditorSnapshot {
  721    pub mode: EditorMode,
  722    show_gutter: bool,
  723    show_line_numbers: Option<bool>,
  724    show_git_diff_gutter: Option<bool>,
  725    show_code_actions: Option<bool>,
  726    show_runnables: Option<bool>,
  727    git_blame_gutter_max_author_length: Option<usize>,
  728    pub display_snapshot: DisplaySnapshot,
  729    pub placeholder_text: Option<Arc<str>>,
  730    diff_map: DiffMapSnapshot,
  731    is_focused: bool,
  732    scroll_anchor: ScrollAnchor,
  733    ongoing_scroll: OngoingScroll,
  734    current_line_highlight: CurrentLineHighlight,
  735    gutter_hovered: bool,
  736}
  737
  738const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  739
  740#[derive(Default, Debug, Clone, Copy)]
  741pub struct GutterDimensions {
  742    pub left_padding: Pixels,
  743    pub right_padding: Pixels,
  744    pub width: Pixels,
  745    pub margin: Pixels,
  746    pub git_blame_entries_width: Option<Pixels>,
  747}
  748
  749impl GutterDimensions {
  750    /// The full width of the space taken up by the gutter.
  751    pub fn full_width(&self) -> Pixels {
  752        self.margin + self.width
  753    }
  754
  755    /// The width of the space reserved for the fold indicators,
  756    /// use alongside 'justify_end' and `gutter_width` to
  757    /// right align content with the line numbers
  758    pub fn fold_area_width(&self) -> Pixels {
  759        self.margin + self.right_padding
  760    }
  761}
  762
  763#[derive(Debug)]
  764pub struct RemoteSelection {
  765    pub replica_id: ReplicaId,
  766    pub selection: Selection<Anchor>,
  767    pub cursor_shape: CursorShape,
  768    pub peer_id: PeerId,
  769    pub line_mode: bool,
  770    pub participant_index: Option<ParticipantIndex>,
  771    pub user_name: Option<SharedString>,
  772}
  773
  774#[derive(Clone, Debug)]
  775struct SelectionHistoryEntry {
  776    selections: Arc<[Selection<Anchor>]>,
  777    select_next_state: Option<SelectNextState>,
  778    select_prev_state: Option<SelectNextState>,
  779    add_selections_state: Option<AddSelectionsState>,
  780}
  781
  782enum SelectionHistoryMode {
  783    Normal,
  784    Undoing,
  785    Redoing,
  786}
  787
  788#[derive(Clone, PartialEq, Eq, Hash)]
  789struct HoveredCursor {
  790    replica_id: u16,
  791    selection_id: usize,
  792}
  793
  794impl Default for SelectionHistoryMode {
  795    fn default() -> Self {
  796        Self::Normal
  797    }
  798}
  799
  800#[derive(Default)]
  801struct SelectionHistory {
  802    #[allow(clippy::type_complexity)]
  803    selections_by_transaction:
  804        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  805    mode: SelectionHistoryMode,
  806    undo_stack: VecDeque<SelectionHistoryEntry>,
  807    redo_stack: VecDeque<SelectionHistoryEntry>,
  808}
  809
  810impl SelectionHistory {
  811    fn insert_transaction(
  812        &mut self,
  813        transaction_id: TransactionId,
  814        selections: Arc<[Selection<Anchor>]>,
  815    ) {
  816        self.selections_by_transaction
  817            .insert(transaction_id, (selections, None));
  818    }
  819
  820    #[allow(clippy::type_complexity)]
  821    fn transaction(
  822        &self,
  823        transaction_id: TransactionId,
  824    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  825        self.selections_by_transaction.get(&transaction_id)
  826    }
  827
  828    #[allow(clippy::type_complexity)]
  829    fn transaction_mut(
  830        &mut self,
  831        transaction_id: TransactionId,
  832    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  833        self.selections_by_transaction.get_mut(&transaction_id)
  834    }
  835
  836    fn push(&mut self, entry: SelectionHistoryEntry) {
  837        if !entry.selections.is_empty() {
  838            match self.mode {
  839                SelectionHistoryMode::Normal => {
  840                    self.push_undo(entry);
  841                    self.redo_stack.clear();
  842                }
  843                SelectionHistoryMode::Undoing => self.push_redo(entry),
  844                SelectionHistoryMode::Redoing => self.push_undo(entry),
  845            }
  846        }
  847    }
  848
  849    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  850        if self
  851            .undo_stack
  852            .back()
  853            .map_or(true, |e| e.selections != entry.selections)
  854        {
  855            self.undo_stack.push_back(entry);
  856            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  857                self.undo_stack.pop_front();
  858            }
  859        }
  860    }
  861
  862    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  863        if self
  864            .redo_stack
  865            .back()
  866            .map_or(true, |e| e.selections != entry.selections)
  867        {
  868            self.redo_stack.push_back(entry);
  869            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  870                self.redo_stack.pop_front();
  871            }
  872        }
  873    }
  874}
  875
  876struct RowHighlight {
  877    index: usize,
  878    range: Range<Anchor>,
  879    color: Hsla,
  880    should_autoscroll: bool,
  881}
  882
  883#[derive(Clone, Debug)]
  884struct AddSelectionsState {
  885    above: bool,
  886    stack: Vec<usize>,
  887}
  888
  889#[derive(Clone)]
  890struct SelectNextState {
  891    query: AhoCorasick,
  892    wordwise: bool,
  893    done: bool,
  894}
  895
  896impl std::fmt::Debug for SelectNextState {
  897    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  898        f.debug_struct(std::any::type_name::<Self>())
  899            .field("wordwise", &self.wordwise)
  900            .field("done", &self.done)
  901            .finish()
  902    }
  903}
  904
  905#[derive(Debug)]
  906struct AutocloseRegion {
  907    selection_id: usize,
  908    range: Range<Anchor>,
  909    pair: BracketPair,
  910}
  911
  912#[derive(Debug)]
  913struct SnippetState {
  914    ranges: Vec<Vec<Range<Anchor>>>,
  915    active_index: usize,
  916    choices: Vec<Option<Vec<String>>>,
  917}
  918
  919#[doc(hidden)]
  920pub struct RenameState {
  921    pub range: Range<Anchor>,
  922    pub old_name: Arc<str>,
  923    pub editor: View<Editor>,
  924    block_id: CustomBlockId,
  925}
  926
  927struct InvalidationStack<T>(Vec<T>);
  928
  929struct RegisteredInlineCompletionProvider {
  930    provider: Arc<dyn InlineCompletionProviderHandle>,
  931    _subscription: Subscription,
  932}
  933
  934#[derive(Debug)]
  935struct ActiveDiagnosticGroup {
  936    primary_range: Range<Anchor>,
  937    primary_message: String,
  938    group_id: usize,
  939    blocks: HashMap<CustomBlockId, Diagnostic>,
  940    is_valid: bool,
  941}
  942
  943#[derive(Serialize, Deserialize, Clone, Debug)]
  944pub struct ClipboardSelection {
  945    pub len: usize,
  946    pub is_entire_line: bool,
  947    pub first_line_indent: u32,
  948}
  949
  950#[derive(Debug)]
  951pub(crate) struct NavigationData {
  952    cursor_anchor: Anchor,
  953    cursor_position: Point,
  954    scroll_anchor: ScrollAnchor,
  955    scroll_top_row: u32,
  956}
  957
  958#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  959pub enum GotoDefinitionKind {
  960    Symbol,
  961    Declaration,
  962    Type,
  963    Implementation,
  964}
  965
  966#[derive(Debug, Clone)]
  967enum InlayHintRefreshReason {
  968    Toggle(bool),
  969    SettingsChange(InlayHintSettings),
  970    NewLinesShown,
  971    BufferEdited(HashSet<Arc<Language>>),
  972    RefreshRequested,
  973    ExcerptsRemoved(Vec<ExcerptId>),
  974}
  975
  976impl InlayHintRefreshReason {
  977    fn description(&self) -> &'static str {
  978        match self {
  979            Self::Toggle(_) => "toggle",
  980            Self::SettingsChange(_) => "settings change",
  981            Self::NewLinesShown => "new lines shown",
  982            Self::BufferEdited(_) => "buffer edited",
  983            Self::RefreshRequested => "refresh requested",
  984            Self::ExcerptsRemoved(_) => "excerpts removed",
  985        }
  986    }
  987}
  988
  989pub(crate) struct FocusedBlock {
  990    id: BlockId,
  991    focus_handle: WeakFocusHandle,
  992}
  993
  994#[derive(Clone)]
  995enum JumpData {
  996    MultiBufferRow {
  997        row: MultiBufferRow,
  998        line_offset_from_top: u32,
  999    },
 1000    MultiBufferPoint {
 1001        excerpt_id: ExcerptId,
 1002        position: Point,
 1003        anchor: text::Anchor,
 1004        line_offset_from_top: u32,
 1005    },
 1006}
 1007
 1008impl Editor {
 1009    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1010        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1011        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1012        Self::new(
 1013            EditorMode::SingleLine { auto_width: false },
 1014            buffer,
 1015            None,
 1016            false,
 1017            cx,
 1018        )
 1019    }
 1020
 1021    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1022        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1023        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1024        Self::new(EditorMode::Full, buffer, None, false, cx)
 1025    }
 1026
 1027    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1028        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1029        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1030        Self::new(
 1031            EditorMode::SingleLine { auto_width: true },
 1032            buffer,
 1033            None,
 1034            false,
 1035            cx,
 1036        )
 1037    }
 1038
 1039    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1040        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1041        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1042        Self::new(
 1043            EditorMode::AutoHeight { max_lines },
 1044            buffer,
 1045            None,
 1046            false,
 1047            cx,
 1048        )
 1049    }
 1050
 1051    pub fn for_buffer(
 1052        buffer: Model<Buffer>,
 1053        project: Option<Model<Project>>,
 1054        cx: &mut ViewContext<Self>,
 1055    ) -> Self {
 1056        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1057        Self::new(EditorMode::Full, buffer, project, false, cx)
 1058    }
 1059
 1060    pub fn for_multibuffer(
 1061        buffer: Model<MultiBuffer>,
 1062        project: Option<Model<Project>>,
 1063        show_excerpt_controls: bool,
 1064        cx: &mut ViewContext<Self>,
 1065    ) -> Self {
 1066        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1067    }
 1068
 1069    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1070        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1071        let mut clone = Self::new(
 1072            self.mode,
 1073            self.buffer.clone(),
 1074            self.project.clone(),
 1075            show_excerpt_controls,
 1076            cx,
 1077        );
 1078        self.display_map.update(cx, |display_map, cx| {
 1079            let snapshot = display_map.snapshot(cx);
 1080            clone.display_map.update(cx, |display_map, cx| {
 1081                display_map.set_state(&snapshot, cx);
 1082            });
 1083        });
 1084        clone.selections.clone_state(&self.selections);
 1085        clone.scroll_manager.clone_state(&self.scroll_manager);
 1086        clone.searchable = self.searchable;
 1087        clone
 1088    }
 1089
 1090    pub fn new(
 1091        mode: EditorMode,
 1092        buffer: Model<MultiBuffer>,
 1093        project: Option<Model<Project>>,
 1094        show_excerpt_controls: bool,
 1095        cx: &mut ViewContext<Self>,
 1096    ) -> Self {
 1097        let style = cx.text_style();
 1098        let font_size = style.font_size.to_pixels(cx.rem_size());
 1099        let editor = cx.view().downgrade();
 1100        let fold_placeholder = FoldPlaceholder {
 1101            constrain_width: true,
 1102            render: Arc::new(move |fold_id, fold_range, cx| {
 1103                let editor = editor.clone();
 1104                div()
 1105                    .id(fold_id)
 1106                    .bg(cx.theme().colors().ghost_element_background)
 1107                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1108                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1109                    .rounded_sm()
 1110                    .size_full()
 1111                    .cursor_pointer()
 1112                    .child("")
 1113                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1114                    .on_click(move |_, cx| {
 1115                        editor
 1116                            .update(cx, |editor, cx| {
 1117                                editor.unfold_ranges(
 1118                                    &[fold_range.start..fold_range.end],
 1119                                    true,
 1120                                    false,
 1121                                    cx,
 1122                                );
 1123                                cx.stop_propagation();
 1124                            })
 1125                            .ok();
 1126                    })
 1127                    .into_any()
 1128            }),
 1129            merge_adjacent: true,
 1130            ..Default::default()
 1131        };
 1132        let display_map = cx.new_model(|cx| {
 1133            DisplayMap::new(
 1134                buffer.clone(),
 1135                style.font(),
 1136                font_size,
 1137                None,
 1138                show_excerpt_controls,
 1139                FILE_HEADER_HEIGHT,
 1140                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1141                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1142                fold_placeholder,
 1143                cx,
 1144            )
 1145        });
 1146
 1147        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1148
 1149        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1150
 1151        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1152            .then(|| language_settings::SoftWrap::None);
 1153
 1154        let mut project_subscriptions = Vec::new();
 1155        if mode == EditorMode::Full {
 1156            if let Some(project) = project.as_ref() {
 1157                if buffer.read(cx).is_singleton() {
 1158                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1159                        cx.emit(EditorEvent::TitleChanged);
 1160                    }));
 1161                }
 1162                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1163                    if let project::Event::RefreshInlayHints = event {
 1164                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1165                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1166                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1167                            let focus_handle = editor.focus_handle(cx);
 1168                            if focus_handle.is_focused(cx) {
 1169                                let snapshot = buffer.read(cx).snapshot();
 1170                                for (range, snippet) in snippet_edits {
 1171                                    let editor_range =
 1172                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1173                                    editor
 1174                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1175                                        .ok();
 1176                                }
 1177                            }
 1178                        }
 1179                    }
 1180                }));
 1181                if let Some(task_inventory) = project
 1182                    .read(cx)
 1183                    .task_store()
 1184                    .read(cx)
 1185                    .task_inventory()
 1186                    .cloned()
 1187                {
 1188                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1189                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1190                    }));
 1191                }
 1192            }
 1193        }
 1194
 1195        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1196
 1197        let inlay_hint_settings =
 1198            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1199        let focus_handle = cx.focus_handle();
 1200        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1201        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1202            .detach();
 1203        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1204            .detach();
 1205        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1206
 1207        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1208            Some(false)
 1209        } else {
 1210            None
 1211        };
 1212
 1213        let mut code_action_providers = Vec::new();
 1214        if let Some(project) = project.clone() {
 1215            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1216            code_action_providers.push(Rc::new(project) as Rc<_>);
 1217        }
 1218
 1219        let mut this = Self {
 1220            focus_handle,
 1221            show_cursor_when_unfocused: false,
 1222            last_focused_descendant: None,
 1223            buffer: buffer.clone(),
 1224            display_map: display_map.clone(),
 1225            selections,
 1226            scroll_manager: ScrollManager::new(cx),
 1227            columnar_selection_tail: None,
 1228            add_selections_state: None,
 1229            select_next_state: None,
 1230            select_prev_state: None,
 1231            selection_history: Default::default(),
 1232            autoclose_regions: Default::default(),
 1233            snippet_stack: Default::default(),
 1234            select_larger_syntax_node_stack: Vec::new(),
 1235            ime_transaction: Default::default(),
 1236            active_diagnostics: None,
 1237            soft_wrap_mode_override,
 1238            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1239            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1240            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1241            project,
 1242            blink_manager: blink_manager.clone(),
 1243            show_local_selections: true,
 1244            show_scrollbars: true,
 1245            mode,
 1246            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1247            show_gutter: mode == EditorMode::Full,
 1248            show_line_numbers: None,
 1249            use_relative_line_numbers: None,
 1250            show_git_diff_gutter: None,
 1251            show_code_actions: None,
 1252            show_runnables: None,
 1253            show_wrap_guides: None,
 1254            show_indent_guides,
 1255            placeholder_text: None,
 1256            highlight_order: 0,
 1257            highlighted_rows: HashMap::default(),
 1258            background_highlights: Default::default(),
 1259            gutter_highlights: TreeMap::default(),
 1260            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1261            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1262            nav_history: None,
 1263            context_menu: RefCell::new(None),
 1264            mouse_context_menu: None,
 1265            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1266            completion_tasks: Default::default(),
 1267            signature_help_state: SignatureHelpState::default(),
 1268            auto_signature_help: None,
 1269            find_all_references_task_sources: Vec::new(),
 1270            next_completion_id: 0,
 1271            next_inlay_id: 0,
 1272            code_action_providers,
 1273            available_code_actions: Default::default(),
 1274            code_actions_task: Default::default(),
 1275            document_highlights_task: Default::default(),
 1276            linked_editing_range_task: Default::default(),
 1277            pending_rename: Default::default(),
 1278            searchable: true,
 1279            cursor_shape: EditorSettings::get_global(cx)
 1280                .cursor_shape
 1281                .unwrap_or_default(),
 1282            current_line_highlight: None,
 1283            autoindent_mode: Some(AutoindentMode::EachLine),
 1284            collapse_matches: false,
 1285            workspace: None,
 1286            input_enabled: true,
 1287            use_modal_editing: mode == EditorMode::Full,
 1288            read_only: false,
 1289            use_autoclose: true,
 1290            use_auto_surround: true,
 1291            auto_replace_emoji_shortcode: false,
 1292            leader_peer_id: None,
 1293            remote_id: None,
 1294            hover_state: Default::default(),
 1295            hovered_link_state: Default::default(),
 1296            inline_completion_provider: None,
 1297            active_inline_completion: None,
 1298            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1299            diff_map: DiffMap::default(),
 1300            gutter_hovered: false,
 1301            pixel_position_of_newest_cursor: None,
 1302            last_bounds: None,
 1303            expect_bounds_change: None,
 1304            gutter_dimensions: GutterDimensions::default(),
 1305            style: None,
 1306            show_cursor_names: false,
 1307            hovered_cursors: Default::default(),
 1308            next_editor_action_id: EditorActionId::default(),
 1309            editor_actions: Rc::default(),
 1310            show_inline_completions_override: None,
 1311            enable_inline_completions: true,
 1312            custom_context_menu: None,
 1313            show_git_blame_gutter: false,
 1314            show_git_blame_inline: false,
 1315            show_selection_menu: None,
 1316            show_git_blame_inline_delay_task: None,
 1317            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1318            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1319                .session
 1320                .restore_unsaved_buffers,
 1321            blame: None,
 1322            blame_subscription: None,
 1323            tasks: Default::default(),
 1324            _subscriptions: vec![
 1325                cx.observe(&buffer, Self::on_buffer_changed),
 1326                cx.subscribe(&buffer, Self::on_buffer_event),
 1327                cx.observe(&display_map, Self::on_display_map_changed),
 1328                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1329                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1330                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1331                cx.observe_window_activation(|editor, cx| {
 1332                    let active = cx.is_window_active();
 1333                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1334                        if active {
 1335                            blink_manager.enable(cx);
 1336                        } else {
 1337                            blink_manager.disable(cx);
 1338                        }
 1339                    });
 1340                }),
 1341            ],
 1342            tasks_update_task: None,
 1343            linked_edit_ranges: Default::default(),
 1344            previous_search_ranges: None,
 1345            breadcrumb_header: None,
 1346            focused_block: None,
 1347            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1348            addons: HashMap::default(),
 1349            registered_buffers: HashMap::default(),
 1350            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1351            toggle_fold_multiple_buffers: Task::ready(()),
 1352            text_style_refinement: None,
 1353        };
 1354        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1355        this._subscriptions.extend(project_subscriptions);
 1356
 1357        this.end_selection(cx);
 1358        this.scroll_manager.show_scrollbar(cx);
 1359
 1360        if mode == EditorMode::Full {
 1361            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1362            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1363
 1364            if this.git_blame_inline_enabled {
 1365                this.git_blame_inline_enabled = true;
 1366                this.start_git_blame_inline(false, cx);
 1367            }
 1368
 1369            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1370                if let Some(project) = this.project.as_ref() {
 1371                    let lsp_store = project.read(cx).lsp_store();
 1372                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1373                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1374                    });
 1375                    this.registered_buffers
 1376                        .insert(buffer.read(cx).remote_id(), handle);
 1377                }
 1378            }
 1379        }
 1380
 1381        this.report_editor_event("Editor Opened", None, cx);
 1382        this
 1383    }
 1384
 1385    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1386        self.mouse_context_menu
 1387            .as_ref()
 1388            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1389    }
 1390
 1391    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1392        let mut key_context = KeyContext::new_with_defaults();
 1393        key_context.add("Editor");
 1394        let mode = match self.mode {
 1395            EditorMode::SingleLine { .. } => "single_line",
 1396            EditorMode::AutoHeight { .. } => "auto_height",
 1397            EditorMode::Full => "full",
 1398        };
 1399
 1400        if EditorSettings::jupyter_enabled(cx) {
 1401            key_context.add("jupyter");
 1402        }
 1403
 1404        key_context.set("mode", mode);
 1405        if self.pending_rename.is_some() {
 1406            key_context.add("renaming");
 1407        }
 1408        match self.context_menu.borrow().as_ref() {
 1409            Some(CodeContextMenu::Completions(_)) => {
 1410                key_context.add("menu");
 1411                key_context.add("showing_completions")
 1412            }
 1413            Some(CodeContextMenu::CodeActions(_)) => {
 1414                key_context.add("menu");
 1415                key_context.add("showing_code_actions")
 1416            }
 1417            None => {}
 1418        }
 1419
 1420        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1421        if !self.focus_handle(cx).contains_focused(cx)
 1422            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1423        {
 1424            for addon in self.addons.values() {
 1425                addon.extend_key_context(&mut key_context, cx)
 1426            }
 1427        }
 1428
 1429        if let Some(extension) = self
 1430            .buffer
 1431            .read(cx)
 1432            .as_singleton()
 1433            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1434        {
 1435            key_context.set("extension", extension.to_string());
 1436        }
 1437
 1438        if self.has_active_inline_completion() {
 1439            key_context.add("copilot_suggestion");
 1440            key_context.add("inline_completion");
 1441        }
 1442
 1443        if !self
 1444            .selections
 1445            .disjoint
 1446            .iter()
 1447            .all(|selection| selection.start == selection.end)
 1448        {
 1449            key_context.add("selection");
 1450        }
 1451
 1452        key_context
 1453    }
 1454
 1455    pub fn new_file(
 1456        workspace: &mut Workspace,
 1457        _: &workspace::NewFile,
 1458        cx: &mut ViewContext<Workspace>,
 1459    ) {
 1460        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1461            "Failed to create buffer",
 1462            cx,
 1463            |e, _| match e.error_code() {
 1464                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1465                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1466                e.error_tag("required").unwrap_or("the latest version")
 1467            )),
 1468                _ => None,
 1469            },
 1470        );
 1471    }
 1472
 1473    pub fn new_in_workspace(
 1474        workspace: &mut Workspace,
 1475        cx: &mut ViewContext<Workspace>,
 1476    ) -> Task<Result<View<Editor>>> {
 1477        let project = workspace.project().clone();
 1478        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1479
 1480        cx.spawn(|workspace, mut cx| async move {
 1481            let buffer = create.await?;
 1482            workspace.update(&mut cx, |workspace, cx| {
 1483                let editor =
 1484                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1485                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1486                editor
 1487            })
 1488        })
 1489    }
 1490
 1491    fn new_file_vertical(
 1492        workspace: &mut Workspace,
 1493        _: &workspace::NewFileSplitVertical,
 1494        cx: &mut ViewContext<Workspace>,
 1495    ) {
 1496        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1497    }
 1498
 1499    fn new_file_horizontal(
 1500        workspace: &mut Workspace,
 1501        _: &workspace::NewFileSplitHorizontal,
 1502        cx: &mut ViewContext<Workspace>,
 1503    ) {
 1504        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1505    }
 1506
 1507    fn new_file_in_direction(
 1508        workspace: &mut Workspace,
 1509        direction: SplitDirection,
 1510        cx: &mut ViewContext<Workspace>,
 1511    ) {
 1512        let project = workspace.project().clone();
 1513        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1514
 1515        cx.spawn(|workspace, mut cx| async move {
 1516            let buffer = create.await?;
 1517            workspace.update(&mut cx, move |workspace, cx| {
 1518                workspace.split_item(
 1519                    direction,
 1520                    Box::new(
 1521                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1522                    ),
 1523                    cx,
 1524                )
 1525            })?;
 1526            anyhow::Ok(())
 1527        })
 1528        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1529            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1530                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1531                e.error_tag("required").unwrap_or("the latest version")
 1532            )),
 1533            _ => None,
 1534        });
 1535    }
 1536
 1537    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1538        self.leader_peer_id
 1539    }
 1540
 1541    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1542        &self.buffer
 1543    }
 1544
 1545    pub fn workspace(&self) -> Option<View<Workspace>> {
 1546        self.workspace.as_ref()?.0.upgrade()
 1547    }
 1548
 1549    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1550        self.buffer().read(cx).title(cx)
 1551    }
 1552
 1553    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1554        let git_blame_gutter_max_author_length = self
 1555            .render_git_blame_gutter(cx)
 1556            .then(|| {
 1557                if let Some(blame) = self.blame.as_ref() {
 1558                    let max_author_length =
 1559                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1560                    Some(max_author_length)
 1561                } else {
 1562                    None
 1563                }
 1564            })
 1565            .flatten();
 1566
 1567        EditorSnapshot {
 1568            mode: self.mode,
 1569            show_gutter: self.show_gutter,
 1570            show_line_numbers: self.show_line_numbers,
 1571            show_git_diff_gutter: self.show_git_diff_gutter,
 1572            show_code_actions: self.show_code_actions,
 1573            show_runnables: self.show_runnables,
 1574            git_blame_gutter_max_author_length,
 1575            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1576            scroll_anchor: self.scroll_manager.anchor(),
 1577            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1578            placeholder_text: self.placeholder_text.clone(),
 1579            diff_map: self.diff_map.snapshot(),
 1580            is_focused: self.focus_handle.is_focused(cx),
 1581            current_line_highlight: self
 1582                .current_line_highlight
 1583                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1584            gutter_hovered: self.gutter_hovered,
 1585        }
 1586    }
 1587
 1588    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1589        self.buffer.read(cx).language_at(point, cx)
 1590    }
 1591
 1592    pub fn file_at<T: ToOffset>(
 1593        &self,
 1594        point: T,
 1595        cx: &AppContext,
 1596    ) -> Option<Arc<dyn language::File>> {
 1597        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1598    }
 1599
 1600    pub fn active_excerpt(
 1601        &self,
 1602        cx: &AppContext,
 1603    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1604        self.buffer
 1605            .read(cx)
 1606            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1607    }
 1608
 1609    pub fn mode(&self) -> EditorMode {
 1610        self.mode
 1611    }
 1612
 1613    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1614        self.collaboration_hub.as_deref()
 1615    }
 1616
 1617    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1618        self.collaboration_hub = Some(hub);
 1619    }
 1620
 1621    pub fn set_custom_context_menu(
 1622        &mut self,
 1623        f: impl 'static
 1624            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1625    ) {
 1626        self.custom_context_menu = Some(Box::new(f))
 1627    }
 1628
 1629    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1630        self.completion_provider = provider;
 1631    }
 1632
 1633    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1634        self.semantics_provider.clone()
 1635    }
 1636
 1637    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1638        self.semantics_provider = provider;
 1639    }
 1640
 1641    pub fn set_inline_completion_provider<T>(
 1642        &mut self,
 1643        provider: Option<Model<T>>,
 1644        cx: &mut ViewContext<Self>,
 1645    ) where
 1646        T: InlineCompletionProvider,
 1647    {
 1648        self.inline_completion_provider =
 1649            provider.map(|provider| RegisteredInlineCompletionProvider {
 1650                _subscription: cx.observe(&provider, |this, _, cx| {
 1651                    if this.focus_handle.is_focused(cx) {
 1652                        this.update_visible_inline_completion(cx);
 1653                    }
 1654                }),
 1655                provider: Arc::new(provider),
 1656            });
 1657        self.refresh_inline_completion(false, false, cx);
 1658    }
 1659
 1660    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1661        self.placeholder_text.as_deref()
 1662    }
 1663
 1664    pub fn set_placeholder_text(
 1665        &mut self,
 1666        placeholder_text: impl Into<Arc<str>>,
 1667        cx: &mut ViewContext<Self>,
 1668    ) {
 1669        let placeholder_text = Some(placeholder_text.into());
 1670        if self.placeholder_text != placeholder_text {
 1671            self.placeholder_text = placeholder_text;
 1672            cx.notify();
 1673        }
 1674    }
 1675
 1676    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1677        self.cursor_shape = cursor_shape;
 1678
 1679        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1680        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1681
 1682        cx.notify();
 1683    }
 1684
 1685    pub fn set_current_line_highlight(
 1686        &mut self,
 1687        current_line_highlight: Option<CurrentLineHighlight>,
 1688    ) {
 1689        self.current_line_highlight = current_line_highlight;
 1690    }
 1691
 1692    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1693        self.collapse_matches = collapse_matches;
 1694    }
 1695
 1696    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1697        let buffers = self.buffer.read(cx).all_buffers();
 1698        let Some(lsp_store) = self.lsp_store(cx) else {
 1699            return;
 1700        };
 1701        lsp_store.update(cx, |lsp_store, cx| {
 1702            for buffer in buffers {
 1703                self.registered_buffers
 1704                    .entry(buffer.read(cx).remote_id())
 1705                    .or_insert_with(|| {
 1706                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1707                    });
 1708            }
 1709        })
 1710    }
 1711
 1712    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1713        if self.collapse_matches {
 1714            return range.start..range.start;
 1715        }
 1716        range.clone()
 1717    }
 1718
 1719    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1720        if self.display_map.read(cx).clip_at_line_ends != clip {
 1721            self.display_map
 1722                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1723        }
 1724    }
 1725
 1726    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1727        self.input_enabled = input_enabled;
 1728    }
 1729
 1730    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 1731        self.enable_inline_completions = enabled;
 1732    }
 1733
 1734    pub fn set_autoindent(&mut self, autoindent: bool) {
 1735        if autoindent {
 1736            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1737        } else {
 1738            self.autoindent_mode = None;
 1739        }
 1740    }
 1741
 1742    pub fn read_only(&self, cx: &AppContext) -> bool {
 1743        self.read_only || self.buffer.read(cx).read_only()
 1744    }
 1745
 1746    pub fn set_read_only(&mut self, read_only: bool) {
 1747        self.read_only = read_only;
 1748    }
 1749
 1750    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1751        self.use_autoclose = autoclose;
 1752    }
 1753
 1754    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1755        self.use_auto_surround = auto_surround;
 1756    }
 1757
 1758    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1759        self.auto_replace_emoji_shortcode = auto_replace;
 1760    }
 1761
 1762    pub fn toggle_inline_completions(
 1763        &mut self,
 1764        _: &ToggleInlineCompletions,
 1765        cx: &mut ViewContext<Self>,
 1766    ) {
 1767        if self.show_inline_completions_override.is_some() {
 1768            self.set_show_inline_completions(None, cx);
 1769        } else {
 1770            let cursor = self.selections.newest_anchor().head();
 1771            if let Some((buffer, cursor_buffer_position)) =
 1772                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1773            {
 1774                let show_inline_completions =
 1775                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1776                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1777            }
 1778        }
 1779    }
 1780
 1781    pub fn set_show_inline_completions(
 1782        &mut self,
 1783        show_inline_completions: Option<bool>,
 1784        cx: &mut ViewContext<Self>,
 1785    ) {
 1786        self.show_inline_completions_override = show_inline_completions;
 1787        self.refresh_inline_completion(false, true, cx);
 1788    }
 1789
 1790    pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
 1791        let cursor = self.selections.newest_anchor().head();
 1792        if let Some((buffer, buffer_position)) =
 1793            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1794        {
 1795            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1796        } else {
 1797            false
 1798        }
 1799    }
 1800
 1801    fn should_show_inline_completions(
 1802        &self,
 1803        buffer: &Model<Buffer>,
 1804        buffer_position: language::Anchor,
 1805        cx: &AppContext,
 1806    ) -> bool {
 1807        if !self.snippet_stack.is_empty() {
 1808            return false;
 1809        }
 1810
 1811        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1812            return false;
 1813        }
 1814
 1815        if let Some(provider) = self.inline_completion_provider() {
 1816            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1817                show_inline_completions
 1818            } else {
 1819                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1820            }
 1821        } else {
 1822            false
 1823        }
 1824    }
 1825
 1826    fn inline_completions_disabled_in_scope(
 1827        &self,
 1828        buffer: &Model<Buffer>,
 1829        buffer_position: language::Anchor,
 1830        cx: &AppContext,
 1831    ) -> bool {
 1832        let snapshot = buffer.read(cx).snapshot();
 1833        let settings = snapshot.settings_at(buffer_position, cx);
 1834
 1835        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1836            return false;
 1837        };
 1838
 1839        scope.override_name().map_or(false, |scope_name| {
 1840            settings
 1841                .inline_completions_disabled_in
 1842                .iter()
 1843                .any(|s| s == scope_name)
 1844        })
 1845    }
 1846
 1847    pub fn set_use_modal_editing(&mut self, to: bool) {
 1848        self.use_modal_editing = to;
 1849    }
 1850
 1851    pub fn use_modal_editing(&self) -> bool {
 1852        self.use_modal_editing
 1853    }
 1854
 1855    fn selections_did_change(
 1856        &mut self,
 1857        local: bool,
 1858        old_cursor_position: &Anchor,
 1859        show_completions: bool,
 1860        cx: &mut ViewContext<Self>,
 1861    ) {
 1862        cx.invalidate_character_coordinates();
 1863
 1864        // Copy selections to primary selection buffer
 1865        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1866        if local {
 1867            let selections = self.selections.all::<usize>(cx);
 1868            let buffer_handle = self.buffer.read(cx).read(cx);
 1869
 1870            let mut text = String::new();
 1871            for (index, selection) in selections.iter().enumerate() {
 1872                let text_for_selection = buffer_handle
 1873                    .text_for_range(selection.start..selection.end)
 1874                    .collect::<String>();
 1875
 1876                text.push_str(&text_for_selection);
 1877                if index != selections.len() - 1 {
 1878                    text.push('\n');
 1879                }
 1880            }
 1881
 1882            if !text.is_empty() {
 1883                cx.write_to_primary(ClipboardItem::new_string(text));
 1884            }
 1885        }
 1886
 1887        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1888            self.buffer.update(cx, |buffer, cx| {
 1889                buffer.set_active_selections(
 1890                    &self.selections.disjoint_anchors(),
 1891                    self.selections.line_mode,
 1892                    self.cursor_shape,
 1893                    cx,
 1894                )
 1895            });
 1896        }
 1897        let display_map = self
 1898            .display_map
 1899            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1900        let buffer = &display_map.buffer_snapshot;
 1901        self.add_selections_state = None;
 1902        self.select_next_state = None;
 1903        self.select_prev_state = None;
 1904        self.select_larger_syntax_node_stack.clear();
 1905        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1906        self.snippet_stack
 1907            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1908        self.take_rename(false, cx);
 1909
 1910        let new_cursor_position = self.selections.newest_anchor().head();
 1911
 1912        self.push_to_nav_history(
 1913            *old_cursor_position,
 1914            Some(new_cursor_position.to_point(buffer)),
 1915            cx,
 1916        );
 1917
 1918        if local {
 1919            let new_cursor_position = self.selections.newest_anchor().head();
 1920            let mut context_menu = self.context_menu.borrow_mut();
 1921            let completion_menu = match context_menu.as_ref() {
 1922                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1923                _ => {
 1924                    *context_menu = None;
 1925                    None
 1926                }
 1927            };
 1928
 1929            if let Some(completion_menu) = completion_menu {
 1930                let cursor_position = new_cursor_position.to_offset(buffer);
 1931                let (word_range, kind) =
 1932                    buffer.surrounding_word(completion_menu.initial_position, true);
 1933                if kind == Some(CharKind::Word)
 1934                    && word_range.to_inclusive().contains(&cursor_position)
 1935                {
 1936                    let mut completion_menu = completion_menu.clone();
 1937                    drop(context_menu);
 1938
 1939                    let query = Self::completion_query(buffer, cursor_position);
 1940                    cx.spawn(move |this, mut cx| async move {
 1941                        completion_menu
 1942                            .filter(query.as_deref(), cx.background_executor().clone())
 1943                            .await;
 1944
 1945                        this.update(&mut cx, |this, cx| {
 1946                            let mut context_menu = this.context_menu.borrow_mut();
 1947                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1948                            else {
 1949                                return;
 1950                            };
 1951
 1952                            if menu.id > completion_menu.id {
 1953                                return;
 1954                            }
 1955
 1956                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1957                            drop(context_menu);
 1958                            cx.notify();
 1959                        })
 1960                    })
 1961                    .detach();
 1962
 1963                    if show_completions {
 1964                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1965                    }
 1966                } else {
 1967                    drop(context_menu);
 1968                    self.hide_context_menu(cx);
 1969                }
 1970            } else {
 1971                drop(context_menu);
 1972            }
 1973
 1974            hide_hover(self, cx);
 1975
 1976            if old_cursor_position.to_display_point(&display_map).row()
 1977                != new_cursor_position.to_display_point(&display_map).row()
 1978            {
 1979                self.available_code_actions.take();
 1980            }
 1981            self.refresh_code_actions(cx);
 1982            self.refresh_document_highlights(cx);
 1983            refresh_matching_bracket_highlights(self, cx);
 1984            self.update_visible_inline_completion(cx);
 1985            linked_editing_ranges::refresh_linked_ranges(self, cx);
 1986            if self.git_blame_inline_enabled {
 1987                self.start_inline_blame_timer(cx);
 1988            }
 1989        }
 1990
 1991        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 1992        cx.emit(EditorEvent::SelectionsChanged { local });
 1993
 1994        if self.selections.disjoint_anchors().len() == 1 {
 1995            cx.emit(SearchEvent::ActiveMatchChanged)
 1996        }
 1997        cx.notify();
 1998    }
 1999
 2000    pub fn change_selections<R>(
 2001        &mut self,
 2002        autoscroll: Option<Autoscroll>,
 2003        cx: &mut ViewContext<Self>,
 2004        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2005    ) -> R {
 2006        self.change_selections_inner(autoscroll, true, cx, change)
 2007    }
 2008
 2009    pub fn change_selections_inner<R>(
 2010        &mut self,
 2011        autoscroll: Option<Autoscroll>,
 2012        request_completions: bool,
 2013        cx: &mut ViewContext<Self>,
 2014        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2015    ) -> R {
 2016        let old_cursor_position = self.selections.newest_anchor().head();
 2017        self.push_to_selection_history();
 2018
 2019        let (changed, result) = self.selections.change_with(cx, change);
 2020
 2021        if changed {
 2022            if let Some(autoscroll) = autoscroll {
 2023                self.request_autoscroll(autoscroll, cx);
 2024            }
 2025            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2026
 2027            if self.should_open_signature_help_automatically(
 2028                &old_cursor_position,
 2029                self.signature_help_state.backspace_pressed(),
 2030                cx,
 2031            ) {
 2032                self.show_signature_help(&ShowSignatureHelp, cx);
 2033            }
 2034            self.signature_help_state.set_backspace_pressed(false);
 2035        }
 2036
 2037        result
 2038    }
 2039
 2040    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2041    where
 2042        I: IntoIterator<Item = (Range<S>, T)>,
 2043        S: ToOffset,
 2044        T: Into<Arc<str>>,
 2045    {
 2046        if self.read_only(cx) {
 2047            return;
 2048        }
 2049
 2050        self.buffer
 2051            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2052    }
 2053
 2054    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2055    where
 2056        I: IntoIterator<Item = (Range<S>, T)>,
 2057        S: ToOffset,
 2058        T: Into<Arc<str>>,
 2059    {
 2060        if self.read_only(cx) {
 2061            return;
 2062        }
 2063
 2064        self.buffer.update(cx, |buffer, cx| {
 2065            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2066        });
 2067    }
 2068
 2069    pub fn edit_with_block_indent<I, S, T>(
 2070        &mut self,
 2071        edits: I,
 2072        original_indent_columns: Vec<u32>,
 2073        cx: &mut ViewContext<Self>,
 2074    ) where
 2075        I: IntoIterator<Item = (Range<S>, T)>,
 2076        S: ToOffset,
 2077        T: Into<Arc<str>>,
 2078    {
 2079        if self.read_only(cx) {
 2080            return;
 2081        }
 2082
 2083        self.buffer.update(cx, |buffer, cx| {
 2084            buffer.edit(
 2085                edits,
 2086                Some(AutoindentMode::Block {
 2087                    original_indent_columns,
 2088                }),
 2089                cx,
 2090            )
 2091        });
 2092    }
 2093
 2094    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2095        self.hide_context_menu(cx);
 2096
 2097        match phase {
 2098            SelectPhase::Begin {
 2099                position,
 2100                add,
 2101                click_count,
 2102            } => self.begin_selection(position, add, click_count, cx),
 2103            SelectPhase::BeginColumnar {
 2104                position,
 2105                goal_column,
 2106                reset,
 2107            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2108            SelectPhase::Extend {
 2109                position,
 2110                click_count,
 2111            } => self.extend_selection(position, click_count, cx),
 2112            SelectPhase::Update {
 2113                position,
 2114                goal_column,
 2115                scroll_delta,
 2116            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2117            SelectPhase::End => self.end_selection(cx),
 2118        }
 2119    }
 2120
 2121    fn extend_selection(
 2122        &mut self,
 2123        position: DisplayPoint,
 2124        click_count: usize,
 2125        cx: &mut ViewContext<Self>,
 2126    ) {
 2127        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2128        let tail = self.selections.newest::<usize>(cx).tail();
 2129        self.begin_selection(position, false, click_count, cx);
 2130
 2131        let position = position.to_offset(&display_map, Bias::Left);
 2132        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2133
 2134        let mut pending_selection = self
 2135            .selections
 2136            .pending_anchor()
 2137            .expect("extend_selection not called with pending selection");
 2138        if position >= tail {
 2139            pending_selection.start = tail_anchor;
 2140        } else {
 2141            pending_selection.end = tail_anchor;
 2142            pending_selection.reversed = true;
 2143        }
 2144
 2145        let mut pending_mode = self.selections.pending_mode().unwrap();
 2146        match &mut pending_mode {
 2147            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2148            _ => {}
 2149        }
 2150
 2151        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2152            s.set_pending(pending_selection, pending_mode)
 2153        });
 2154    }
 2155
 2156    fn begin_selection(
 2157        &mut self,
 2158        position: DisplayPoint,
 2159        add: bool,
 2160        click_count: usize,
 2161        cx: &mut ViewContext<Self>,
 2162    ) {
 2163        if !self.focus_handle.is_focused(cx) {
 2164            self.last_focused_descendant = None;
 2165            cx.focus(&self.focus_handle);
 2166        }
 2167
 2168        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2169        let buffer = &display_map.buffer_snapshot;
 2170        let newest_selection = self.selections.newest_anchor().clone();
 2171        let position = display_map.clip_point(position, Bias::Left);
 2172
 2173        let start;
 2174        let end;
 2175        let mode;
 2176        let mut auto_scroll;
 2177        match click_count {
 2178            1 => {
 2179                start = buffer.anchor_before(position.to_point(&display_map));
 2180                end = start;
 2181                mode = SelectMode::Character;
 2182                auto_scroll = true;
 2183            }
 2184            2 => {
 2185                let range = movement::surrounding_word(&display_map, position);
 2186                start = buffer.anchor_before(range.start.to_point(&display_map));
 2187                end = buffer.anchor_before(range.end.to_point(&display_map));
 2188                mode = SelectMode::Word(start..end);
 2189                auto_scroll = true;
 2190            }
 2191            3 => {
 2192                let position = display_map
 2193                    .clip_point(position, Bias::Left)
 2194                    .to_point(&display_map);
 2195                let line_start = display_map.prev_line_boundary(position).0;
 2196                let next_line_start = buffer.clip_point(
 2197                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2198                    Bias::Left,
 2199                );
 2200                start = buffer.anchor_before(line_start);
 2201                end = buffer.anchor_before(next_line_start);
 2202                mode = SelectMode::Line(start..end);
 2203                auto_scroll = true;
 2204            }
 2205            _ => {
 2206                start = buffer.anchor_before(0);
 2207                end = buffer.anchor_before(buffer.len());
 2208                mode = SelectMode::All;
 2209                auto_scroll = false;
 2210            }
 2211        }
 2212        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2213
 2214        let point_to_delete: Option<usize> = {
 2215            let selected_points: Vec<Selection<Point>> =
 2216                self.selections.disjoint_in_range(start..end, cx);
 2217
 2218            if !add || click_count > 1 {
 2219                None
 2220            } else if !selected_points.is_empty() {
 2221                Some(selected_points[0].id)
 2222            } else {
 2223                let clicked_point_already_selected =
 2224                    self.selections.disjoint.iter().find(|selection| {
 2225                        selection.start.to_point(buffer) == start.to_point(buffer)
 2226                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2227                    });
 2228
 2229                clicked_point_already_selected.map(|selection| selection.id)
 2230            }
 2231        };
 2232
 2233        let selections_count = self.selections.count();
 2234
 2235        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2236            if let Some(point_to_delete) = point_to_delete {
 2237                s.delete(point_to_delete);
 2238
 2239                if selections_count == 1 {
 2240                    s.set_pending_anchor_range(start..end, mode);
 2241                }
 2242            } else {
 2243                if !add {
 2244                    s.clear_disjoint();
 2245                } else if click_count > 1 {
 2246                    s.delete(newest_selection.id)
 2247                }
 2248
 2249                s.set_pending_anchor_range(start..end, mode);
 2250            }
 2251        });
 2252    }
 2253
 2254    fn begin_columnar_selection(
 2255        &mut self,
 2256        position: DisplayPoint,
 2257        goal_column: u32,
 2258        reset: bool,
 2259        cx: &mut ViewContext<Self>,
 2260    ) {
 2261        if !self.focus_handle.is_focused(cx) {
 2262            self.last_focused_descendant = None;
 2263            cx.focus(&self.focus_handle);
 2264        }
 2265
 2266        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2267
 2268        if reset {
 2269            let pointer_position = display_map
 2270                .buffer_snapshot
 2271                .anchor_before(position.to_point(&display_map));
 2272
 2273            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2274                s.clear_disjoint();
 2275                s.set_pending_anchor_range(
 2276                    pointer_position..pointer_position,
 2277                    SelectMode::Character,
 2278                );
 2279            });
 2280        }
 2281
 2282        let tail = self.selections.newest::<Point>(cx).tail();
 2283        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2284
 2285        if !reset {
 2286            self.select_columns(
 2287                tail.to_display_point(&display_map),
 2288                position,
 2289                goal_column,
 2290                &display_map,
 2291                cx,
 2292            );
 2293        }
 2294    }
 2295
 2296    fn update_selection(
 2297        &mut self,
 2298        position: DisplayPoint,
 2299        goal_column: u32,
 2300        scroll_delta: gpui::Point<f32>,
 2301        cx: &mut ViewContext<Self>,
 2302    ) {
 2303        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2304
 2305        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2306            let tail = tail.to_display_point(&display_map);
 2307            self.select_columns(tail, position, goal_column, &display_map, cx);
 2308        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2309            let buffer = self.buffer.read(cx).snapshot(cx);
 2310            let head;
 2311            let tail;
 2312            let mode = self.selections.pending_mode().unwrap();
 2313            match &mode {
 2314                SelectMode::Character => {
 2315                    head = position.to_point(&display_map);
 2316                    tail = pending.tail().to_point(&buffer);
 2317                }
 2318                SelectMode::Word(original_range) => {
 2319                    let original_display_range = original_range.start.to_display_point(&display_map)
 2320                        ..original_range.end.to_display_point(&display_map);
 2321                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2322                        ..original_display_range.end.to_point(&display_map);
 2323                    if movement::is_inside_word(&display_map, position)
 2324                        || original_display_range.contains(&position)
 2325                    {
 2326                        let word_range = movement::surrounding_word(&display_map, position);
 2327                        if word_range.start < original_display_range.start {
 2328                            head = word_range.start.to_point(&display_map);
 2329                        } else {
 2330                            head = word_range.end.to_point(&display_map);
 2331                        }
 2332                    } else {
 2333                        head = position.to_point(&display_map);
 2334                    }
 2335
 2336                    if head <= original_buffer_range.start {
 2337                        tail = original_buffer_range.end;
 2338                    } else {
 2339                        tail = original_buffer_range.start;
 2340                    }
 2341                }
 2342                SelectMode::Line(original_range) => {
 2343                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2344
 2345                    let position = display_map
 2346                        .clip_point(position, Bias::Left)
 2347                        .to_point(&display_map);
 2348                    let line_start = display_map.prev_line_boundary(position).0;
 2349                    let next_line_start = buffer.clip_point(
 2350                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2351                        Bias::Left,
 2352                    );
 2353
 2354                    if line_start < original_range.start {
 2355                        head = line_start
 2356                    } else {
 2357                        head = next_line_start
 2358                    }
 2359
 2360                    if head <= original_range.start {
 2361                        tail = original_range.end;
 2362                    } else {
 2363                        tail = original_range.start;
 2364                    }
 2365                }
 2366                SelectMode::All => {
 2367                    return;
 2368                }
 2369            };
 2370
 2371            if head < tail {
 2372                pending.start = buffer.anchor_before(head);
 2373                pending.end = buffer.anchor_before(tail);
 2374                pending.reversed = true;
 2375            } else {
 2376                pending.start = buffer.anchor_before(tail);
 2377                pending.end = buffer.anchor_before(head);
 2378                pending.reversed = false;
 2379            }
 2380
 2381            self.change_selections(None, cx, |s| {
 2382                s.set_pending(pending, mode);
 2383            });
 2384        } else {
 2385            log::error!("update_selection dispatched with no pending selection");
 2386            return;
 2387        }
 2388
 2389        self.apply_scroll_delta(scroll_delta, cx);
 2390        cx.notify();
 2391    }
 2392
 2393    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2394        self.columnar_selection_tail.take();
 2395        if self.selections.pending_anchor().is_some() {
 2396            let selections = self.selections.all::<usize>(cx);
 2397            self.change_selections(None, cx, |s| {
 2398                s.select(selections);
 2399                s.clear_pending();
 2400            });
 2401        }
 2402    }
 2403
 2404    fn select_columns(
 2405        &mut self,
 2406        tail: DisplayPoint,
 2407        head: DisplayPoint,
 2408        goal_column: u32,
 2409        display_map: &DisplaySnapshot,
 2410        cx: &mut ViewContext<Self>,
 2411    ) {
 2412        let start_row = cmp::min(tail.row(), head.row());
 2413        let end_row = cmp::max(tail.row(), head.row());
 2414        let start_column = cmp::min(tail.column(), goal_column);
 2415        let end_column = cmp::max(tail.column(), goal_column);
 2416        let reversed = start_column < tail.column();
 2417
 2418        let selection_ranges = (start_row.0..=end_row.0)
 2419            .map(DisplayRow)
 2420            .filter_map(|row| {
 2421                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2422                    let start = display_map
 2423                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2424                        .to_point(display_map);
 2425                    let end = display_map
 2426                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2427                        .to_point(display_map);
 2428                    if reversed {
 2429                        Some(end..start)
 2430                    } else {
 2431                        Some(start..end)
 2432                    }
 2433                } else {
 2434                    None
 2435                }
 2436            })
 2437            .collect::<Vec<_>>();
 2438
 2439        self.change_selections(None, cx, |s| {
 2440            s.select_ranges(selection_ranges);
 2441        });
 2442        cx.notify();
 2443    }
 2444
 2445    pub fn has_pending_nonempty_selection(&self) -> bool {
 2446        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2447            Some(Selection { start, end, .. }) => start != end,
 2448            None => false,
 2449        };
 2450
 2451        pending_nonempty_selection
 2452            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2453    }
 2454
 2455    pub fn has_pending_selection(&self) -> bool {
 2456        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2457    }
 2458
 2459    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2460        if self.clear_expanded_diff_hunks(cx) {
 2461            cx.notify();
 2462            return;
 2463        }
 2464        if self.dismiss_menus_and_popups(true, cx) {
 2465            return;
 2466        }
 2467
 2468        if self.mode == EditorMode::Full
 2469            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2470        {
 2471            return;
 2472        }
 2473
 2474        cx.propagate();
 2475    }
 2476
 2477    pub fn dismiss_menus_and_popups(
 2478        &mut self,
 2479        should_report_inline_completion_event: bool,
 2480        cx: &mut ViewContext<Self>,
 2481    ) -> bool {
 2482        if self.take_rename(false, cx).is_some() {
 2483            return true;
 2484        }
 2485
 2486        if hide_hover(self, cx) {
 2487            return true;
 2488        }
 2489
 2490        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2491            return true;
 2492        }
 2493
 2494        if self.hide_context_menu(cx).is_some() {
 2495            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2496                self.update_visible_inline_completion(cx);
 2497            }
 2498            return true;
 2499        }
 2500
 2501        if self.mouse_context_menu.take().is_some() {
 2502            return true;
 2503        }
 2504
 2505        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2506            return true;
 2507        }
 2508
 2509        if self.snippet_stack.pop().is_some() {
 2510            return true;
 2511        }
 2512
 2513        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2514            self.dismiss_diagnostics(cx);
 2515            return true;
 2516        }
 2517
 2518        false
 2519    }
 2520
 2521    fn linked_editing_ranges_for(
 2522        &self,
 2523        selection: Range<text::Anchor>,
 2524        cx: &AppContext,
 2525    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2526        if self.linked_edit_ranges.is_empty() {
 2527            return None;
 2528        }
 2529        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2530            selection.end.buffer_id.and_then(|end_buffer_id| {
 2531                if selection.start.buffer_id != Some(end_buffer_id) {
 2532                    return None;
 2533                }
 2534                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2535                let snapshot = buffer.read(cx).snapshot();
 2536                self.linked_edit_ranges
 2537                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2538                    .map(|ranges| (ranges, snapshot, buffer))
 2539            })?;
 2540        use text::ToOffset as TO;
 2541        // find offset from the start of current range to current cursor position
 2542        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2543
 2544        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2545        let start_difference = start_offset - start_byte_offset;
 2546        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2547        let end_difference = end_offset - start_byte_offset;
 2548        // Current range has associated linked ranges.
 2549        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2550        for range in linked_ranges.iter() {
 2551            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2552            let end_offset = start_offset + end_difference;
 2553            let start_offset = start_offset + start_difference;
 2554            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2555                continue;
 2556            }
 2557            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 2558                if s.start.buffer_id != selection.start.buffer_id
 2559                    || s.end.buffer_id != selection.end.buffer_id
 2560                {
 2561                    return false;
 2562                }
 2563                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2564                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2565            }) {
 2566                continue;
 2567            }
 2568            let start = buffer_snapshot.anchor_after(start_offset);
 2569            let end = buffer_snapshot.anchor_after(end_offset);
 2570            linked_edits
 2571                .entry(buffer.clone())
 2572                .or_default()
 2573                .push(start..end);
 2574        }
 2575        Some(linked_edits)
 2576    }
 2577
 2578    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2579        let text: Arc<str> = text.into();
 2580
 2581        if self.read_only(cx) {
 2582            return;
 2583        }
 2584
 2585        let selections = self.selections.all_adjusted(cx);
 2586        let mut bracket_inserted = false;
 2587        let mut edits = Vec::new();
 2588        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2589        let mut new_selections = Vec::with_capacity(selections.len());
 2590        let mut new_autoclose_regions = Vec::new();
 2591        let snapshot = self.buffer.read(cx).read(cx);
 2592
 2593        for (selection, autoclose_region) in
 2594            self.selections_with_autoclose_regions(selections, &snapshot)
 2595        {
 2596            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2597                // Determine if the inserted text matches the opening or closing
 2598                // bracket of any of this language's bracket pairs.
 2599                let mut bracket_pair = None;
 2600                let mut is_bracket_pair_start = false;
 2601                let mut is_bracket_pair_end = false;
 2602                if !text.is_empty() {
 2603                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2604                    //  and they are removing the character that triggered IME popup.
 2605                    for (pair, enabled) in scope.brackets() {
 2606                        if !pair.close && !pair.surround {
 2607                            continue;
 2608                        }
 2609
 2610                        if enabled && pair.start.ends_with(text.as_ref()) {
 2611                            let prefix_len = pair.start.len() - text.len();
 2612                            let preceding_text_matches_prefix = prefix_len == 0
 2613                                || (selection.start.column >= (prefix_len as u32)
 2614                                    && snapshot.contains_str_at(
 2615                                        Point::new(
 2616                                            selection.start.row,
 2617                                            selection.start.column - (prefix_len as u32),
 2618                                        ),
 2619                                        &pair.start[..prefix_len],
 2620                                    ));
 2621                            if preceding_text_matches_prefix {
 2622                                bracket_pair = Some(pair.clone());
 2623                                is_bracket_pair_start = true;
 2624                                break;
 2625                            }
 2626                        }
 2627                        if pair.end.as_str() == text.as_ref() {
 2628                            bracket_pair = Some(pair.clone());
 2629                            is_bracket_pair_end = true;
 2630                            break;
 2631                        }
 2632                    }
 2633                }
 2634
 2635                if let Some(bracket_pair) = bracket_pair {
 2636                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2637                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2638                    let auto_surround =
 2639                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2640                    if selection.is_empty() {
 2641                        if is_bracket_pair_start {
 2642                            // If the inserted text is a suffix of an opening bracket and the
 2643                            // selection is preceded by the rest of the opening bracket, then
 2644                            // insert the closing bracket.
 2645                            let following_text_allows_autoclose = snapshot
 2646                                .chars_at(selection.start)
 2647                                .next()
 2648                                .map_or(true, |c| scope.should_autoclose_before(c));
 2649
 2650                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2651                                && bracket_pair.start.len() == 1
 2652                            {
 2653                                let target = bracket_pair.start.chars().next().unwrap();
 2654                                let current_line_count = snapshot
 2655                                    .reversed_chars_at(selection.start)
 2656                                    .take_while(|&c| c != '\n')
 2657                                    .filter(|&c| c == target)
 2658                                    .count();
 2659                                current_line_count % 2 == 1
 2660                            } else {
 2661                                false
 2662                            };
 2663
 2664                            if autoclose
 2665                                && bracket_pair.close
 2666                                && following_text_allows_autoclose
 2667                                && !is_closing_quote
 2668                            {
 2669                                let anchor = snapshot.anchor_before(selection.end);
 2670                                new_selections.push((selection.map(|_| anchor), text.len()));
 2671                                new_autoclose_regions.push((
 2672                                    anchor,
 2673                                    text.len(),
 2674                                    selection.id,
 2675                                    bracket_pair.clone(),
 2676                                ));
 2677                                edits.push((
 2678                                    selection.range(),
 2679                                    format!("{}{}", text, bracket_pair.end).into(),
 2680                                ));
 2681                                bracket_inserted = true;
 2682                                continue;
 2683                            }
 2684                        }
 2685
 2686                        if let Some(region) = autoclose_region {
 2687                            // If the selection is followed by an auto-inserted closing bracket,
 2688                            // then don't insert that closing bracket again; just move the selection
 2689                            // past the closing bracket.
 2690                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2691                                && text.as_ref() == region.pair.end.as_str();
 2692                            if should_skip {
 2693                                let anchor = snapshot.anchor_after(selection.end);
 2694                                new_selections
 2695                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2696                                continue;
 2697                            }
 2698                        }
 2699
 2700                        let always_treat_brackets_as_autoclosed = snapshot
 2701                            .settings_at(selection.start, cx)
 2702                            .always_treat_brackets_as_autoclosed;
 2703                        if always_treat_brackets_as_autoclosed
 2704                            && is_bracket_pair_end
 2705                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2706                        {
 2707                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2708                            // and the inserted text is a closing bracket and the selection is followed
 2709                            // by the closing bracket then move the selection past the closing bracket.
 2710                            let anchor = snapshot.anchor_after(selection.end);
 2711                            new_selections.push((selection.map(|_| anchor), text.len()));
 2712                            continue;
 2713                        }
 2714                    }
 2715                    // If an opening bracket is 1 character long and is typed while
 2716                    // text is selected, then surround that text with the bracket pair.
 2717                    else if auto_surround
 2718                        && bracket_pair.surround
 2719                        && is_bracket_pair_start
 2720                        && bracket_pair.start.chars().count() == 1
 2721                    {
 2722                        edits.push((selection.start..selection.start, text.clone()));
 2723                        edits.push((
 2724                            selection.end..selection.end,
 2725                            bracket_pair.end.as_str().into(),
 2726                        ));
 2727                        bracket_inserted = true;
 2728                        new_selections.push((
 2729                            Selection {
 2730                                id: selection.id,
 2731                                start: snapshot.anchor_after(selection.start),
 2732                                end: snapshot.anchor_before(selection.end),
 2733                                reversed: selection.reversed,
 2734                                goal: selection.goal,
 2735                            },
 2736                            0,
 2737                        ));
 2738                        continue;
 2739                    }
 2740                }
 2741            }
 2742
 2743            if self.auto_replace_emoji_shortcode
 2744                && selection.is_empty()
 2745                && text.as_ref().ends_with(':')
 2746            {
 2747                if let Some(possible_emoji_short_code) =
 2748                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2749                {
 2750                    if !possible_emoji_short_code.is_empty() {
 2751                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2752                            let emoji_shortcode_start = Point::new(
 2753                                selection.start.row,
 2754                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2755                            );
 2756
 2757                            // Remove shortcode from buffer
 2758                            edits.push((
 2759                                emoji_shortcode_start..selection.start,
 2760                                "".to_string().into(),
 2761                            ));
 2762                            new_selections.push((
 2763                                Selection {
 2764                                    id: selection.id,
 2765                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2766                                    end: snapshot.anchor_before(selection.start),
 2767                                    reversed: selection.reversed,
 2768                                    goal: selection.goal,
 2769                                },
 2770                                0,
 2771                            ));
 2772
 2773                            // Insert emoji
 2774                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2775                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2776                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2777
 2778                            continue;
 2779                        }
 2780                    }
 2781                }
 2782            }
 2783
 2784            // If not handling any auto-close operation, then just replace the selected
 2785            // text with the given input and move the selection to the end of the
 2786            // newly inserted text.
 2787            let anchor = snapshot.anchor_after(selection.end);
 2788            if !self.linked_edit_ranges.is_empty() {
 2789                let start_anchor = snapshot.anchor_before(selection.start);
 2790
 2791                let is_word_char = text.chars().next().map_or(true, |char| {
 2792                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2793                    classifier.is_word(char)
 2794                });
 2795
 2796                if is_word_char {
 2797                    if let Some(ranges) = self
 2798                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2799                    {
 2800                        for (buffer, edits) in ranges {
 2801                            linked_edits
 2802                                .entry(buffer.clone())
 2803                                .or_default()
 2804                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2805                        }
 2806                    }
 2807                }
 2808            }
 2809
 2810            new_selections.push((selection.map(|_| anchor), 0));
 2811            edits.push((selection.start..selection.end, text.clone()));
 2812        }
 2813
 2814        drop(snapshot);
 2815
 2816        self.transact(cx, |this, cx| {
 2817            this.buffer.update(cx, |buffer, cx| {
 2818                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2819            });
 2820            for (buffer, edits) in linked_edits {
 2821                buffer.update(cx, |buffer, cx| {
 2822                    let snapshot = buffer.snapshot();
 2823                    let edits = edits
 2824                        .into_iter()
 2825                        .map(|(range, text)| {
 2826                            use text::ToPoint as TP;
 2827                            let end_point = TP::to_point(&range.end, &snapshot);
 2828                            let start_point = TP::to_point(&range.start, &snapshot);
 2829                            (start_point..end_point, text)
 2830                        })
 2831                        .sorted_by_key(|(range, _)| range.start)
 2832                        .collect::<Vec<_>>();
 2833                    buffer.edit(edits, None, cx);
 2834                })
 2835            }
 2836            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2837            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2838            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2839            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2840                .zip(new_selection_deltas)
 2841                .map(|(selection, delta)| Selection {
 2842                    id: selection.id,
 2843                    start: selection.start + delta,
 2844                    end: selection.end + delta,
 2845                    reversed: selection.reversed,
 2846                    goal: SelectionGoal::None,
 2847                })
 2848                .collect::<Vec<_>>();
 2849
 2850            let mut i = 0;
 2851            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2852                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2853                let start = map.buffer_snapshot.anchor_before(position);
 2854                let end = map.buffer_snapshot.anchor_after(position);
 2855                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2856                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2857                        Ordering::Less => i += 1,
 2858                        Ordering::Greater => break,
 2859                        Ordering::Equal => {
 2860                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2861                                Ordering::Less => i += 1,
 2862                                Ordering::Equal => break,
 2863                                Ordering::Greater => break,
 2864                            }
 2865                        }
 2866                    }
 2867                }
 2868                this.autoclose_regions.insert(
 2869                    i,
 2870                    AutocloseRegion {
 2871                        selection_id,
 2872                        range: start..end,
 2873                        pair,
 2874                    },
 2875                );
 2876            }
 2877
 2878            let had_active_inline_completion = this.has_active_inline_completion();
 2879            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2880                s.select(new_selections)
 2881            });
 2882
 2883            if !bracket_inserted {
 2884                if let Some(on_type_format_task) =
 2885                    this.trigger_on_type_formatting(text.to_string(), cx)
 2886                {
 2887                    on_type_format_task.detach_and_log_err(cx);
 2888                }
 2889            }
 2890
 2891            let editor_settings = EditorSettings::get_global(cx);
 2892            if bracket_inserted
 2893                && (editor_settings.auto_signature_help
 2894                    || editor_settings.show_signature_help_after_edits)
 2895            {
 2896                this.show_signature_help(&ShowSignatureHelp, cx);
 2897            }
 2898
 2899            let trigger_in_words =
 2900                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2901            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2902            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2903            this.refresh_inline_completion(true, false, cx);
 2904        });
 2905    }
 2906
 2907    fn find_possible_emoji_shortcode_at_position(
 2908        snapshot: &MultiBufferSnapshot,
 2909        position: Point,
 2910    ) -> Option<String> {
 2911        let mut chars = Vec::new();
 2912        let mut found_colon = false;
 2913        for char in snapshot.reversed_chars_at(position).take(100) {
 2914            // Found a possible emoji shortcode in the middle of the buffer
 2915            if found_colon {
 2916                if char.is_whitespace() {
 2917                    chars.reverse();
 2918                    return Some(chars.iter().collect());
 2919                }
 2920                // If the previous character is not a whitespace, we are in the middle of a word
 2921                // and we only want to complete the shortcode if the word is made up of other emojis
 2922                let mut containing_word = String::new();
 2923                for ch in snapshot
 2924                    .reversed_chars_at(position)
 2925                    .skip(chars.len() + 1)
 2926                    .take(100)
 2927                {
 2928                    if ch.is_whitespace() {
 2929                        break;
 2930                    }
 2931                    containing_word.push(ch);
 2932                }
 2933                let containing_word = containing_word.chars().rev().collect::<String>();
 2934                if util::word_consists_of_emojis(containing_word.as_str()) {
 2935                    chars.reverse();
 2936                    return Some(chars.iter().collect());
 2937                }
 2938            }
 2939
 2940            if char.is_whitespace() || !char.is_ascii() {
 2941                return None;
 2942            }
 2943            if char == ':' {
 2944                found_colon = true;
 2945            } else {
 2946                chars.push(char);
 2947            }
 2948        }
 2949        // Found a possible emoji shortcode at the beginning of the buffer
 2950        chars.reverse();
 2951        Some(chars.iter().collect())
 2952    }
 2953
 2954    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2955        self.transact(cx, |this, cx| {
 2956            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2957                let selections = this.selections.all::<usize>(cx);
 2958                let multi_buffer = this.buffer.read(cx);
 2959                let buffer = multi_buffer.snapshot(cx);
 2960                selections
 2961                    .iter()
 2962                    .map(|selection| {
 2963                        let start_point = selection.start.to_point(&buffer);
 2964                        let mut indent =
 2965                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2966                        indent.len = cmp::min(indent.len, start_point.column);
 2967                        let start = selection.start;
 2968                        let end = selection.end;
 2969                        let selection_is_empty = start == end;
 2970                        let language_scope = buffer.language_scope_at(start);
 2971                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2972                            &language_scope
 2973                        {
 2974                            let leading_whitespace_len = buffer
 2975                                .reversed_chars_at(start)
 2976                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2977                                .map(|c| c.len_utf8())
 2978                                .sum::<usize>();
 2979
 2980                            let trailing_whitespace_len = buffer
 2981                                .chars_at(end)
 2982                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2983                                .map(|c| c.len_utf8())
 2984                                .sum::<usize>();
 2985
 2986                            let insert_extra_newline =
 2987                                language.brackets().any(|(pair, enabled)| {
 2988                                    let pair_start = pair.start.trim_end();
 2989                                    let pair_end = pair.end.trim_start();
 2990
 2991                                    enabled
 2992                                        && pair.newline
 2993                                        && buffer.contains_str_at(
 2994                                            end + trailing_whitespace_len,
 2995                                            pair_end,
 2996                                        )
 2997                                        && buffer.contains_str_at(
 2998                                            (start - leading_whitespace_len)
 2999                                                .saturating_sub(pair_start.len()),
 3000                                            pair_start,
 3001                                        )
 3002                                });
 3003
 3004                            // Comment extension on newline is allowed only for cursor selections
 3005                            let comment_delimiter = maybe!({
 3006                                if !selection_is_empty {
 3007                                    return None;
 3008                                }
 3009
 3010                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3011                                    return None;
 3012                                }
 3013
 3014                                let delimiters = language.line_comment_prefixes();
 3015                                let max_len_of_delimiter =
 3016                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3017                                let (snapshot, range) =
 3018                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3019
 3020                                let mut index_of_first_non_whitespace = 0;
 3021                                let comment_candidate = snapshot
 3022                                    .chars_for_range(range)
 3023                                    .skip_while(|c| {
 3024                                        let should_skip = c.is_whitespace();
 3025                                        if should_skip {
 3026                                            index_of_first_non_whitespace += 1;
 3027                                        }
 3028                                        should_skip
 3029                                    })
 3030                                    .take(max_len_of_delimiter)
 3031                                    .collect::<String>();
 3032                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3033                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3034                                })?;
 3035                                let cursor_is_placed_after_comment_marker =
 3036                                    index_of_first_non_whitespace + comment_prefix.len()
 3037                                        <= start_point.column as usize;
 3038                                if cursor_is_placed_after_comment_marker {
 3039                                    Some(comment_prefix.clone())
 3040                                } else {
 3041                                    None
 3042                                }
 3043                            });
 3044                            (comment_delimiter, insert_extra_newline)
 3045                        } else {
 3046                            (None, false)
 3047                        };
 3048
 3049                        let capacity_for_delimiter = comment_delimiter
 3050                            .as_deref()
 3051                            .map(str::len)
 3052                            .unwrap_or_default();
 3053                        let mut new_text =
 3054                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3055                        new_text.push('\n');
 3056                        new_text.extend(indent.chars());
 3057                        if let Some(delimiter) = &comment_delimiter {
 3058                            new_text.push_str(delimiter);
 3059                        }
 3060                        if insert_extra_newline {
 3061                            new_text = new_text.repeat(2);
 3062                        }
 3063
 3064                        let anchor = buffer.anchor_after(end);
 3065                        let new_selection = selection.map(|_| anchor);
 3066                        (
 3067                            (start..end, new_text),
 3068                            (insert_extra_newline, new_selection),
 3069                        )
 3070                    })
 3071                    .unzip()
 3072            };
 3073
 3074            this.edit_with_autoindent(edits, cx);
 3075            let buffer = this.buffer.read(cx).snapshot(cx);
 3076            let new_selections = selection_fixup_info
 3077                .into_iter()
 3078                .map(|(extra_newline_inserted, new_selection)| {
 3079                    let mut cursor = new_selection.end.to_point(&buffer);
 3080                    if extra_newline_inserted {
 3081                        cursor.row -= 1;
 3082                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3083                    }
 3084                    new_selection.map(|_| cursor)
 3085                })
 3086                .collect();
 3087
 3088            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3089            this.refresh_inline_completion(true, false, cx);
 3090        });
 3091    }
 3092
 3093    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3094        let buffer = self.buffer.read(cx);
 3095        let snapshot = buffer.snapshot(cx);
 3096
 3097        let mut edits = Vec::new();
 3098        let mut rows = Vec::new();
 3099
 3100        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3101            let cursor = selection.head();
 3102            let row = cursor.row;
 3103
 3104            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3105
 3106            let newline = "\n".to_string();
 3107            edits.push((start_of_line..start_of_line, newline));
 3108
 3109            rows.push(row + rows_inserted as u32);
 3110        }
 3111
 3112        self.transact(cx, |editor, cx| {
 3113            editor.edit(edits, cx);
 3114
 3115            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3116                let mut index = 0;
 3117                s.move_cursors_with(|map, _, _| {
 3118                    let row = rows[index];
 3119                    index += 1;
 3120
 3121                    let point = Point::new(row, 0);
 3122                    let boundary = map.next_line_boundary(point).1;
 3123                    let clipped = map.clip_point(boundary, Bias::Left);
 3124
 3125                    (clipped, SelectionGoal::None)
 3126                });
 3127            });
 3128
 3129            let mut indent_edits = Vec::new();
 3130            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3131            for row in rows {
 3132                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3133                for (row, indent) in indents {
 3134                    if indent.len == 0 {
 3135                        continue;
 3136                    }
 3137
 3138                    let text = match indent.kind {
 3139                        IndentKind::Space => " ".repeat(indent.len as usize),
 3140                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3141                    };
 3142                    let point = Point::new(row.0, 0);
 3143                    indent_edits.push((point..point, text));
 3144                }
 3145            }
 3146            editor.edit(indent_edits, cx);
 3147        });
 3148    }
 3149
 3150    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3151        let buffer = self.buffer.read(cx);
 3152        let snapshot = buffer.snapshot(cx);
 3153
 3154        let mut edits = Vec::new();
 3155        let mut rows = Vec::new();
 3156        let mut rows_inserted = 0;
 3157
 3158        for selection in self.selections.all_adjusted(cx) {
 3159            let cursor = selection.head();
 3160            let row = cursor.row;
 3161
 3162            let point = Point::new(row + 1, 0);
 3163            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3164
 3165            let newline = "\n".to_string();
 3166            edits.push((start_of_line..start_of_line, newline));
 3167
 3168            rows_inserted += 1;
 3169            rows.push(row + rows_inserted);
 3170        }
 3171
 3172        self.transact(cx, |editor, cx| {
 3173            editor.edit(edits, cx);
 3174
 3175            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3176                let mut index = 0;
 3177                s.move_cursors_with(|map, _, _| {
 3178                    let row = rows[index];
 3179                    index += 1;
 3180
 3181                    let point = Point::new(row, 0);
 3182                    let boundary = map.next_line_boundary(point).1;
 3183                    let clipped = map.clip_point(boundary, Bias::Left);
 3184
 3185                    (clipped, SelectionGoal::None)
 3186                });
 3187            });
 3188
 3189            let mut indent_edits = Vec::new();
 3190            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3191            for row in rows {
 3192                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3193                for (row, indent) in indents {
 3194                    if indent.len == 0 {
 3195                        continue;
 3196                    }
 3197
 3198                    let text = match indent.kind {
 3199                        IndentKind::Space => " ".repeat(indent.len as usize),
 3200                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3201                    };
 3202                    let point = Point::new(row.0, 0);
 3203                    indent_edits.push((point..point, text));
 3204                }
 3205            }
 3206            editor.edit(indent_edits, cx);
 3207        });
 3208    }
 3209
 3210    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3211        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3212            original_indent_columns: Vec::new(),
 3213        });
 3214        self.insert_with_autoindent_mode(text, autoindent, cx);
 3215    }
 3216
 3217    fn insert_with_autoindent_mode(
 3218        &mut self,
 3219        text: &str,
 3220        autoindent_mode: Option<AutoindentMode>,
 3221        cx: &mut ViewContext<Self>,
 3222    ) {
 3223        if self.read_only(cx) {
 3224            return;
 3225        }
 3226
 3227        let text: Arc<str> = text.into();
 3228        self.transact(cx, |this, cx| {
 3229            let old_selections = this.selections.all_adjusted(cx);
 3230            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3231                let anchors = {
 3232                    let snapshot = buffer.read(cx);
 3233                    old_selections
 3234                        .iter()
 3235                        .map(|s| {
 3236                            let anchor = snapshot.anchor_after(s.head());
 3237                            s.map(|_| anchor)
 3238                        })
 3239                        .collect::<Vec<_>>()
 3240                };
 3241                buffer.edit(
 3242                    old_selections
 3243                        .iter()
 3244                        .map(|s| (s.start..s.end, text.clone())),
 3245                    autoindent_mode,
 3246                    cx,
 3247                );
 3248                anchors
 3249            });
 3250
 3251            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3252                s.select_anchors(selection_anchors);
 3253            })
 3254        });
 3255    }
 3256
 3257    fn trigger_completion_on_input(
 3258        &mut self,
 3259        text: &str,
 3260        trigger_in_words: bool,
 3261        cx: &mut ViewContext<Self>,
 3262    ) {
 3263        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3264            self.show_completions(
 3265                &ShowCompletions {
 3266                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3267                },
 3268                cx,
 3269            );
 3270        } else {
 3271            self.hide_context_menu(cx);
 3272        }
 3273    }
 3274
 3275    fn is_completion_trigger(
 3276        &self,
 3277        text: &str,
 3278        trigger_in_words: bool,
 3279        cx: &mut ViewContext<Self>,
 3280    ) -> bool {
 3281        let position = self.selections.newest_anchor().head();
 3282        let multibuffer = self.buffer.read(cx);
 3283        let Some(buffer) = position
 3284            .buffer_id
 3285            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3286        else {
 3287            return false;
 3288        };
 3289
 3290        if let Some(completion_provider) = &self.completion_provider {
 3291            completion_provider.is_completion_trigger(
 3292                &buffer,
 3293                position.text_anchor,
 3294                text,
 3295                trigger_in_words,
 3296                cx,
 3297            )
 3298        } else {
 3299            false
 3300        }
 3301    }
 3302
 3303    /// If any empty selections is touching the start of its innermost containing autoclose
 3304    /// region, expand it to select the brackets.
 3305    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3306        let selections = self.selections.all::<usize>(cx);
 3307        let buffer = self.buffer.read(cx).read(cx);
 3308        let new_selections = self
 3309            .selections_with_autoclose_regions(selections, &buffer)
 3310            .map(|(mut selection, region)| {
 3311                if !selection.is_empty() {
 3312                    return selection;
 3313                }
 3314
 3315                if let Some(region) = region {
 3316                    let mut range = region.range.to_offset(&buffer);
 3317                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3318                        range.start -= region.pair.start.len();
 3319                        if buffer.contains_str_at(range.start, &region.pair.start)
 3320                            && buffer.contains_str_at(range.end, &region.pair.end)
 3321                        {
 3322                            range.end += region.pair.end.len();
 3323                            selection.start = range.start;
 3324                            selection.end = range.end;
 3325
 3326                            return selection;
 3327                        }
 3328                    }
 3329                }
 3330
 3331                let always_treat_brackets_as_autoclosed = buffer
 3332                    .settings_at(selection.start, cx)
 3333                    .always_treat_brackets_as_autoclosed;
 3334
 3335                if !always_treat_brackets_as_autoclosed {
 3336                    return selection;
 3337                }
 3338
 3339                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3340                    for (pair, enabled) in scope.brackets() {
 3341                        if !enabled || !pair.close {
 3342                            continue;
 3343                        }
 3344
 3345                        if buffer.contains_str_at(selection.start, &pair.end) {
 3346                            let pair_start_len = pair.start.len();
 3347                            if buffer.contains_str_at(
 3348                                selection.start.saturating_sub(pair_start_len),
 3349                                &pair.start,
 3350                            ) {
 3351                                selection.start -= pair_start_len;
 3352                                selection.end += pair.end.len();
 3353
 3354                                return selection;
 3355                            }
 3356                        }
 3357                    }
 3358                }
 3359
 3360                selection
 3361            })
 3362            .collect();
 3363
 3364        drop(buffer);
 3365        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3366    }
 3367
 3368    /// Iterate the given selections, and for each one, find the smallest surrounding
 3369    /// autoclose region. This uses the ordering of the selections and the autoclose
 3370    /// regions to avoid repeated comparisons.
 3371    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3372        &'a self,
 3373        selections: impl IntoIterator<Item = Selection<D>>,
 3374        buffer: &'a MultiBufferSnapshot,
 3375    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3376        let mut i = 0;
 3377        let mut regions = self.autoclose_regions.as_slice();
 3378        selections.into_iter().map(move |selection| {
 3379            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3380
 3381            let mut enclosing = None;
 3382            while let Some(pair_state) = regions.get(i) {
 3383                if pair_state.range.end.to_offset(buffer) < range.start {
 3384                    regions = &regions[i + 1..];
 3385                    i = 0;
 3386                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3387                    break;
 3388                } else {
 3389                    if pair_state.selection_id == selection.id {
 3390                        enclosing = Some(pair_state);
 3391                    }
 3392                    i += 1;
 3393                }
 3394            }
 3395
 3396            (selection, enclosing)
 3397        })
 3398    }
 3399
 3400    /// Remove any autoclose regions that no longer contain their selection.
 3401    fn invalidate_autoclose_regions(
 3402        &mut self,
 3403        mut selections: &[Selection<Anchor>],
 3404        buffer: &MultiBufferSnapshot,
 3405    ) {
 3406        self.autoclose_regions.retain(|state| {
 3407            let mut i = 0;
 3408            while let Some(selection) = selections.get(i) {
 3409                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3410                    selections = &selections[1..];
 3411                    continue;
 3412                }
 3413                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3414                    break;
 3415                }
 3416                if selection.id == state.selection_id {
 3417                    return true;
 3418                } else {
 3419                    i += 1;
 3420                }
 3421            }
 3422            false
 3423        });
 3424    }
 3425
 3426    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3427        let offset = position.to_offset(buffer);
 3428        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3429        if offset > word_range.start && kind == Some(CharKind::Word) {
 3430            Some(
 3431                buffer
 3432                    .text_for_range(word_range.start..offset)
 3433                    .collect::<String>(),
 3434            )
 3435        } else {
 3436            None
 3437        }
 3438    }
 3439
 3440    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3441        self.refresh_inlay_hints(
 3442            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3443            cx,
 3444        );
 3445    }
 3446
 3447    pub fn inlay_hints_enabled(&self) -> bool {
 3448        self.inlay_hint_cache.enabled
 3449    }
 3450
 3451    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3452        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3453            return;
 3454        }
 3455
 3456        let reason_description = reason.description();
 3457        let ignore_debounce = matches!(
 3458            reason,
 3459            InlayHintRefreshReason::SettingsChange(_)
 3460                | InlayHintRefreshReason::Toggle(_)
 3461                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3462        );
 3463        let (invalidate_cache, required_languages) = match reason {
 3464            InlayHintRefreshReason::Toggle(enabled) => {
 3465                self.inlay_hint_cache.enabled = enabled;
 3466                if enabled {
 3467                    (InvalidationStrategy::RefreshRequested, None)
 3468                } else {
 3469                    self.inlay_hint_cache.clear();
 3470                    self.splice_inlays(
 3471                        self.visible_inlay_hints(cx)
 3472                            .iter()
 3473                            .map(|inlay| inlay.id)
 3474                            .collect(),
 3475                        Vec::new(),
 3476                        cx,
 3477                    );
 3478                    return;
 3479                }
 3480            }
 3481            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3482                match self.inlay_hint_cache.update_settings(
 3483                    &self.buffer,
 3484                    new_settings,
 3485                    self.visible_inlay_hints(cx),
 3486                    cx,
 3487                ) {
 3488                    ControlFlow::Break(Some(InlaySplice {
 3489                        to_remove,
 3490                        to_insert,
 3491                    })) => {
 3492                        self.splice_inlays(to_remove, to_insert, cx);
 3493                        return;
 3494                    }
 3495                    ControlFlow::Break(None) => return,
 3496                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3497                }
 3498            }
 3499            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3500                if let Some(InlaySplice {
 3501                    to_remove,
 3502                    to_insert,
 3503                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3504                {
 3505                    self.splice_inlays(to_remove, to_insert, cx);
 3506                }
 3507                return;
 3508            }
 3509            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3510            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3511                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3512            }
 3513            InlayHintRefreshReason::RefreshRequested => {
 3514                (InvalidationStrategy::RefreshRequested, None)
 3515            }
 3516        };
 3517
 3518        if let Some(InlaySplice {
 3519            to_remove,
 3520            to_insert,
 3521        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3522            reason_description,
 3523            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3524            invalidate_cache,
 3525            ignore_debounce,
 3526            cx,
 3527        ) {
 3528            self.splice_inlays(to_remove, to_insert, cx);
 3529        }
 3530    }
 3531
 3532    fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
 3533        self.display_map
 3534            .read(cx)
 3535            .current_inlays()
 3536            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3537            .cloned()
 3538            .collect()
 3539    }
 3540
 3541    pub fn excerpts_for_inlay_hints_query(
 3542        &self,
 3543        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3544        cx: &mut ViewContext<Editor>,
 3545    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3546        let Some(project) = self.project.as_ref() else {
 3547            return HashMap::default();
 3548        };
 3549        let project = project.read(cx);
 3550        let multi_buffer = self.buffer().read(cx);
 3551        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3552        let multi_buffer_visible_start = self
 3553            .scroll_manager
 3554            .anchor()
 3555            .anchor
 3556            .to_point(&multi_buffer_snapshot);
 3557        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3558            multi_buffer_visible_start
 3559                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3560            Bias::Left,
 3561        );
 3562        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3563        multi_buffer_snapshot
 3564            .range_to_buffer_ranges(multi_buffer_visible_range)
 3565            .into_iter()
 3566            .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
 3567            .filter_map(|(excerpt, excerpt_visible_range)| {
 3568                let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
 3569                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3570                let worktree_entry = buffer_worktree
 3571                    .read(cx)
 3572                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3573                if worktree_entry.is_ignored {
 3574                    return None;
 3575                }
 3576
 3577                let language = excerpt.buffer().language()?;
 3578                if let Some(restrict_to_languages) = restrict_to_languages {
 3579                    if !restrict_to_languages.contains(language) {
 3580                        return None;
 3581                    }
 3582                }
 3583                Some((
 3584                    excerpt.id(),
 3585                    (
 3586                        multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
 3587                        excerpt.buffer().version().clone(),
 3588                        excerpt_visible_range,
 3589                    ),
 3590                ))
 3591            })
 3592            .collect()
 3593    }
 3594
 3595    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3596        TextLayoutDetails {
 3597            text_system: cx.text_system().clone(),
 3598            editor_style: self.style.clone().unwrap(),
 3599            rem_size: cx.rem_size(),
 3600            scroll_anchor: self.scroll_manager.anchor(),
 3601            visible_rows: self.visible_line_count(),
 3602            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3603        }
 3604    }
 3605
 3606    pub fn splice_inlays(
 3607        &self,
 3608        to_remove: Vec<InlayId>,
 3609        to_insert: Vec<Inlay>,
 3610        cx: &mut ViewContext<Self>,
 3611    ) {
 3612        self.display_map.update(cx, |display_map, cx| {
 3613            display_map.splice_inlays(to_remove, to_insert, cx)
 3614        });
 3615        cx.notify();
 3616    }
 3617
 3618    fn trigger_on_type_formatting(
 3619        &self,
 3620        input: String,
 3621        cx: &mut ViewContext<Self>,
 3622    ) -> Option<Task<Result<()>>> {
 3623        if input.len() != 1 {
 3624            return None;
 3625        }
 3626
 3627        let project = self.project.as_ref()?;
 3628        let position = self.selections.newest_anchor().head();
 3629        let (buffer, buffer_position) = self
 3630            .buffer
 3631            .read(cx)
 3632            .text_anchor_for_position(position, cx)?;
 3633
 3634        let settings = language_settings::language_settings(
 3635            buffer
 3636                .read(cx)
 3637                .language_at(buffer_position)
 3638                .map(|l| l.name()),
 3639            buffer.read(cx).file(),
 3640            cx,
 3641        );
 3642        if !settings.use_on_type_format {
 3643            return None;
 3644        }
 3645
 3646        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3647        // hence we do LSP request & edit on host side only — add formats to host's history.
 3648        let push_to_lsp_host_history = true;
 3649        // If this is not the host, append its history with new edits.
 3650        let push_to_client_history = project.read(cx).is_via_collab();
 3651
 3652        let on_type_formatting = project.update(cx, |project, cx| {
 3653            project.on_type_format(
 3654                buffer.clone(),
 3655                buffer_position,
 3656                input,
 3657                push_to_lsp_host_history,
 3658                cx,
 3659            )
 3660        });
 3661        Some(cx.spawn(|editor, mut cx| async move {
 3662            if let Some(transaction) = on_type_formatting.await? {
 3663                if push_to_client_history {
 3664                    buffer
 3665                        .update(&mut cx, |buffer, _| {
 3666                            buffer.push_transaction(transaction, Instant::now());
 3667                        })
 3668                        .ok();
 3669                }
 3670                editor.update(&mut cx, |editor, cx| {
 3671                    editor.refresh_document_highlights(cx);
 3672                })?;
 3673            }
 3674            Ok(())
 3675        }))
 3676    }
 3677
 3678    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3679        if self.pending_rename.is_some() {
 3680            return;
 3681        }
 3682
 3683        let Some(provider) = self.completion_provider.as_ref() else {
 3684            return;
 3685        };
 3686
 3687        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3688            return;
 3689        }
 3690
 3691        let position = self.selections.newest_anchor().head();
 3692        let (buffer, buffer_position) =
 3693            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3694                output
 3695            } else {
 3696                return;
 3697            };
 3698        let show_completion_documentation = buffer
 3699            .read(cx)
 3700            .snapshot()
 3701            .settings_at(buffer_position, cx)
 3702            .show_completion_documentation;
 3703
 3704        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3705
 3706        let trigger_kind = match &options.trigger {
 3707            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3708                CompletionTriggerKind::TRIGGER_CHARACTER
 3709            }
 3710            _ => CompletionTriggerKind::INVOKED,
 3711        };
 3712        let completion_context = CompletionContext {
 3713            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3714                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3715                    Some(String::from(trigger))
 3716                } else {
 3717                    None
 3718                }
 3719            }),
 3720            trigger_kind,
 3721        };
 3722        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3723        let sort_completions = provider.sort_completions();
 3724
 3725        let id = post_inc(&mut self.next_completion_id);
 3726        let task = cx.spawn(|editor, mut cx| {
 3727            async move {
 3728                editor.update(&mut cx, |this, _| {
 3729                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3730                })?;
 3731                let completions = completions.await.log_err();
 3732                let menu = if let Some(completions) = completions {
 3733                    let mut menu = CompletionsMenu::new(
 3734                        id,
 3735                        sort_completions,
 3736                        show_completion_documentation,
 3737                        position,
 3738                        buffer.clone(),
 3739                        completions.into(),
 3740                    );
 3741
 3742                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3743                        .await;
 3744
 3745                    menu.visible().then_some(menu)
 3746                } else {
 3747                    None
 3748                };
 3749
 3750                editor.update(&mut cx, |editor, cx| {
 3751                    match editor.context_menu.borrow().as_ref() {
 3752                        None => {}
 3753                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3754                            if prev_menu.id > id {
 3755                                return;
 3756                            }
 3757                        }
 3758                        _ => return,
 3759                    }
 3760
 3761                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3762                        let mut menu = menu.unwrap();
 3763                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3764
 3765                        if editor.show_inline_completions_in_menu(cx) {
 3766                            if let Some(hint) = editor.inline_completion_menu_hint(cx) {
 3767                                menu.show_inline_completion_hint(hint);
 3768                            }
 3769                        } else {
 3770                            editor.discard_inline_completion(false, cx);
 3771                        }
 3772
 3773                        *editor.context_menu.borrow_mut() =
 3774                            Some(CodeContextMenu::Completions(menu));
 3775
 3776                        cx.notify();
 3777                    } else if editor.completion_tasks.len() <= 1 {
 3778                        // If there are no more completion tasks and the last menu was
 3779                        // empty, we should hide it.
 3780                        let was_hidden = editor.hide_context_menu(cx).is_none();
 3781                        // If it was already hidden and we don't show inline
 3782                        // completions in the menu, we should also show the
 3783                        // inline-completion when available.
 3784                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3785                            editor.update_visible_inline_completion(cx);
 3786                        }
 3787                    }
 3788                })?;
 3789
 3790                Ok::<_, anyhow::Error>(())
 3791            }
 3792            .log_err()
 3793        });
 3794
 3795        self.completion_tasks.push((id, task));
 3796    }
 3797
 3798    pub fn confirm_completion(
 3799        &mut self,
 3800        action: &ConfirmCompletion,
 3801        cx: &mut ViewContext<Self>,
 3802    ) -> Option<Task<Result<()>>> {
 3803        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3804    }
 3805
 3806    pub fn compose_completion(
 3807        &mut self,
 3808        action: &ComposeCompletion,
 3809        cx: &mut ViewContext<Self>,
 3810    ) -> Option<Task<Result<()>>> {
 3811        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3812    }
 3813
 3814    fn do_completion(
 3815        &mut self,
 3816        item_ix: Option<usize>,
 3817        intent: CompletionIntent,
 3818        cx: &mut ViewContext<Editor>,
 3819    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3820        use language::ToOffset as _;
 3821
 3822        let completions_menu =
 3823            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3824                menu
 3825            } else {
 3826                return None;
 3827            };
 3828
 3829        let entries = completions_menu.entries.borrow();
 3830        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3831        let mat = match mat {
 3832            CompletionEntry::InlineCompletionHint { .. } => {
 3833                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3834                cx.stop_propagation();
 3835                return Some(Task::ready(Ok(())));
 3836            }
 3837            CompletionEntry::Match(mat) => {
 3838                if self.show_inline_completions_in_menu(cx) {
 3839                    self.discard_inline_completion(true, cx);
 3840                }
 3841                mat
 3842            }
 3843        };
 3844        let candidate_id = mat.candidate_id;
 3845        drop(entries);
 3846
 3847        let buffer_handle = completions_menu.buffer;
 3848        let completion = completions_menu
 3849            .completions
 3850            .borrow()
 3851            .get(candidate_id)?
 3852            .clone();
 3853        cx.stop_propagation();
 3854
 3855        let snippet;
 3856        let text;
 3857
 3858        if completion.is_snippet() {
 3859            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3860            text = snippet.as_ref().unwrap().text.clone();
 3861        } else {
 3862            snippet = None;
 3863            text = completion.new_text.clone();
 3864        };
 3865        let selections = self.selections.all::<usize>(cx);
 3866        let buffer = buffer_handle.read(cx);
 3867        let old_range = completion.old_range.to_offset(buffer);
 3868        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3869
 3870        let newest_selection = self.selections.newest_anchor();
 3871        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3872            return None;
 3873        }
 3874
 3875        let lookbehind = newest_selection
 3876            .start
 3877            .text_anchor
 3878            .to_offset(buffer)
 3879            .saturating_sub(old_range.start);
 3880        let lookahead = old_range
 3881            .end
 3882            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3883        let mut common_prefix_len = old_text
 3884            .bytes()
 3885            .zip(text.bytes())
 3886            .take_while(|(a, b)| a == b)
 3887            .count();
 3888
 3889        let snapshot = self.buffer.read(cx).snapshot(cx);
 3890        let mut range_to_replace: Option<Range<isize>> = None;
 3891        let mut ranges = Vec::new();
 3892        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3893        for selection in &selections {
 3894            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3895                let start = selection.start.saturating_sub(lookbehind);
 3896                let end = selection.end + lookahead;
 3897                if selection.id == newest_selection.id {
 3898                    range_to_replace = Some(
 3899                        ((start + common_prefix_len) as isize - selection.start as isize)
 3900                            ..(end as isize - selection.start as isize),
 3901                    );
 3902                }
 3903                ranges.push(start + common_prefix_len..end);
 3904            } else {
 3905                common_prefix_len = 0;
 3906                ranges.clear();
 3907                ranges.extend(selections.iter().map(|s| {
 3908                    if s.id == newest_selection.id {
 3909                        range_to_replace = Some(
 3910                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3911                                - selection.start as isize
 3912                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3913                                    - selection.start as isize,
 3914                        );
 3915                        old_range.clone()
 3916                    } else {
 3917                        s.start..s.end
 3918                    }
 3919                }));
 3920                break;
 3921            }
 3922            if !self.linked_edit_ranges.is_empty() {
 3923                let start_anchor = snapshot.anchor_before(selection.head());
 3924                let end_anchor = snapshot.anchor_after(selection.tail());
 3925                if let Some(ranges) = self
 3926                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3927                {
 3928                    for (buffer, edits) in ranges {
 3929                        linked_edits.entry(buffer.clone()).or_default().extend(
 3930                            edits
 3931                                .into_iter()
 3932                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3933                        );
 3934                    }
 3935                }
 3936            }
 3937        }
 3938        let text = &text[common_prefix_len..];
 3939
 3940        cx.emit(EditorEvent::InputHandled {
 3941            utf16_range_to_replace: range_to_replace,
 3942            text: text.into(),
 3943        });
 3944
 3945        self.transact(cx, |this, cx| {
 3946            if let Some(mut snippet) = snippet {
 3947                snippet.text = text.to_string();
 3948                for tabstop in snippet
 3949                    .tabstops
 3950                    .iter_mut()
 3951                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3952                {
 3953                    tabstop.start -= common_prefix_len as isize;
 3954                    tabstop.end -= common_prefix_len as isize;
 3955                }
 3956
 3957                this.insert_snippet(&ranges, snippet, cx).log_err();
 3958            } else {
 3959                this.buffer.update(cx, |buffer, cx| {
 3960                    buffer.edit(
 3961                        ranges.iter().map(|range| (range.clone(), text)),
 3962                        this.autoindent_mode.clone(),
 3963                        cx,
 3964                    );
 3965                });
 3966            }
 3967            for (buffer, edits) in linked_edits {
 3968                buffer.update(cx, |buffer, cx| {
 3969                    let snapshot = buffer.snapshot();
 3970                    let edits = edits
 3971                        .into_iter()
 3972                        .map(|(range, text)| {
 3973                            use text::ToPoint as TP;
 3974                            let end_point = TP::to_point(&range.end, &snapshot);
 3975                            let start_point = TP::to_point(&range.start, &snapshot);
 3976                            (start_point..end_point, text)
 3977                        })
 3978                        .sorted_by_key(|(range, _)| range.start)
 3979                        .collect::<Vec<_>>();
 3980                    buffer.edit(edits, None, cx);
 3981                })
 3982            }
 3983
 3984            this.refresh_inline_completion(true, false, cx);
 3985        });
 3986
 3987        let show_new_completions_on_confirm = completion
 3988            .confirm
 3989            .as_ref()
 3990            .map_or(false, |confirm| confirm(intent, cx));
 3991        if show_new_completions_on_confirm {
 3992            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3993        }
 3994
 3995        let provider = self.completion_provider.as_ref()?;
 3996        drop(completion);
 3997        let apply_edits = provider.apply_additional_edits_for_completion(
 3998            buffer_handle,
 3999            completions_menu.completions.clone(),
 4000            candidate_id,
 4001            true,
 4002            cx,
 4003        );
 4004
 4005        let editor_settings = EditorSettings::get_global(cx);
 4006        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4007            // After the code completion is finished, users often want to know what signatures are needed.
 4008            // so we should automatically call signature_help
 4009            self.show_signature_help(&ShowSignatureHelp, cx);
 4010        }
 4011
 4012        Some(cx.foreground_executor().spawn(async move {
 4013            apply_edits.await?;
 4014            Ok(())
 4015        }))
 4016    }
 4017
 4018    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4019        let mut context_menu = self.context_menu.borrow_mut();
 4020        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4021            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4022                // Toggle if we're selecting the same one
 4023                *context_menu = None;
 4024                cx.notify();
 4025                return;
 4026            } else {
 4027                // Otherwise, clear it and start a new one
 4028                *context_menu = None;
 4029                cx.notify();
 4030            }
 4031        }
 4032        drop(context_menu);
 4033        let snapshot = self.snapshot(cx);
 4034        let deployed_from_indicator = action.deployed_from_indicator;
 4035        let mut task = self.code_actions_task.take();
 4036        let action = action.clone();
 4037        cx.spawn(|editor, mut cx| async move {
 4038            while let Some(prev_task) = task {
 4039                prev_task.await.log_err();
 4040                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4041            }
 4042
 4043            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4044                if editor.focus_handle.is_focused(cx) {
 4045                    let multibuffer_point = action
 4046                        .deployed_from_indicator
 4047                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4048                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4049                    let (buffer, buffer_row) = snapshot
 4050                        .buffer_snapshot
 4051                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4052                        .and_then(|(buffer_snapshot, range)| {
 4053                            editor
 4054                                .buffer
 4055                                .read(cx)
 4056                                .buffer(buffer_snapshot.remote_id())
 4057                                .map(|buffer| (buffer, range.start.row))
 4058                        })?;
 4059                    let (_, code_actions) = editor
 4060                        .available_code_actions
 4061                        .clone()
 4062                        .and_then(|(location, code_actions)| {
 4063                            let snapshot = location.buffer.read(cx).snapshot();
 4064                            let point_range = location.range.to_point(&snapshot);
 4065                            let point_range = point_range.start.row..=point_range.end.row;
 4066                            if point_range.contains(&buffer_row) {
 4067                                Some((location, code_actions))
 4068                            } else {
 4069                                None
 4070                            }
 4071                        })
 4072                        .unzip();
 4073                    let buffer_id = buffer.read(cx).remote_id();
 4074                    let tasks = editor
 4075                        .tasks
 4076                        .get(&(buffer_id, buffer_row))
 4077                        .map(|t| Arc::new(t.to_owned()));
 4078                    if tasks.is_none() && code_actions.is_none() {
 4079                        return None;
 4080                    }
 4081
 4082                    editor.completion_tasks.clear();
 4083                    editor.discard_inline_completion(false, cx);
 4084                    let task_context =
 4085                        tasks
 4086                            .as_ref()
 4087                            .zip(editor.project.clone())
 4088                            .map(|(tasks, project)| {
 4089                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4090                            });
 4091
 4092                    Some(cx.spawn(|editor, mut cx| async move {
 4093                        let task_context = match task_context {
 4094                            Some(task_context) => task_context.await,
 4095                            None => None,
 4096                        };
 4097                        let resolved_tasks =
 4098                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4099                                Rc::new(ResolvedTasks {
 4100                                    templates: tasks.resolve(&task_context).collect(),
 4101                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4102                                        multibuffer_point.row,
 4103                                        tasks.column,
 4104                                    )),
 4105                                })
 4106                            });
 4107                        let spawn_straight_away = resolved_tasks
 4108                            .as_ref()
 4109                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4110                            && code_actions
 4111                                .as_ref()
 4112                                .map_or(true, |actions| actions.is_empty());
 4113                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4114                            *editor.context_menu.borrow_mut() =
 4115                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4116                                    buffer,
 4117                                    actions: CodeActionContents {
 4118                                        tasks: resolved_tasks,
 4119                                        actions: code_actions,
 4120                                    },
 4121                                    selected_item: Default::default(),
 4122                                    scroll_handle: UniformListScrollHandle::default(),
 4123                                    deployed_from_indicator,
 4124                                }));
 4125                            if spawn_straight_away {
 4126                                if let Some(task) = editor.confirm_code_action(
 4127                                    &ConfirmCodeAction { item_ix: Some(0) },
 4128                                    cx,
 4129                                ) {
 4130                                    cx.notify();
 4131                                    return task;
 4132                                }
 4133                            }
 4134                            cx.notify();
 4135                            Task::ready(Ok(()))
 4136                        }) {
 4137                            task.await
 4138                        } else {
 4139                            Ok(())
 4140                        }
 4141                    }))
 4142                } else {
 4143                    Some(Task::ready(Ok(())))
 4144                }
 4145            })?;
 4146            if let Some(task) = spawned_test_task {
 4147                task.await?;
 4148            }
 4149
 4150            Ok::<_, anyhow::Error>(())
 4151        })
 4152        .detach_and_log_err(cx);
 4153    }
 4154
 4155    pub fn confirm_code_action(
 4156        &mut self,
 4157        action: &ConfirmCodeAction,
 4158        cx: &mut ViewContext<Self>,
 4159    ) -> Option<Task<Result<()>>> {
 4160        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4161            menu
 4162        } else {
 4163            return None;
 4164        };
 4165        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4166        let action = actions_menu.actions.get(action_ix)?;
 4167        let title = action.label();
 4168        let buffer = actions_menu.buffer;
 4169        let workspace = self.workspace()?;
 4170
 4171        match action {
 4172            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4173                workspace.update(cx, |workspace, cx| {
 4174                    workspace::tasks::schedule_resolved_task(
 4175                        workspace,
 4176                        task_source_kind,
 4177                        resolved_task,
 4178                        false,
 4179                        cx,
 4180                    );
 4181
 4182                    Some(Task::ready(Ok(())))
 4183                })
 4184            }
 4185            CodeActionsItem::CodeAction {
 4186                excerpt_id,
 4187                action,
 4188                provider,
 4189            } => {
 4190                let apply_code_action =
 4191                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4192                let workspace = workspace.downgrade();
 4193                Some(cx.spawn(|editor, cx| async move {
 4194                    let project_transaction = apply_code_action.await?;
 4195                    Self::open_project_transaction(
 4196                        &editor,
 4197                        workspace,
 4198                        project_transaction,
 4199                        title,
 4200                        cx,
 4201                    )
 4202                    .await
 4203                }))
 4204            }
 4205        }
 4206    }
 4207
 4208    pub async fn open_project_transaction(
 4209        this: &WeakView<Editor>,
 4210        workspace: WeakView<Workspace>,
 4211        transaction: ProjectTransaction,
 4212        title: String,
 4213        mut cx: AsyncWindowContext,
 4214    ) -> Result<()> {
 4215        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4216        cx.update(|cx| {
 4217            entries.sort_unstable_by_key(|(buffer, _)| {
 4218                buffer.read(cx).file().map(|f| f.path().clone())
 4219            });
 4220        })?;
 4221
 4222        // If the project transaction's edits are all contained within this editor, then
 4223        // avoid opening a new editor to display them.
 4224
 4225        if let Some((buffer, transaction)) = entries.first() {
 4226            if entries.len() == 1 {
 4227                let excerpt = this.update(&mut cx, |editor, cx| {
 4228                    editor
 4229                        .buffer()
 4230                        .read(cx)
 4231                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4232                })?;
 4233                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4234                    if excerpted_buffer == *buffer {
 4235                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4236                            let excerpt_range = excerpt_range.to_offset(buffer);
 4237                            buffer
 4238                                .edited_ranges_for_transaction::<usize>(transaction)
 4239                                .all(|range| {
 4240                                    excerpt_range.start <= range.start
 4241                                        && excerpt_range.end >= range.end
 4242                                })
 4243                        })?;
 4244
 4245                        if all_edits_within_excerpt {
 4246                            return Ok(());
 4247                        }
 4248                    }
 4249                }
 4250            }
 4251        } else {
 4252            return Ok(());
 4253        }
 4254
 4255        let mut ranges_to_highlight = Vec::new();
 4256        let excerpt_buffer = cx.new_model(|cx| {
 4257            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4258            for (buffer_handle, transaction) in &entries {
 4259                let buffer = buffer_handle.read(cx);
 4260                ranges_to_highlight.extend(
 4261                    multibuffer.push_excerpts_with_context_lines(
 4262                        buffer_handle.clone(),
 4263                        buffer
 4264                            .edited_ranges_for_transaction::<usize>(transaction)
 4265                            .collect(),
 4266                        DEFAULT_MULTIBUFFER_CONTEXT,
 4267                        cx,
 4268                    ),
 4269                );
 4270            }
 4271            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4272            multibuffer
 4273        })?;
 4274
 4275        workspace.update(&mut cx, |workspace, cx| {
 4276            let project = workspace.project().clone();
 4277            let editor =
 4278                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4279            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4280            editor.update(cx, |editor, cx| {
 4281                editor.highlight_background::<Self>(
 4282                    &ranges_to_highlight,
 4283                    |theme| theme.editor_highlighted_line_background,
 4284                    cx,
 4285                );
 4286            });
 4287        })?;
 4288
 4289        Ok(())
 4290    }
 4291
 4292    pub fn clear_code_action_providers(&mut self) {
 4293        self.code_action_providers.clear();
 4294        self.available_code_actions.take();
 4295    }
 4296
 4297    pub fn push_code_action_provider(
 4298        &mut self,
 4299        provider: Rc<dyn CodeActionProvider>,
 4300        cx: &mut ViewContext<Self>,
 4301    ) {
 4302        self.code_action_providers.push(provider);
 4303        self.refresh_code_actions(cx);
 4304    }
 4305
 4306    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4307        let buffer = self.buffer.read(cx);
 4308        let newest_selection = self.selections.newest_anchor().clone();
 4309        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4310        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4311        if start_buffer != end_buffer {
 4312            return None;
 4313        }
 4314
 4315        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4316            cx.background_executor()
 4317                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4318                .await;
 4319
 4320            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4321                let providers = this.code_action_providers.clone();
 4322                let tasks = this
 4323                    .code_action_providers
 4324                    .iter()
 4325                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4326                    .collect::<Vec<_>>();
 4327                (providers, tasks)
 4328            })?;
 4329
 4330            let mut actions = Vec::new();
 4331            for (provider, provider_actions) in
 4332                providers.into_iter().zip(future::join_all(tasks).await)
 4333            {
 4334                if let Some(provider_actions) = provider_actions.log_err() {
 4335                    actions.extend(provider_actions.into_iter().map(|action| {
 4336                        AvailableCodeAction {
 4337                            excerpt_id: newest_selection.start.excerpt_id,
 4338                            action,
 4339                            provider: provider.clone(),
 4340                        }
 4341                    }));
 4342                }
 4343            }
 4344
 4345            this.update(&mut cx, |this, cx| {
 4346                this.available_code_actions = if actions.is_empty() {
 4347                    None
 4348                } else {
 4349                    Some((
 4350                        Location {
 4351                            buffer: start_buffer,
 4352                            range: start..end,
 4353                        },
 4354                        actions.into(),
 4355                    ))
 4356                };
 4357                cx.notify();
 4358            })
 4359        }));
 4360        None
 4361    }
 4362
 4363    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4364        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4365            self.show_git_blame_inline = false;
 4366
 4367            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4368                cx.background_executor().timer(delay).await;
 4369
 4370                this.update(&mut cx, |this, cx| {
 4371                    this.show_git_blame_inline = true;
 4372                    cx.notify();
 4373                })
 4374                .log_err();
 4375            }));
 4376        }
 4377    }
 4378
 4379    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4380        if self.pending_rename.is_some() {
 4381            return None;
 4382        }
 4383
 4384        let provider = self.semantics_provider.clone()?;
 4385        let buffer = self.buffer.read(cx);
 4386        let newest_selection = self.selections.newest_anchor().clone();
 4387        let cursor_position = newest_selection.head();
 4388        let (cursor_buffer, cursor_buffer_position) =
 4389            buffer.text_anchor_for_position(cursor_position, cx)?;
 4390        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4391        if cursor_buffer != tail_buffer {
 4392            return None;
 4393        }
 4394        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4395        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4396            cx.background_executor()
 4397                .timer(Duration::from_millis(debounce))
 4398                .await;
 4399
 4400            let highlights = if let Some(highlights) = cx
 4401                .update(|cx| {
 4402                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4403                })
 4404                .ok()
 4405                .flatten()
 4406            {
 4407                highlights.await.log_err()
 4408            } else {
 4409                None
 4410            };
 4411
 4412            if let Some(highlights) = highlights {
 4413                this.update(&mut cx, |this, cx| {
 4414                    if this.pending_rename.is_some() {
 4415                        return;
 4416                    }
 4417
 4418                    let buffer_id = cursor_position.buffer_id;
 4419                    let buffer = this.buffer.read(cx);
 4420                    if !buffer
 4421                        .text_anchor_for_position(cursor_position, cx)
 4422                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4423                    {
 4424                        return;
 4425                    }
 4426
 4427                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4428                    let mut write_ranges = Vec::new();
 4429                    let mut read_ranges = Vec::new();
 4430                    for highlight in highlights {
 4431                        for (excerpt_id, excerpt_range) in
 4432                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4433                        {
 4434                            let start = highlight
 4435                                .range
 4436                                .start
 4437                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4438                            let end = highlight
 4439                                .range
 4440                                .end
 4441                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4442                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4443                                continue;
 4444                            }
 4445
 4446                            let range = Anchor {
 4447                                buffer_id,
 4448                                excerpt_id,
 4449                                text_anchor: start,
 4450                            }..Anchor {
 4451                                buffer_id,
 4452                                excerpt_id,
 4453                                text_anchor: end,
 4454                            };
 4455                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4456                                write_ranges.push(range);
 4457                            } else {
 4458                                read_ranges.push(range);
 4459                            }
 4460                        }
 4461                    }
 4462
 4463                    this.highlight_background::<DocumentHighlightRead>(
 4464                        &read_ranges,
 4465                        |theme| theme.editor_document_highlight_read_background,
 4466                        cx,
 4467                    );
 4468                    this.highlight_background::<DocumentHighlightWrite>(
 4469                        &write_ranges,
 4470                        |theme| theme.editor_document_highlight_write_background,
 4471                        cx,
 4472                    );
 4473                    cx.notify();
 4474                })
 4475                .log_err();
 4476            }
 4477        }));
 4478        None
 4479    }
 4480
 4481    pub fn refresh_inline_completion(
 4482        &mut self,
 4483        debounce: bool,
 4484        user_requested: bool,
 4485        cx: &mut ViewContext<Self>,
 4486    ) -> Option<()> {
 4487        let provider = self.inline_completion_provider()?;
 4488        let cursor = self.selections.newest_anchor().head();
 4489        let (buffer, cursor_buffer_position) =
 4490            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4491
 4492        if !user_requested
 4493            && (!self.enable_inline_completions
 4494                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4495                || !self.is_focused(cx))
 4496        {
 4497            self.discard_inline_completion(false, cx);
 4498            return None;
 4499        }
 4500
 4501        self.update_visible_inline_completion(cx);
 4502        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4503        Some(())
 4504    }
 4505
 4506    fn cycle_inline_completion(
 4507        &mut self,
 4508        direction: Direction,
 4509        cx: &mut ViewContext<Self>,
 4510    ) -> Option<()> {
 4511        let provider = self.inline_completion_provider()?;
 4512        let cursor = self.selections.newest_anchor().head();
 4513        let (buffer, cursor_buffer_position) =
 4514            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4515        if !self.enable_inline_completions
 4516            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4517        {
 4518            return None;
 4519        }
 4520
 4521        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4522        self.update_visible_inline_completion(cx);
 4523
 4524        Some(())
 4525    }
 4526
 4527    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4528        if !self.has_active_inline_completion() {
 4529            self.refresh_inline_completion(false, true, cx);
 4530            return;
 4531        }
 4532
 4533        self.update_visible_inline_completion(cx);
 4534    }
 4535
 4536    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4537        self.show_cursor_names(cx);
 4538    }
 4539
 4540    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4541        self.show_cursor_names = true;
 4542        cx.notify();
 4543        cx.spawn(|this, mut cx| async move {
 4544            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4545            this.update(&mut cx, |this, cx| {
 4546                this.show_cursor_names = false;
 4547                cx.notify()
 4548            })
 4549            .ok()
 4550        })
 4551        .detach();
 4552    }
 4553
 4554    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4555        if self.has_active_inline_completion() {
 4556            self.cycle_inline_completion(Direction::Next, cx);
 4557        } else {
 4558            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4559            if is_copilot_disabled {
 4560                cx.propagate();
 4561            }
 4562        }
 4563    }
 4564
 4565    pub fn previous_inline_completion(
 4566        &mut self,
 4567        _: &PreviousInlineCompletion,
 4568        cx: &mut ViewContext<Self>,
 4569    ) {
 4570        if self.has_active_inline_completion() {
 4571            self.cycle_inline_completion(Direction::Prev, cx);
 4572        } else {
 4573            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4574            if is_copilot_disabled {
 4575                cx.propagate();
 4576            }
 4577        }
 4578    }
 4579
 4580    pub fn accept_inline_completion(
 4581        &mut self,
 4582        _: &AcceptInlineCompletion,
 4583        cx: &mut ViewContext<Self>,
 4584    ) {
 4585        let buffer = self.buffer.read(cx);
 4586        let snapshot = buffer.snapshot(cx);
 4587        let selection = self.selections.newest_adjusted(cx);
 4588        let cursor = selection.head();
 4589        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4590        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4591        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4592        {
 4593            if cursor.column < suggested_indent.len
 4594                && cursor.column <= current_indent.len
 4595                && current_indent.len <= suggested_indent.len
 4596            {
 4597                self.tab(&Default::default(), cx);
 4598                return;
 4599            }
 4600        }
 4601
 4602        if self.show_inline_completions_in_menu(cx) {
 4603            self.hide_context_menu(cx);
 4604        }
 4605
 4606        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4607            return;
 4608        };
 4609
 4610        self.report_inline_completion_event(true, cx);
 4611
 4612        match &active_inline_completion.completion {
 4613            InlineCompletion::Move(position) => {
 4614                let position = *position;
 4615                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4616                    selections.select_anchor_ranges([position..position]);
 4617                });
 4618            }
 4619            InlineCompletion::Edit(edits) => {
 4620                if let Some(provider) = self.inline_completion_provider() {
 4621                    provider.accept(cx);
 4622                }
 4623
 4624                let snapshot = self.buffer.read(cx).snapshot(cx);
 4625                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4626
 4627                self.buffer.update(cx, |buffer, cx| {
 4628                    buffer.edit(edits.iter().cloned(), None, cx)
 4629                });
 4630
 4631                self.change_selections(None, cx, |s| {
 4632                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4633                });
 4634
 4635                self.update_visible_inline_completion(cx);
 4636                if self.active_inline_completion.is_none() {
 4637                    self.refresh_inline_completion(true, true, cx);
 4638                }
 4639
 4640                cx.notify();
 4641            }
 4642        }
 4643    }
 4644
 4645    pub fn accept_partial_inline_completion(
 4646        &mut self,
 4647        _: &AcceptPartialInlineCompletion,
 4648        cx: &mut ViewContext<Self>,
 4649    ) {
 4650        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4651            return;
 4652        };
 4653        if self.selections.count() != 1 {
 4654            return;
 4655        }
 4656
 4657        self.report_inline_completion_event(true, cx);
 4658
 4659        match &active_inline_completion.completion {
 4660            InlineCompletion::Move(position) => {
 4661                let position = *position;
 4662                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4663                    selections.select_anchor_ranges([position..position]);
 4664                });
 4665            }
 4666            InlineCompletion::Edit(edits) => {
 4667                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4668                    let text = edits[0].1.as_str();
 4669                    let mut partial_completion = text
 4670                        .chars()
 4671                        .by_ref()
 4672                        .take_while(|c| c.is_alphabetic())
 4673                        .collect::<String>();
 4674                    if partial_completion.is_empty() {
 4675                        partial_completion = text
 4676                            .chars()
 4677                            .by_ref()
 4678                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4679                            .collect::<String>();
 4680                    }
 4681
 4682                    cx.emit(EditorEvent::InputHandled {
 4683                        utf16_range_to_replace: None,
 4684                        text: partial_completion.clone().into(),
 4685                    });
 4686
 4687                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4688
 4689                    self.refresh_inline_completion(true, true, cx);
 4690                    cx.notify();
 4691                }
 4692            }
 4693        }
 4694    }
 4695
 4696    fn discard_inline_completion(
 4697        &mut self,
 4698        should_report_inline_completion_event: bool,
 4699        cx: &mut ViewContext<Self>,
 4700    ) -> bool {
 4701        if should_report_inline_completion_event {
 4702            self.report_inline_completion_event(false, cx);
 4703        }
 4704
 4705        if let Some(provider) = self.inline_completion_provider() {
 4706            provider.discard(cx);
 4707        }
 4708
 4709        self.take_active_inline_completion(cx).is_some()
 4710    }
 4711
 4712    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4713        let Some(provider) = self.inline_completion_provider() else {
 4714            return;
 4715        };
 4716        let Some(project) = self.project.as_ref() else {
 4717            return;
 4718        };
 4719        let Some((_, buffer, _)) = self
 4720            .buffer
 4721            .read(cx)
 4722            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4723        else {
 4724            return;
 4725        };
 4726
 4727        let project = project.read(cx);
 4728        let extension = buffer
 4729            .read(cx)
 4730            .file()
 4731            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4732        project.client().telemetry().report_inline_completion_event(
 4733            provider.name().into(),
 4734            accepted,
 4735            extension,
 4736        );
 4737    }
 4738
 4739    pub fn has_active_inline_completion(&self) -> bool {
 4740        self.active_inline_completion.is_some()
 4741    }
 4742
 4743    fn take_active_inline_completion(
 4744        &mut self,
 4745        cx: &mut ViewContext<Self>,
 4746    ) -> Option<InlineCompletion> {
 4747        let active_inline_completion = self.active_inline_completion.take()?;
 4748        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4749        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4750        Some(active_inline_completion.completion)
 4751    }
 4752
 4753    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4754        let selection = self.selections.newest_anchor();
 4755        let cursor = selection.head();
 4756        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4757        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4758        let excerpt_id = cursor.excerpt_id;
 4759
 4760        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 4761            && (self.context_menu.borrow().is_some()
 4762                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 4763        if completions_menu_has_precedence
 4764            || !offset_selection.is_empty()
 4765            || self
 4766                .active_inline_completion
 4767                .as_ref()
 4768                .map_or(false, |completion| {
 4769                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4770                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4771                    !invalidation_range.contains(&offset_selection.head())
 4772                })
 4773        {
 4774            self.discard_inline_completion(false, cx);
 4775            return None;
 4776        }
 4777
 4778        self.take_active_inline_completion(cx);
 4779        let provider = self.inline_completion_provider()?;
 4780
 4781        let (buffer, cursor_buffer_position) =
 4782            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4783
 4784        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4785        let edits = completion
 4786            .edits
 4787            .into_iter()
 4788            .flat_map(|(range, new_text)| {
 4789                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4790                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4791                Some((start..end, new_text))
 4792            })
 4793            .collect::<Vec<_>>();
 4794        if edits.is_empty() {
 4795            return None;
 4796        }
 4797
 4798        let first_edit_start = edits.first().unwrap().0.start;
 4799        let edit_start_row = first_edit_start
 4800            .to_point(&multibuffer)
 4801            .row
 4802            .saturating_sub(2);
 4803
 4804        let last_edit_end = edits.last().unwrap().0.end;
 4805        let edit_end_row = cmp::min(
 4806            multibuffer.max_point().row,
 4807            last_edit_end.to_point(&multibuffer).row + 2,
 4808        );
 4809
 4810        let cursor_row = cursor.to_point(&multibuffer).row;
 4811
 4812        let mut inlay_ids = Vec::new();
 4813        let invalidation_row_range;
 4814        let completion;
 4815        if cursor_row < edit_start_row {
 4816            invalidation_row_range = cursor_row..edit_end_row;
 4817            completion = InlineCompletion::Move(first_edit_start);
 4818        } else if cursor_row > edit_end_row {
 4819            invalidation_row_range = edit_start_row..cursor_row;
 4820            completion = InlineCompletion::Move(first_edit_start);
 4821        } else {
 4822            if edits
 4823                .iter()
 4824                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4825            {
 4826                let mut inlays = Vec::new();
 4827                for (range, new_text) in &edits {
 4828                    let inlay = Inlay::inline_completion(
 4829                        post_inc(&mut self.next_inlay_id),
 4830                        range.start,
 4831                        new_text.as_str(),
 4832                    );
 4833                    inlay_ids.push(inlay.id);
 4834                    inlays.push(inlay);
 4835                }
 4836
 4837                self.splice_inlays(vec![], inlays, cx);
 4838            } else {
 4839                let background_color = cx.theme().status().deleted_background;
 4840                self.highlight_text::<InlineCompletionHighlight>(
 4841                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4842                    HighlightStyle {
 4843                        background_color: Some(background_color),
 4844                        ..Default::default()
 4845                    },
 4846                    cx,
 4847                );
 4848            }
 4849
 4850            invalidation_row_range = edit_start_row..edit_end_row;
 4851            completion = InlineCompletion::Edit(edits);
 4852        };
 4853
 4854        let invalidation_range = multibuffer
 4855            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4856            ..multibuffer.anchor_after(Point::new(
 4857                invalidation_row_range.end,
 4858                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4859            ));
 4860
 4861        self.active_inline_completion = Some(InlineCompletionState {
 4862            inlay_ids,
 4863            completion,
 4864            invalidation_range,
 4865        });
 4866
 4867        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 4868            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4869                match self.context_menu.borrow_mut().as_mut() {
 4870                    Some(CodeContextMenu::Completions(menu)) => {
 4871                        menu.show_inline_completion_hint(hint);
 4872                    }
 4873                    _ => {}
 4874                }
 4875            }
 4876        }
 4877
 4878        cx.notify();
 4879
 4880        Some(())
 4881    }
 4882
 4883    fn inline_completion_menu_hint(
 4884        &mut self,
 4885        cx: &mut ViewContext<Self>,
 4886    ) -> Option<InlineCompletionMenuHint> {
 4887        if self.has_active_inline_completion() {
 4888            let provider_name = self.inline_completion_provider()?.display_name();
 4889            let editor_snapshot = self.snapshot(cx);
 4890
 4891            let text = match &self.active_inline_completion.as_ref()?.completion {
 4892                InlineCompletion::Edit(edits) => {
 4893                    inline_completion_edit_text(&editor_snapshot, edits, true, cx)
 4894                }
 4895                InlineCompletion::Move(target) => {
 4896                    let target_point =
 4897                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4898                    let target_line = target_point.row + 1;
 4899                    InlineCompletionText::Move(
 4900                        format!("Jump to edit in line {}", target_line).into(),
 4901                    )
 4902                }
 4903            };
 4904
 4905            Some(InlineCompletionMenuHint {
 4906                provider_name,
 4907                text,
 4908            })
 4909        } else {
 4910            None
 4911        }
 4912    }
 4913
 4914    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4915        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4916    }
 4917
 4918    fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
 4919        EditorSettings::get_global(cx).show_inline_completions_in_menu
 4920            && self
 4921                .inline_completion_provider()
 4922                .map_or(false, |provider| provider.show_completions_in_menu())
 4923    }
 4924
 4925    fn render_code_actions_indicator(
 4926        &self,
 4927        _style: &EditorStyle,
 4928        row: DisplayRow,
 4929        is_active: bool,
 4930        cx: &mut ViewContext<Self>,
 4931    ) -> Option<IconButton> {
 4932        if self.available_code_actions.is_some() {
 4933            Some(
 4934                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4935                    .shape(ui::IconButtonShape::Square)
 4936                    .icon_size(IconSize::XSmall)
 4937                    .icon_color(Color::Muted)
 4938                    .toggle_state(is_active)
 4939                    .tooltip({
 4940                        let focus_handle = self.focus_handle.clone();
 4941                        move |cx| {
 4942                            Tooltip::for_action_in(
 4943                                "Toggle Code Actions",
 4944                                &ToggleCodeActions {
 4945                                    deployed_from_indicator: None,
 4946                                },
 4947                                &focus_handle,
 4948                                cx,
 4949                            )
 4950                        }
 4951                    })
 4952                    .on_click(cx.listener(move |editor, _e, cx| {
 4953                        editor.focus(cx);
 4954                        editor.toggle_code_actions(
 4955                            &ToggleCodeActions {
 4956                                deployed_from_indicator: Some(row),
 4957                            },
 4958                            cx,
 4959                        );
 4960                    })),
 4961            )
 4962        } else {
 4963            None
 4964        }
 4965    }
 4966
 4967    fn clear_tasks(&mut self) {
 4968        self.tasks.clear()
 4969    }
 4970
 4971    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4972        if self.tasks.insert(key, value).is_some() {
 4973            // This case should hopefully be rare, but just in case...
 4974            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4975        }
 4976    }
 4977
 4978    fn build_tasks_context(
 4979        project: &Model<Project>,
 4980        buffer: &Model<Buffer>,
 4981        buffer_row: u32,
 4982        tasks: &Arc<RunnableTasks>,
 4983        cx: &mut ViewContext<Self>,
 4984    ) -> Task<Option<task::TaskContext>> {
 4985        let position = Point::new(buffer_row, tasks.column);
 4986        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4987        let location = Location {
 4988            buffer: buffer.clone(),
 4989            range: range_start..range_start,
 4990        };
 4991        // Fill in the environmental variables from the tree-sitter captures
 4992        let mut captured_task_variables = TaskVariables::default();
 4993        for (capture_name, value) in tasks.extra_variables.clone() {
 4994            captured_task_variables.insert(
 4995                task::VariableName::Custom(capture_name.into()),
 4996                value.clone(),
 4997            );
 4998        }
 4999        project.update(cx, |project, cx| {
 5000            project.task_store().update(cx, |task_store, cx| {
 5001                task_store.task_context_for_location(captured_task_variables, location, cx)
 5002            })
 5003        })
 5004    }
 5005
 5006    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5007        let Some((workspace, _)) = self.workspace.clone() else {
 5008            return;
 5009        };
 5010        let Some(project) = self.project.clone() else {
 5011            return;
 5012        };
 5013
 5014        // Try to find a closest, enclosing node using tree-sitter that has a
 5015        // task
 5016        let Some((buffer, buffer_row, tasks)) = self
 5017            .find_enclosing_node_task(cx)
 5018            // Or find the task that's closest in row-distance.
 5019            .or_else(|| self.find_closest_task(cx))
 5020        else {
 5021            return;
 5022        };
 5023
 5024        let reveal_strategy = action.reveal;
 5025        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5026        cx.spawn(|_, mut cx| async move {
 5027            let context = task_context.await?;
 5028            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5029
 5030            let resolved = resolved_task.resolved.as_mut()?;
 5031            resolved.reveal = reveal_strategy;
 5032
 5033            workspace
 5034                .update(&mut cx, |workspace, cx| {
 5035                    workspace::tasks::schedule_resolved_task(
 5036                        workspace,
 5037                        task_source_kind,
 5038                        resolved_task,
 5039                        false,
 5040                        cx,
 5041                    );
 5042                })
 5043                .ok()
 5044        })
 5045        .detach();
 5046    }
 5047
 5048    fn find_closest_task(
 5049        &mut self,
 5050        cx: &mut ViewContext<Self>,
 5051    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5052        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5053
 5054        let ((buffer_id, row), tasks) = self
 5055            .tasks
 5056            .iter()
 5057            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5058
 5059        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5060        let tasks = Arc::new(tasks.to_owned());
 5061        Some((buffer, *row, tasks))
 5062    }
 5063
 5064    fn find_enclosing_node_task(
 5065        &mut self,
 5066        cx: &mut ViewContext<Self>,
 5067    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5068        let snapshot = self.buffer.read(cx).snapshot(cx);
 5069        let offset = self.selections.newest::<usize>(cx).head();
 5070        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5071        let buffer_id = excerpt.buffer().remote_id();
 5072
 5073        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5074        let mut cursor = layer.node().walk();
 5075
 5076        while cursor.goto_first_child_for_byte(offset).is_some() {
 5077            if cursor.node().end_byte() == offset {
 5078                cursor.goto_next_sibling();
 5079            }
 5080        }
 5081
 5082        // Ascend to the smallest ancestor that contains the range and has a task.
 5083        loop {
 5084            let node = cursor.node();
 5085            let node_range = node.byte_range();
 5086            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5087
 5088            // Check if this node contains our offset
 5089            if node_range.start <= offset && node_range.end >= offset {
 5090                // If it contains offset, check for task
 5091                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5092                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5093                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5094                }
 5095            }
 5096
 5097            if !cursor.goto_parent() {
 5098                break;
 5099            }
 5100        }
 5101        None
 5102    }
 5103
 5104    fn render_run_indicator(
 5105        &self,
 5106        _style: &EditorStyle,
 5107        is_active: bool,
 5108        row: DisplayRow,
 5109        cx: &mut ViewContext<Self>,
 5110    ) -> IconButton {
 5111        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5112            .shape(ui::IconButtonShape::Square)
 5113            .icon_size(IconSize::XSmall)
 5114            .icon_color(Color::Muted)
 5115            .toggle_state(is_active)
 5116            .on_click(cx.listener(move |editor, _e, cx| {
 5117                editor.focus(cx);
 5118                editor.toggle_code_actions(
 5119                    &ToggleCodeActions {
 5120                        deployed_from_indicator: Some(row),
 5121                    },
 5122                    cx,
 5123                );
 5124            }))
 5125    }
 5126
 5127    #[cfg(any(feature = "test-support", test))]
 5128    pub fn context_menu_visible(&self) -> bool {
 5129        self.context_menu
 5130            .borrow()
 5131            .as_ref()
 5132            .map_or(false, |menu| menu.visible())
 5133    }
 5134
 5135    #[cfg(feature = "test-support")]
 5136    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5137        self.context_menu
 5138            .borrow()
 5139            .as_ref()
 5140            .map_or(false, |menu| match menu {
 5141                CodeContextMenu::Completions(menu) => {
 5142                    menu.entries.borrow().first().map_or(false, |entry| {
 5143                        matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5144                    })
 5145                }
 5146                CodeContextMenu::CodeActions(_) => false,
 5147            })
 5148    }
 5149
 5150    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5151        self.context_menu
 5152            .borrow()
 5153            .as_ref()
 5154            .map(|menu| menu.origin(cursor_position))
 5155    }
 5156
 5157    fn render_context_menu(
 5158        &self,
 5159        style: &EditorStyle,
 5160        max_height_in_lines: u32,
 5161        cx: &mut ViewContext<Editor>,
 5162    ) -> Option<AnyElement> {
 5163        self.context_menu.borrow().as_ref().and_then(|menu| {
 5164            if menu.visible() {
 5165                Some(menu.render(style, max_height_in_lines, cx))
 5166            } else {
 5167                None
 5168            }
 5169        })
 5170    }
 5171
 5172    fn render_context_menu_aside(
 5173        &self,
 5174        style: &EditorStyle,
 5175        max_size: Size<Pixels>,
 5176        cx: &mut ViewContext<Editor>,
 5177    ) -> Option<AnyElement> {
 5178        self.context_menu.borrow().as_ref().and_then(|menu| {
 5179            if menu.visible() {
 5180                menu.render_aside(
 5181                    style,
 5182                    max_size,
 5183                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5184                    cx,
 5185                )
 5186            } else {
 5187                None
 5188            }
 5189        })
 5190    }
 5191
 5192    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5193        cx.notify();
 5194        self.completion_tasks.clear();
 5195        let context_menu = self.context_menu.borrow_mut().take();
 5196        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5197            self.update_visible_inline_completion(cx);
 5198        }
 5199        context_menu
 5200    }
 5201
 5202    fn show_snippet_choices(
 5203        &mut self,
 5204        choices: &Vec<String>,
 5205        selection: Range<Anchor>,
 5206        cx: &mut ViewContext<Self>,
 5207    ) {
 5208        if selection.start.buffer_id.is_none() {
 5209            return;
 5210        }
 5211        let buffer_id = selection.start.buffer_id.unwrap();
 5212        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5213        let id = post_inc(&mut self.next_completion_id);
 5214
 5215        if let Some(buffer) = buffer {
 5216            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5217                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5218            ));
 5219        }
 5220    }
 5221
 5222    pub fn insert_snippet(
 5223        &mut self,
 5224        insertion_ranges: &[Range<usize>],
 5225        snippet: Snippet,
 5226        cx: &mut ViewContext<Self>,
 5227    ) -> Result<()> {
 5228        struct Tabstop<T> {
 5229            is_end_tabstop: bool,
 5230            ranges: Vec<Range<T>>,
 5231            choices: Option<Vec<String>>,
 5232        }
 5233
 5234        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5235            let snippet_text: Arc<str> = snippet.text.clone().into();
 5236            buffer.edit(
 5237                insertion_ranges
 5238                    .iter()
 5239                    .cloned()
 5240                    .map(|range| (range, snippet_text.clone())),
 5241                Some(AutoindentMode::EachLine),
 5242                cx,
 5243            );
 5244
 5245            let snapshot = &*buffer.read(cx);
 5246            let snippet = &snippet;
 5247            snippet
 5248                .tabstops
 5249                .iter()
 5250                .map(|tabstop| {
 5251                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5252                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5253                    });
 5254                    let mut tabstop_ranges = tabstop
 5255                        .ranges
 5256                        .iter()
 5257                        .flat_map(|tabstop_range| {
 5258                            let mut delta = 0_isize;
 5259                            insertion_ranges.iter().map(move |insertion_range| {
 5260                                let insertion_start = insertion_range.start as isize + delta;
 5261                                delta +=
 5262                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5263
 5264                                let start = ((insertion_start + tabstop_range.start) as usize)
 5265                                    .min(snapshot.len());
 5266                                let end = ((insertion_start + tabstop_range.end) as usize)
 5267                                    .min(snapshot.len());
 5268                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5269                            })
 5270                        })
 5271                        .collect::<Vec<_>>();
 5272                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5273
 5274                    Tabstop {
 5275                        is_end_tabstop,
 5276                        ranges: tabstop_ranges,
 5277                        choices: tabstop.choices.clone(),
 5278                    }
 5279                })
 5280                .collect::<Vec<_>>()
 5281        });
 5282        if let Some(tabstop) = tabstops.first() {
 5283            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5284                s.select_ranges(tabstop.ranges.iter().cloned());
 5285            });
 5286
 5287            if let Some(choices) = &tabstop.choices {
 5288                if let Some(selection) = tabstop.ranges.first() {
 5289                    self.show_snippet_choices(choices, selection.clone(), cx)
 5290                }
 5291            }
 5292
 5293            // If we're already at the last tabstop and it's at the end of the snippet,
 5294            // we're done, we don't need to keep the state around.
 5295            if !tabstop.is_end_tabstop {
 5296                let choices = tabstops
 5297                    .iter()
 5298                    .map(|tabstop| tabstop.choices.clone())
 5299                    .collect();
 5300
 5301                let ranges = tabstops
 5302                    .into_iter()
 5303                    .map(|tabstop| tabstop.ranges)
 5304                    .collect::<Vec<_>>();
 5305
 5306                self.snippet_stack.push(SnippetState {
 5307                    active_index: 0,
 5308                    ranges,
 5309                    choices,
 5310                });
 5311            }
 5312
 5313            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5314            if self.autoclose_regions.is_empty() {
 5315                let snapshot = self.buffer.read(cx).snapshot(cx);
 5316                for selection in &mut self.selections.all::<Point>(cx) {
 5317                    let selection_head = selection.head();
 5318                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5319                        continue;
 5320                    };
 5321
 5322                    let mut bracket_pair = None;
 5323                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5324                    let prev_chars = snapshot
 5325                        .reversed_chars_at(selection_head)
 5326                        .collect::<String>();
 5327                    for (pair, enabled) in scope.brackets() {
 5328                        if enabled
 5329                            && pair.close
 5330                            && prev_chars.starts_with(pair.start.as_str())
 5331                            && next_chars.starts_with(pair.end.as_str())
 5332                        {
 5333                            bracket_pair = Some(pair.clone());
 5334                            break;
 5335                        }
 5336                    }
 5337                    if let Some(pair) = bracket_pair {
 5338                        let start = snapshot.anchor_after(selection_head);
 5339                        let end = snapshot.anchor_after(selection_head);
 5340                        self.autoclose_regions.push(AutocloseRegion {
 5341                            selection_id: selection.id,
 5342                            range: start..end,
 5343                            pair,
 5344                        });
 5345                    }
 5346                }
 5347            }
 5348        }
 5349        Ok(())
 5350    }
 5351
 5352    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5353        self.move_to_snippet_tabstop(Bias::Right, cx)
 5354    }
 5355
 5356    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5357        self.move_to_snippet_tabstop(Bias::Left, cx)
 5358    }
 5359
 5360    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5361        if let Some(mut snippet) = self.snippet_stack.pop() {
 5362            match bias {
 5363                Bias::Left => {
 5364                    if snippet.active_index > 0 {
 5365                        snippet.active_index -= 1;
 5366                    } else {
 5367                        self.snippet_stack.push(snippet);
 5368                        return false;
 5369                    }
 5370                }
 5371                Bias::Right => {
 5372                    if snippet.active_index + 1 < snippet.ranges.len() {
 5373                        snippet.active_index += 1;
 5374                    } else {
 5375                        self.snippet_stack.push(snippet);
 5376                        return false;
 5377                    }
 5378                }
 5379            }
 5380            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5381                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5382                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5383                });
 5384
 5385                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5386                    if let Some(selection) = current_ranges.first() {
 5387                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5388                    }
 5389                }
 5390
 5391                // If snippet state is not at the last tabstop, push it back on the stack
 5392                if snippet.active_index + 1 < snippet.ranges.len() {
 5393                    self.snippet_stack.push(snippet);
 5394                }
 5395                return true;
 5396            }
 5397        }
 5398
 5399        false
 5400    }
 5401
 5402    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5403        self.transact(cx, |this, cx| {
 5404            this.select_all(&SelectAll, cx);
 5405            this.insert("", cx);
 5406        });
 5407    }
 5408
 5409    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5410        self.transact(cx, |this, cx| {
 5411            this.select_autoclose_pair(cx);
 5412            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5413            if !this.linked_edit_ranges.is_empty() {
 5414                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5415                let snapshot = this.buffer.read(cx).snapshot(cx);
 5416
 5417                for selection in selections.iter() {
 5418                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5419                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5420                    if selection_start.buffer_id != selection_end.buffer_id {
 5421                        continue;
 5422                    }
 5423                    if let Some(ranges) =
 5424                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5425                    {
 5426                        for (buffer, entries) in ranges {
 5427                            linked_ranges.entry(buffer).or_default().extend(entries);
 5428                        }
 5429                    }
 5430                }
 5431            }
 5432
 5433            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5434            if !this.selections.line_mode {
 5435                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5436                for selection in &mut selections {
 5437                    if selection.is_empty() {
 5438                        let old_head = selection.head();
 5439                        let mut new_head =
 5440                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5441                                .to_point(&display_map);
 5442                        if let Some((buffer, line_buffer_range)) = display_map
 5443                            .buffer_snapshot
 5444                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5445                        {
 5446                            let indent_size =
 5447                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5448                            let indent_len = match indent_size.kind {
 5449                                IndentKind::Space => {
 5450                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5451                                }
 5452                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5453                            };
 5454                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5455                                let indent_len = indent_len.get();
 5456                                new_head = cmp::min(
 5457                                    new_head,
 5458                                    MultiBufferPoint::new(
 5459                                        old_head.row,
 5460                                        ((old_head.column - 1) / indent_len) * indent_len,
 5461                                    ),
 5462                                );
 5463                            }
 5464                        }
 5465
 5466                        selection.set_head(new_head, SelectionGoal::None);
 5467                    }
 5468                }
 5469            }
 5470
 5471            this.signature_help_state.set_backspace_pressed(true);
 5472            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5473            this.insert("", cx);
 5474            let empty_str: Arc<str> = Arc::from("");
 5475            for (buffer, edits) in linked_ranges {
 5476                let snapshot = buffer.read(cx).snapshot();
 5477                use text::ToPoint as TP;
 5478
 5479                let edits = edits
 5480                    .into_iter()
 5481                    .map(|range| {
 5482                        let end_point = TP::to_point(&range.end, &snapshot);
 5483                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5484
 5485                        if end_point == start_point {
 5486                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5487                                .saturating_sub(1);
 5488                            start_point =
 5489                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5490                        };
 5491
 5492                        (start_point..end_point, empty_str.clone())
 5493                    })
 5494                    .sorted_by_key(|(range, _)| range.start)
 5495                    .collect::<Vec<_>>();
 5496                buffer.update(cx, |this, cx| {
 5497                    this.edit(edits, None, cx);
 5498                })
 5499            }
 5500            this.refresh_inline_completion(true, false, cx);
 5501            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5502        });
 5503    }
 5504
 5505    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5506        self.transact(cx, |this, cx| {
 5507            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5508                let line_mode = s.line_mode;
 5509                s.move_with(|map, selection| {
 5510                    if selection.is_empty() && !line_mode {
 5511                        let cursor = movement::right(map, selection.head());
 5512                        selection.end = cursor;
 5513                        selection.reversed = true;
 5514                        selection.goal = SelectionGoal::None;
 5515                    }
 5516                })
 5517            });
 5518            this.insert("", cx);
 5519            this.refresh_inline_completion(true, false, cx);
 5520        });
 5521    }
 5522
 5523    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5524        if self.move_to_prev_snippet_tabstop(cx) {
 5525            return;
 5526        }
 5527
 5528        self.outdent(&Outdent, cx);
 5529    }
 5530
 5531    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5532        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5533            return;
 5534        }
 5535
 5536        let mut selections = self.selections.all_adjusted(cx);
 5537        let buffer = self.buffer.read(cx);
 5538        let snapshot = buffer.snapshot(cx);
 5539        let rows_iter = selections.iter().map(|s| s.head().row);
 5540        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5541
 5542        let mut edits = Vec::new();
 5543        let mut prev_edited_row = 0;
 5544        let mut row_delta = 0;
 5545        for selection in &mut selections {
 5546            if selection.start.row != prev_edited_row {
 5547                row_delta = 0;
 5548            }
 5549            prev_edited_row = selection.end.row;
 5550
 5551            // If the selection is non-empty, then increase the indentation of the selected lines.
 5552            if !selection.is_empty() {
 5553                row_delta =
 5554                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5555                continue;
 5556            }
 5557
 5558            // If the selection is empty and the cursor is in the leading whitespace before the
 5559            // suggested indentation, then auto-indent the line.
 5560            let cursor = selection.head();
 5561            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5562            if let Some(suggested_indent) =
 5563                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5564            {
 5565                if cursor.column < suggested_indent.len
 5566                    && cursor.column <= current_indent.len
 5567                    && current_indent.len <= suggested_indent.len
 5568                {
 5569                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5570                    selection.end = selection.start;
 5571                    if row_delta == 0 {
 5572                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5573                            cursor.row,
 5574                            current_indent,
 5575                            suggested_indent,
 5576                        ));
 5577                        row_delta = suggested_indent.len - current_indent.len;
 5578                    }
 5579                    continue;
 5580                }
 5581            }
 5582
 5583            // Otherwise, insert a hard or soft tab.
 5584            let settings = buffer.settings_at(cursor, cx);
 5585            let tab_size = if settings.hard_tabs {
 5586                IndentSize::tab()
 5587            } else {
 5588                let tab_size = settings.tab_size.get();
 5589                let char_column = snapshot
 5590                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5591                    .flat_map(str::chars)
 5592                    .count()
 5593                    + row_delta as usize;
 5594                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5595                IndentSize::spaces(chars_to_next_tab_stop)
 5596            };
 5597            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5598            selection.end = selection.start;
 5599            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5600            row_delta += tab_size.len;
 5601        }
 5602
 5603        self.transact(cx, |this, cx| {
 5604            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5605            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5606            this.refresh_inline_completion(true, false, cx);
 5607        });
 5608    }
 5609
 5610    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5611        if self.read_only(cx) {
 5612            return;
 5613        }
 5614        let mut selections = self.selections.all::<Point>(cx);
 5615        let mut prev_edited_row = 0;
 5616        let mut row_delta = 0;
 5617        let mut edits = Vec::new();
 5618        let buffer = self.buffer.read(cx);
 5619        let snapshot = buffer.snapshot(cx);
 5620        for selection in &mut selections {
 5621            if selection.start.row != prev_edited_row {
 5622                row_delta = 0;
 5623            }
 5624            prev_edited_row = selection.end.row;
 5625
 5626            row_delta =
 5627                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5628        }
 5629
 5630        self.transact(cx, |this, cx| {
 5631            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5632            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5633        });
 5634    }
 5635
 5636    fn indent_selection(
 5637        buffer: &MultiBuffer,
 5638        snapshot: &MultiBufferSnapshot,
 5639        selection: &mut Selection<Point>,
 5640        edits: &mut Vec<(Range<Point>, String)>,
 5641        delta_for_start_row: u32,
 5642        cx: &AppContext,
 5643    ) -> u32 {
 5644        let settings = buffer.settings_at(selection.start, cx);
 5645        let tab_size = settings.tab_size.get();
 5646        let indent_kind = if settings.hard_tabs {
 5647            IndentKind::Tab
 5648        } else {
 5649            IndentKind::Space
 5650        };
 5651        let mut start_row = selection.start.row;
 5652        let mut end_row = selection.end.row + 1;
 5653
 5654        // If a selection ends at the beginning of a line, don't indent
 5655        // that last line.
 5656        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5657            end_row -= 1;
 5658        }
 5659
 5660        // Avoid re-indenting a row that has already been indented by a
 5661        // previous selection, but still update this selection's column
 5662        // to reflect that indentation.
 5663        if delta_for_start_row > 0 {
 5664            start_row += 1;
 5665            selection.start.column += delta_for_start_row;
 5666            if selection.end.row == selection.start.row {
 5667                selection.end.column += delta_for_start_row;
 5668            }
 5669        }
 5670
 5671        let mut delta_for_end_row = 0;
 5672        let has_multiple_rows = start_row + 1 != end_row;
 5673        for row in start_row..end_row {
 5674            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5675            let indent_delta = match (current_indent.kind, indent_kind) {
 5676                (IndentKind::Space, IndentKind::Space) => {
 5677                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5678                    IndentSize::spaces(columns_to_next_tab_stop)
 5679                }
 5680                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5681                (_, IndentKind::Tab) => IndentSize::tab(),
 5682            };
 5683
 5684            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5685                0
 5686            } else {
 5687                selection.start.column
 5688            };
 5689            let row_start = Point::new(row, start);
 5690            edits.push((
 5691                row_start..row_start,
 5692                indent_delta.chars().collect::<String>(),
 5693            ));
 5694
 5695            // Update this selection's endpoints to reflect the indentation.
 5696            if row == selection.start.row {
 5697                selection.start.column += indent_delta.len;
 5698            }
 5699            if row == selection.end.row {
 5700                selection.end.column += indent_delta.len;
 5701                delta_for_end_row = indent_delta.len;
 5702            }
 5703        }
 5704
 5705        if selection.start.row == selection.end.row {
 5706            delta_for_start_row + delta_for_end_row
 5707        } else {
 5708            delta_for_end_row
 5709        }
 5710    }
 5711
 5712    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5713        if self.read_only(cx) {
 5714            return;
 5715        }
 5716        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5717        let selections = self.selections.all::<Point>(cx);
 5718        let mut deletion_ranges = Vec::new();
 5719        let mut last_outdent = None;
 5720        {
 5721            let buffer = self.buffer.read(cx);
 5722            let snapshot = buffer.snapshot(cx);
 5723            for selection in &selections {
 5724                let settings = buffer.settings_at(selection.start, cx);
 5725                let tab_size = settings.tab_size.get();
 5726                let mut rows = selection.spanned_rows(false, &display_map);
 5727
 5728                // Avoid re-outdenting a row that has already been outdented by a
 5729                // previous selection.
 5730                if let Some(last_row) = last_outdent {
 5731                    if last_row == rows.start {
 5732                        rows.start = rows.start.next_row();
 5733                    }
 5734                }
 5735                let has_multiple_rows = rows.len() > 1;
 5736                for row in rows.iter_rows() {
 5737                    let indent_size = snapshot.indent_size_for_line(row);
 5738                    if indent_size.len > 0 {
 5739                        let deletion_len = match indent_size.kind {
 5740                            IndentKind::Space => {
 5741                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5742                                if columns_to_prev_tab_stop == 0 {
 5743                                    tab_size
 5744                                } else {
 5745                                    columns_to_prev_tab_stop
 5746                                }
 5747                            }
 5748                            IndentKind::Tab => 1,
 5749                        };
 5750                        let start = if has_multiple_rows
 5751                            || deletion_len > selection.start.column
 5752                            || indent_size.len < selection.start.column
 5753                        {
 5754                            0
 5755                        } else {
 5756                            selection.start.column - deletion_len
 5757                        };
 5758                        deletion_ranges.push(
 5759                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5760                        );
 5761                        last_outdent = Some(row);
 5762                    }
 5763                }
 5764            }
 5765        }
 5766
 5767        self.transact(cx, |this, cx| {
 5768            this.buffer.update(cx, |buffer, cx| {
 5769                let empty_str: Arc<str> = Arc::default();
 5770                buffer.edit(
 5771                    deletion_ranges
 5772                        .into_iter()
 5773                        .map(|range| (range, empty_str.clone())),
 5774                    None,
 5775                    cx,
 5776                );
 5777            });
 5778            let selections = this.selections.all::<usize>(cx);
 5779            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5780        });
 5781    }
 5782
 5783    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5784        if self.read_only(cx) {
 5785            return;
 5786        }
 5787        let selections = self
 5788            .selections
 5789            .all::<usize>(cx)
 5790            .into_iter()
 5791            .map(|s| s.range());
 5792
 5793        self.transact(cx, |this, cx| {
 5794            this.buffer.update(cx, |buffer, cx| {
 5795                buffer.autoindent_ranges(selections, cx);
 5796            });
 5797            let selections = this.selections.all::<usize>(cx);
 5798            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5799        });
 5800    }
 5801
 5802    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5803        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5804        let selections = self.selections.all::<Point>(cx);
 5805
 5806        let mut new_cursors = Vec::new();
 5807        let mut edit_ranges = Vec::new();
 5808        let mut selections = selections.iter().peekable();
 5809        while let Some(selection) = selections.next() {
 5810            let mut rows = selection.spanned_rows(false, &display_map);
 5811            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5812
 5813            // Accumulate contiguous regions of rows that we want to delete.
 5814            while let Some(next_selection) = selections.peek() {
 5815                let next_rows = next_selection.spanned_rows(false, &display_map);
 5816                if next_rows.start <= rows.end {
 5817                    rows.end = next_rows.end;
 5818                    selections.next().unwrap();
 5819                } else {
 5820                    break;
 5821                }
 5822            }
 5823
 5824            let buffer = &display_map.buffer_snapshot;
 5825            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5826            let edit_end;
 5827            let cursor_buffer_row;
 5828            if buffer.max_point().row >= rows.end.0 {
 5829                // If there's a line after the range, delete the \n from the end of the row range
 5830                // and position the cursor on the next line.
 5831                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5832                cursor_buffer_row = rows.end;
 5833            } else {
 5834                // If there isn't a line after the range, delete the \n from the line before the
 5835                // start of the row range and position the cursor there.
 5836                edit_start = edit_start.saturating_sub(1);
 5837                edit_end = buffer.len();
 5838                cursor_buffer_row = rows.start.previous_row();
 5839            }
 5840
 5841            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5842            *cursor.column_mut() =
 5843                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5844
 5845            new_cursors.push((
 5846                selection.id,
 5847                buffer.anchor_after(cursor.to_point(&display_map)),
 5848            ));
 5849            edit_ranges.push(edit_start..edit_end);
 5850        }
 5851
 5852        self.transact(cx, |this, cx| {
 5853            let buffer = this.buffer.update(cx, |buffer, cx| {
 5854                let empty_str: Arc<str> = Arc::default();
 5855                buffer.edit(
 5856                    edit_ranges
 5857                        .into_iter()
 5858                        .map(|range| (range, empty_str.clone())),
 5859                    None,
 5860                    cx,
 5861                );
 5862                buffer.snapshot(cx)
 5863            });
 5864            let new_selections = new_cursors
 5865                .into_iter()
 5866                .map(|(id, cursor)| {
 5867                    let cursor = cursor.to_point(&buffer);
 5868                    Selection {
 5869                        id,
 5870                        start: cursor,
 5871                        end: cursor,
 5872                        reversed: false,
 5873                        goal: SelectionGoal::None,
 5874                    }
 5875                })
 5876                .collect();
 5877
 5878            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5879                s.select(new_selections);
 5880            });
 5881        });
 5882    }
 5883
 5884    pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
 5885        if self.read_only(cx) {
 5886            return;
 5887        }
 5888        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5889        for selection in self.selections.all::<Point>(cx) {
 5890            let start = MultiBufferRow(selection.start.row);
 5891            // Treat single line selections as if they include the next line. Otherwise this action
 5892            // would do nothing for single line selections individual cursors.
 5893            let end = if selection.start.row == selection.end.row {
 5894                MultiBufferRow(selection.start.row + 1)
 5895            } else {
 5896                MultiBufferRow(selection.end.row)
 5897            };
 5898
 5899            if let Some(last_row_range) = row_ranges.last_mut() {
 5900                if start <= last_row_range.end {
 5901                    last_row_range.end = end;
 5902                    continue;
 5903                }
 5904            }
 5905            row_ranges.push(start..end);
 5906        }
 5907
 5908        let snapshot = self.buffer.read(cx).snapshot(cx);
 5909        let mut cursor_positions = Vec::new();
 5910        for row_range in &row_ranges {
 5911            let anchor = snapshot.anchor_before(Point::new(
 5912                row_range.end.previous_row().0,
 5913                snapshot.line_len(row_range.end.previous_row()),
 5914            ));
 5915            cursor_positions.push(anchor..anchor);
 5916        }
 5917
 5918        self.transact(cx, |this, cx| {
 5919            for row_range in row_ranges.into_iter().rev() {
 5920                for row in row_range.iter_rows().rev() {
 5921                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5922                    let next_line_row = row.next_row();
 5923                    let indent = snapshot.indent_size_for_line(next_line_row);
 5924                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5925
 5926                    let replace =
 5927                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 5928                            " "
 5929                        } else {
 5930                            ""
 5931                        };
 5932
 5933                    this.buffer.update(cx, |buffer, cx| {
 5934                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5935                    });
 5936                }
 5937            }
 5938
 5939            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5940                s.select_anchor_ranges(cursor_positions)
 5941            });
 5942        });
 5943    }
 5944
 5945    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5946        self.join_lines_impl(true, cx);
 5947    }
 5948
 5949    pub fn sort_lines_case_sensitive(
 5950        &mut self,
 5951        _: &SortLinesCaseSensitive,
 5952        cx: &mut ViewContext<Self>,
 5953    ) {
 5954        self.manipulate_lines(cx, |lines| lines.sort())
 5955    }
 5956
 5957    pub fn sort_lines_case_insensitive(
 5958        &mut self,
 5959        _: &SortLinesCaseInsensitive,
 5960        cx: &mut ViewContext<Self>,
 5961    ) {
 5962        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5963    }
 5964
 5965    pub fn unique_lines_case_insensitive(
 5966        &mut self,
 5967        _: &UniqueLinesCaseInsensitive,
 5968        cx: &mut ViewContext<Self>,
 5969    ) {
 5970        self.manipulate_lines(cx, |lines| {
 5971            let mut seen = HashSet::default();
 5972            lines.retain(|line| seen.insert(line.to_lowercase()));
 5973        })
 5974    }
 5975
 5976    pub fn unique_lines_case_sensitive(
 5977        &mut self,
 5978        _: &UniqueLinesCaseSensitive,
 5979        cx: &mut ViewContext<Self>,
 5980    ) {
 5981        self.manipulate_lines(cx, |lines| {
 5982            let mut seen = HashSet::default();
 5983            lines.retain(|line| seen.insert(*line));
 5984        })
 5985    }
 5986
 5987    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 5988        let mut revert_changes = HashMap::default();
 5989        let snapshot = self.snapshot(cx);
 5990        for hunk in hunks_for_ranges(
 5991            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 5992            &snapshot,
 5993        ) {
 5994            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5995        }
 5996        if !revert_changes.is_empty() {
 5997            self.transact(cx, |editor, cx| {
 5998                editor.revert(revert_changes, cx);
 5999            });
 6000        }
 6001    }
 6002
 6003    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6004        let Some(project) = self.project.clone() else {
 6005            return;
 6006        };
 6007        self.reload(project, cx).detach_and_notify_err(cx);
 6008    }
 6009
 6010    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6011        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 6012        if !revert_changes.is_empty() {
 6013            self.transact(cx, |editor, cx| {
 6014                editor.revert(revert_changes, cx);
 6015            });
 6016        }
 6017    }
 6018
 6019    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 6020        let snapshot = self.buffer.read(cx).read(cx);
 6021        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 6022            drop(snapshot);
 6023            let mut revert_changes = HashMap::default();
 6024            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6025            if !revert_changes.is_empty() {
 6026                self.revert(revert_changes, cx)
 6027            }
 6028        }
 6029    }
 6030
 6031    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6032        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6033            let project_path = buffer.read(cx).project_path(cx)?;
 6034            let project = self.project.as_ref()?.read(cx);
 6035            let entry = project.entry_for_path(&project_path, cx)?;
 6036            let parent = match &entry.canonical_path {
 6037                Some(canonical_path) => canonical_path.to_path_buf(),
 6038                None => project.absolute_path(&project_path, cx)?,
 6039            }
 6040            .parent()?
 6041            .to_path_buf();
 6042            Some(parent)
 6043        }) {
 6044            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6045        }
 6046    }
 6047
 6048    fn gather_revert_changes(
 6049        &mut self,
 6050        selections: &[Selection<Point>],
 6051        cx: &mut ViewContext<Editor>,
 6052    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6053        let mut revert_changes = HashMap::default();
 6054        let snapshot = self.snapshot(cx);
 6055        for hunk in hunks_for_selections(&snapshot, selections) {
 6056            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6057        }
 6058        revert_changes
 6059    }
 6060
 6061    pub fn prepare_revert_change(
 6062        &mut self,
 6063        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6064        hunk: &MultiBufferDiffHunk,
 6065        cx: &AppContext,
 6066    ) -> Option<()> {
 6067        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6068        let buffer = buffer.read(cx);
 6069        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6070        let original_text = change_set
 6071            .read(cx)
 6072            .base_text
 6073            .as_ref()?
 6074            .read(cx)
 6075            .as_rope()
 6076            .slice(hunk.diff_base_byte_range.clone());
 6077        let buffer_snapshot = buffer.snapshot();
 6078        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6079        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6080            probe
 6081                .0
 6082                .start
 6083                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6084                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6085        }) {
 6086            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6087            Some(())
 6088        } else {
 6089            None
 6090        }
 6091    }
 6092
 6093    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6094        self.manipulate_lines(cx, |lines| lines.reverse())
 6095    }
 6096
 6097    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6098        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6099    }
 6100
 6101    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6102    where
 6103        Fn: FnMut(&mut Vec<&str>),
 6104    {
 6105        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6106        let buffer = self.buffer.read(cx).snapshot(cx);
 6107
 6108        let mut edits = Vec::new();
 6109
 6110        let selections = self.selections.all::<Point>(cx);
 6111        let mut selections = selections.iter().peekable();
 6112        let mut contiguous_row_selections = Vec::new();
 6113        let mut new_selections = Vec::new();
 6114        let mut added_lines = 0;
 6115        let mut removed_lines = 0;
 6116
 6117        while let Some(selection) = selections.next() {
 6118            let (start_row, end_row) = consume_contiguous_rows(
 6119                &mut contiguous_row_selections,
 6120                selection,
 6121                &display_map,
 6122                &mut selections,
 6123            );
 6124
 6125            let start_point = Point::new(start_row.0, 0);
 6126            let end_point = Point::new(
 6127                end_row.previous_row().0,
 6128                buffer.line_len(end_row.previous_row()),
 6129            );
 6130            let text = buffer
 6131                .text_for_range(start_point..end_point)
 6132                .collect::<String>();
 6133
 6134            let mut lines = text.split('\n').collect_vec();
 6135
 6136            let lines_before = lines.len();
 6137            callback(&mut lines);
 6138            let lines_after = lines.len();
 6139
 6140            edits.push((start_point..end_point, lines.join("\n")));
 6141
 6142            // Selections must change based on added and removed line count
 6143            let start_row =
 6144                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6145            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6146            new_selections.push(Selection {
 6147                id: selection.id,
 6148                start: start_row,
 6149                end: end_row,
 6150                goal: SelectionGoal::None,
 6151                reversed: selection.reversed,
 6152            });
 6153
 6154            if lines_after > lines_before {
 6155                added_lines += lines_after - lines_before;
 6156            } else if lines_before > lines_after {
 6157                removed_lines += lines_before - lines_after;
 6158            }
 6159        }
 6160
 6161        self.transact(cx, |this, cx| {
 6162            let buffer = this.buffer.update(cx, |buffer, cx| {
 6163                buffer.edit(edits, None, cx);
 6164                buffer.snapshot(cx)
 6165            });
 6166
 6167            // Recalculate offsets on newly edited buffer
 6168            let new_selections = new_selections
 6169                .iter()
 6170                .map(|s| {
 6171                    let start_point = Point::new(s.start.0, 0);
 6172                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6173                    Selection {
 6174                        id: s.id,
 6175                        start: buffer.point_to_offset(start_point),
 6176                        end: buffer.point_to_offset(end_point),
 6177                        goal: s.goal,
 6178                        reversed: s.reversed,
 6179                    }
 6180                })
 6181                .collect();
 6182
 6183            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6184                s.select(new_selections);
 6185            });
 6186
 6187            this.request_autoscroll(Autoscroll::fit(), cx);
 6188        });
 6189    }
 6190
 6191    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6192        self.manipulate_text(cx, |text| text.to_uppercase())
 6193    }
 6194
 6195    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6196        self.manipulate_text(cx, |text| text.to_lowercase())
 6197    }
 6198
 6199    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6200        self.manipulate_text(cx, |text| {
 6201            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6202            // https://github.com/rutrum/convert-case/issues/16
 6203            text.split('\n')
 6204                .map(|line| line.to_case(Case::Title))
 6205                .join("\n")
 6206        })
 6207    }
 6208
 6209    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6210        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6211    }
 6212
 6213    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6214        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6215    }
 6216
 6217    pub fn convert_to_upper_camel_case(
 6218        &mut self,
 6219        _: &ConvertToUpperCamelCase,
 6220        cx: &mut ViewContext<Self>,
 6221    ) {
 6222        self.manipulate_text(cx, |text| {
 6223            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6224            // https://github.com/rutrum/convert-case/issues/16
 6225            text.split('\n')
 6226                .map(|line| line.to_case(Case::UpperCamel))
 6227                .join("\n")
 6228        })
 6229    }
 6230
 6231    pub fn convert_to_lower_camel_case(
 6232        &mut self,
 6233        _: &ConvertToLowerCamelCase,
 6234        cx: &mut ViewContext<Self>,
 6235    ) {
 6236        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6237    }
 6238
 6239    pub fn convert_to_opposite_case(
 6240        &mut self,
 6241        _: &ConvertToOppositeCase,
 6242        cx: &mut ViewContext<Self>,
 6243    ) {
 6244        self.manipulate_text(cx, |text| {
 6245            text.chars()
 6246                .fold(String::with_capacity(text.len()), |mut t, c| {
 6247                    if c.is_uppercase() {
 6248                        t.extend(c.to_lowercase());
 6249                    } else {
 6250                        t.extend(c.to_uppercase());
 6251                    }
 6252                    t
 6253                })
 6254        })
 6255    }
 6256
 6257    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6258    where
 6259        Fn: FnMut(&str) -> String,
 6260    {
 6261        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6262        let buffer = self.buffer.read(cx).snapshot(cx);
 6263
 6264        let mut new_selections = Vec::new();
 6265        let mut edits = Vec::new();
 6266        let mut selection_adjustment = 0i32;
 6267
 6268        for selection in self.selections.all::<usize>(cx) {
 6269            let selection_is_empty = selection.is_empty();
 6270
 6271            let (start, end) = if selection_is_empty {
 6272                let word_range = movement::surrounding_word(
 6273                    &display_map,
 6274                    selection.start.to_display_point(&display_map),
 6275                );
 6276                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6277                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6278                (start, end)
 6279            } else {
 6280                (selection.start, selection.end)
 6281            };
 6282
 6283            let text = buffer.text_for_range(start..end).collect::<String>();
 6284            let old_length = text.len() as i32;
 6285            let text = callback(&text);
 6286
 6287            new_selections.push(Selection {
 6288                start: (start as i32 - selection_adjustment) as usize,
 6289                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6290                goal: SelectionGoal::None,
 6291                ..selection
 6292            });
 6293
 6294            selection_adjustment += old_length - text.len() as i32;
 6295
 6296            edits.push((start..end, text));
 6297        }
 6298
 6299        self.transact(cx, |this, cx| {
 6300            this.buffer.update(cx, |buffer, cx| {
 6301                buffer.edit(edits, None, cx);
 6302            });
 6303
 6304            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6305                s.select(new_selections);
 6306            });
 6307
 6308            this.request_autoscroll(Autoscroll::fit(), cx);
 6309        });
 6310    }
 6311
 6312    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6313        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6314        let buffer = &display_map.buffer_snapshot;
 6315        let selections = self.selections.all::<Point>(cx);
 6316
 6317        let mut edits = Vec::new();
 6318        let mut selections_iter = selections.iter().peekable();
 6319        while let Some(selection) = selections_iter.next() {
 6320            let mut rows = selection.spanned_rows(false, &display_map);
 6321            // duplicate line-wise
 6322            if whole_lines || selection.start == selection.end {
 6323                // Avoid duplicating the same lines twice.
 6324                while let Some(next_selection) = selections_iter.peek() {
 6325                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6326                    if next_rows.start < rows.end {
 6327                        rows.end = next_rows.end;
 6328                        selections_iter.next().unwrap();
 6329                    } else {
 6330                        break;
 6331                    }
 6332                }
 6333
 6334                // Copy the text from the selected row region and splice it either at the start
 6335                // or end of the region.
 6336                let start = Point::new(rows.start.0, 0);
 6337                let end = Point::new(
 6338                    rows.end.previous_row().0,
 6339                    buffer.line_len(rows.end.previous_row()),
 6340                );
 6341                let text = buffer
 6342                    .text_for_range(start..end)
 6343                    .chain(Some("\n"))
 6344                    .collect::<String>();
 6345                let insert_location = if upwards {
 6346                    Point::new(rows.end.0, 0)
 6347                } else {
 6348                    start
 6349                };
 6350                edits.push((insert_location..insert_location, text));
 6351            } else {
 6352                // duplicate character-wise
 6353                let start = selection.start;
 6354                let end = selection.end;
 6355                let text = buffer.text_for_range(start..end).collect::<String>();
 6356                edits.push((selection.end..selection.end, text));
 6357            }
 6358        }
 6359
 6360        self.transact(cx, |this, cx| {
 6361            this.buffer.update(cx, |buffer, cx| {
 6362                buffer.edit(edits, None, cx);
 6363            });
 6364
 6365            this.request_autoscroll(Autoscroll::fit(), cx);
 6366        });
 6367    }
 6368
 6369    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6370        self.duplicate(true, true, cx);
 6371    }
 6372
 6373    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6374        self.duplicate(false, true, cx);
 6375    }
 6376
 6377    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6378        self.duplicate(false, false, cx);
 6379    }
 6380
 6381    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6382        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6383        let buffer = self.buffer.read(cx).snapshot(cx);
 6384
 6385        let mut edits = Vec::new();
 6386        let mut unfold_ranges = Vec::new();
 6387        let mut refold_creases = Vec::new();
 6388
 6389        let selections = self.selections.all::<Point>(cx);
 6390        let mut selections = selections.iter().peekable();
 6391        let mut contiguous_row_selections = Vec::new();
 6392        let mut new_selections = Vec::new();
 6393
 6394        while let Some(selection) = selections.next() {
 6395            // Find all the selections that span a contiguous row range
 6396            let (start_row, end_row) = consume_contiguous_rows(
 6397                &mut contiguous_row_selections,
 6398                selection,
 6399                &display_map,
 6400                &mut selections,
 6401            );
 6402
 6403            // Move the text spanned by the row range to be before the line preceding the row range
 6404            if start_row.0 > 0 {
 6405                let range_to_move = Point::new(
 6406                    start_row.previous_row().0,
 6407                    buffer.line_len(start_row.previous_row()),
 6408                )
 6409                    ..Point::new(
 6410                        end_row.previous_row().0,
 6411                        buffer.line_len(end_row.previous_row()),
 6412                    );
 6413                let insertion_point = display_map
 6414                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6415                    .0;
 6416
 6417                // Don't move lines across excerpts
 6418                if buffer
 6419                    .excerpt_boundaries_in_range((
 6420                        Bound::Excluded(insertion_point),
 6421                        Bound::Included(range_to_move.end),
 6422                    ))
 6423                    .next()
 6424                    .is_none()
 6425                {
 6426                    let text = buffer
 6427                        .text_for_range(range_to_move.clone())
 6428                        .flat_map(|s| s.chars())
 6429                        .skip(1)
 6430                        .chain(['\n'])
 6431                        .collect::<String>();
 6432
 6433                    edits.push((
 6434                        buffer.anchor_after(range_to_move.start)
 6435                            ..buffer.anchor_before(range_to_move.end),
 6436                        String::new(),
 6437                    ));
 6438                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6439                    edits.push((insertion_anchor..insertion_anchor, text));
 6440
 6441                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6442
 6443                    // Move selections up
 6444                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6445                        |mut selection| {
 6446                            selection.start.row -= row_delta;
 6447                            selection.end.row -= row_delta;
 6448                            selection
 6449                        },
 6450                    ));
 6451
 6452                    // Move folds up
 6453                    unfold_ranges.push(range_to_move.clone());
 6454                    for fold in display_map.folds_in_range(
 6455                        buffer.anchor_before(range_to_move.start)
 6456                            ..buffer.anchor_after(range_to_move.end),
 6457                    ) {
 6458                        let mut start = fold.range.start.to_point(&buffer);
 6459                        let mut end = fold.range.end.to_point(&buffer);
 6460                        start.row -= row_delta;
 6461                        end.row -= row_delta;
 6462                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6463                    }
 6464                }
 6465            }
 6466
 6467            // If we didn't move line(s), preserve the existing selections
 6468            new_selections.append(&mut contiguous_row_selections);
 6469        }
 6470
 6471        self.transact(cx, |this, cx| {
 6472            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6473            this.buffer.update(cx, |buffer, cx| {
 6474                for (range, text) in edits {
 6475                    buffer.edit([(range, text)], None, cx);
 6476                }
 6477            });
 6478            this.fold_creases(refold_creases, true, cx);
 6479            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6480                s.select(new_selections);
 6481            })
 6482        });
 6483    }
 6484
 6485    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6486        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6487        let buffer = self.buffer.read(cx).snapshot(cx);
 6488
 6489        let mut edits = Vec::new();
 6490        let mut unfold_ranges = Vec::new();
 6491        let mut refold_creases = Vec::new();
 6492
 6493        let selections = self.selections.all::<Point>(cx);
 6494        let mut selections = selections.iter().peekable();
 6495        let mut contiguous_row_selections = Vec::new();
 6496        let mut new_selections = Vec::new();
 6497
 6498        while let Some(selection) = selections.next() {
 6499            // Find all the selections that span a contiguous row range
 6500            let (start_row, end_row) = consume_contiguous_rows(
 6501                &mut contiguous_row_selections,
 6502                selection,
 6503                &display_map,
 6504                &mut selections,
 6505            );
 6506
 6507            // Move the text spanned by the row range to be after the last line of the row range
 6508            if end_row.0 <= buffer.max_point().row {
 6509                let range_to_move =
 6510                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6511                let insertion_point = display_map
 6512                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6513                    .0;
 6514
 6515                // Don't move lines across excerpt boundaries
 6516                if buffer
 6517                    .excerpt_boundaries_in_range((
 6518                        Bound::Excluded(range_to_move.start),
 6519                        Bound::Included(insertion_point),
 6520                    ))
 6521                    .next()
 6522                    .is_none()
 6523                {
 6524                    let mut text = String::from("\n");
 6525                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6526                    text.pop(); // Drop trailing newline
 6527                    edits.push((
 6528                        buffer.anchor_after(range_to_move.start)
 6529                            ..buffer.anchor_before(range_to_move.end),
 6530                        String::new(),
 6531                    ));
 6532                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6533                    edits.push((insertion_anchor..insertion_anchor, text));
 6534
 6535                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6536
 6537                    // Move selections down
 6538                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6539                        |mut selection| {
 6540                            selection.start.row += row_delta;
 6541                            selection.end.row += row_delta;
 6542                            selection
 6543                        },
 6544                    ));
 6545
 6546                    // Move folds down
 6547                    unfold_ranges.push(range_to_move.clone());
 6548                    for fold in display_map.folds_in_range(
 6549                        buffer.anchor_before(range_to_move.start)
 6550                            ..buffer.anchor_after(range_to_move.end),
 6551                    ) {
 6552                        let mut start = fold.range.start.to_point(&buffer);
 6553                        let mut end = fold.range.end.to_point(&buffer);
 6554                        start.row += row_delta;
 6555                        end.row += row_delta;
 6556                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6557                    }
 6558                }
 6559            }
 6560
 6561            // If we didn't move line(s), preserve the existing selections
 6562            new_selections.append(&mut contiguous_row_selections);
 6563        }
 6564
 6565        self.transact(cx, |this, cx| {
 6566            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6567            this.buffer.update(cx, |buffer, cx| {
 6568                for (range, text) in edits {
 6569                    buffer.edit([(range, text)], None, cx);
 6570                }
 6571            });
 6572            this.fold_creases(refold_creases, true, cx);
 6573            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6574        });
 6575    }
 6576
 6577    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6578        let text_layout_details = &self.text_layout_details(cx);
 6579        self.transact(cx, |this, cx| {
 6580            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6581                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6582                let line_mode = s.line_mode;
 6583                s.move_with(|display_map, selection| {
 6584                    if !selection.is_empty() || line_mode {
 6585                        return;
 6586                    }
 6587
 6588                    let mut head = selection.head();
 6589                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6590                    if head.column() == display_map.line_len(head.row()) {
 6591                        transpose_offset = display_map
 6592                            .buffer_snapshot
 6593                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6594                    }
 6595
 6596                    if transpose_offset == 0 {
 6597                        return;
 6598                    }
 6599
 6600                    *head.column_mut() += 1;
 6601                    head = display_map.clip_point(head, Bias::Right);
 6602                    let goal = SelectionGoal::HorizontalPosition(
 6603                        display_map
 6604                            .x_for_display_point(head, text_layout_details)
 6605                            .into(),
 6606                    );
 6607                    selection.collapse_to(head, goal);
 6608
 6609                    let transpose_start = display_map
 6610                        .buffer_snapshot
 6611                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6612                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6613                        let transpose_end = display_map
 6614                            .buffer_snapshot
 6615                            .clip_offset(transpose_offset + 1, Bias::Right);
 6616                        if let Some(ch) =
 6617                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6618                        {
 6619                            edits.push((transpose_start..transpose_offset, String::new()));
 6620                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6621                        }
 6622                    }
 6623                });
 6624                edits
 6625            });
 6626            this.buffer
 6627                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6628            let selections = this.selections.all::<usize>(cx);
 6629            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6630                s.select(selections);
 6631            });
 6632        });
 6633    }
 6634
 6635    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6636        self.rewrap_impl(IsVimMode::No, cx)
 6637    }
 6638
 6639    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6640        let buffer = self.buffer.read(cx).snapshot(cx);
 6641        let selections = self.selections.all::<Point>(cx);
 6642        let mut selections = selections.iter().peekable();
 6643
 6644        let mut edits = Vec::new();
 6645        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6646
 6647        while let Some(selection) = selections.next() {
 6648            let mut start_row = selection.start.row;
 6649            let mut end_row = selection.end.row;
 6650
 6651            // Skip selections that overlap with a range that has already been rewrapped.
 6652            let selection_range = start_row..end_row;
 6653            if rewrapped_row_ranges
 6654                .iter()
 6655                .any(|range| range.overlaps(&selection_range))
 6656            {
 6657                continue;
 6658            }
 6659
 6660            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6661
 6662            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6663                match language_scope.language_name().0.as_ref() {
 6664                    "Markdown" | "Plain Text" => {
 6665                        should_rewrap = true;
 6666                    }
 6667                    _ => {}
 6668                }
 6669            }
 6670
 6671            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6672
 6673            // Since not all lines in the selection may be at the same indent
 6674            // level, choose the indent size that is the most common between all
 6675            // of the lines.
 6676            //
 6677            // If there is a tie, we use the deepest indent.
 6678            let (indent_size, indent_end) = {
 6679                let mut indent_size_occurrences = HashMap::default();
 6680                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6681
 6682                for row in start_row..=end_row {
 6683                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6684                    rows_by_indent_size.entry(indent).or_default().push(row);
 6685                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6686                }
 6687
 6688                let indent_size = indent_size_occurrences
 6689                    .into_iter()
 6690                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6691                    .map(|(indent, _)| indent)
 6692                    .unwrap_or_default();
 6693                let row = rows_by_indent_size[&indent_size][0];
 6694                let indent_end = Point::new(row, indent_size.len);
 6695
 6696                (indent_size, indent_end)
 6697            };
 6698
 6699            let mut line_prefix = indent_size.chars().collect::<String>();
 6700
 6701            if let Some(comment_prefix) =
 6702                buffer
 6703                    .language_scope_at(selection.head())
 6704                    .and_then(|language| {
 6705                        language
 6706                            .line_comment_prefixes()
 6707                            .iter()
 6708                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6709                            .cloned()
 6710                    })
 6711            {
 6712                line_prefix.push_str(&comment_prefix);
 6713                should_rewrap = true;
 6714            }
 6715
 6716            if !should_rewrap {
 6717                continue;
 6718            }
 6719
 6720            if selection.is_empty() {
 6721                'expand_upwards: while start_row > 0 {
 6722                    let prev_row = start_row - 1;
 6723                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6724                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6725                    {
 6726                        start_row = prev_row;
 6727                    } else {
 6728                        break 'expand_upwards;
 6729                    }
 6730                }
 6731
 6732                'expand_downwards: while end_row < buffer.max_point().row {
 6733                    let next_row = end_row + 1;
 6734                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6735                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6736                    {
 6737                        end_row = next_row;
 6738                    } else {
 6739                        break 'expand_downwards;
 6740                    }
 6741                }
 6742            }
 6743
 6744            let start = Point::new(start_row, 0);
 6745            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6746            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6747            let Some(lines_without_prefixes) = selection_text
 6748                .lines()
 6749                .map(|line| {
 6750                    line.strip_prefix(&line_prefix)
 6751                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6752                        .ok_or_else(|| {
 6753                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6754                        })
 6755                })
 6756                .collect::<Result<Vec<_>, _>>()
 6757                .log_err()
 6758            else {
 6759                continue;
 6760            };
 6761
 6762            let wrap_column = buffer
 6763                .settings_at(Point::new(start_row, 0), cx)
 6764                .preferred_line_length as usize;
 6765            let wrapped_text = wrap_with_prefix(
 6766                line_prefix,
 6767                lines_without_prefixes.join(" "),
 6768                wrap_column,
 6769                tab_size,
 6770            );
 6771
 6772            // TODO: should always use char-based diff while still supporting cursor behavior that
 6773            // matches vim.
 6774            let diff = match is_vim_mode {
 6775                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6776                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6777            };
 6778            let mut offset = start.to_offset(&buffer);
 6779            let mut moved_since_edit = true;
 6780
 6781            for change in diff.iter_all_changes() {
 6782                let value = change.value();
 6783                match change.tag() {
 6784                    ChangeTag::Equal => {
 6785                        offset += value.len();
 6786                        moved_since_edit = true;
 6787                    }
 6788                    ChangeTag::Delete => {
 6789                        let start = buffer.anchor_after(offset);
 6790                        let end = buffer.anchor_before(offset + value.len());
 6791
 6792                        if moved_since_edit {
 6793                            edits.push((start..end, String::new()));
 6794                        } else {
 6795                            edits.last_mut().unwrap().0.end = end;
 6796                        }
 6797
 6798                        offset += value.len();
 6799                        moved_since_edit = false;
 6800                    }
 6801                    ChangeTag::Insert => {
 6802                        if moved_since_edit {
 6803                            let anchor = buffer.anchor_after(offset);
 6804                            edits.push((anchor..anchor, value.to_string()));
 6805                        } else {
 6806                            edits.last_mut().unwrap().1.push_str(value);
 6807                        }
 6808
 6809                        moved_since_edit = false;
 6810                    }
 6811                }
 6812            }
 6813
 6814            rewrapped_row_ranges.push(start_row..=end_row);
 6815        }
 6816
 6817        self.buffer
 6818            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6819    }
 6820
 6821    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6822        let mut text = String::new();
 6823        let buffer = self.buffer.read(cx).snapshot(cx);
 6824        let mut selections = self.selections.all::<Point>(cx);
 6825        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6826        {
 6827            let max_point = buffer.max_point();
 6828            let mut is_first = true;
 6829            for selection in &mut selections {
 6830                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6831                if is_entire_line {
 6832                    selection.start = Point::new(selection.start.row, 0);
 6833                    if !selection.is_empty() && selection.end.column == 0 {
 6834                        selection.end = cmp::min(max_point, selection.end);
 6835                    } else {
 6836                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6837                    }
 6838                    selection.goal = SelectionGoal::None;
 6839                }
 6840                if is_first {
 6841                    is_first = false;
 6842                } else {
 6843                    text += "\n";
 6844                }
 6845                let mut len = 0;
 6846                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6847                    text.push_str(chunk);
 6848                    len += chunk.len();
 6849                }
 6850                clipboard_selections.push(ClipboardSelection {
 6851                    len,
 6852                    is_entire_line,
 6853                    first_line_indent: buffer
 6854                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6855                        .len,
 6856                });
 6857            }
 6858        }
 6859
 6860        self.transact(cx, |this, cx| {
 6861            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6862                s.select(selections);
 6863            });
 6864            this.insert("", cx);
 6865        });
 6866        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6867    }
 6868
 6869    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6870        let item = self.cut_common(cx);
 6871        cx.write_to_clipboard(item);
 6872    }
 6873
 6874    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6875        self.change_selections(None, cx, |s| {
 6876            s.move_with(|snapshot, sel| {
 6877                if sel.is_empty() {
 6878                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6879                }
 6880            });
 6881        });
 6882        let item = self.cut_common(cx);
 6883        cx.set_global(KillRing(item))
 6884    }
 6885
 6886    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6887        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6888            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6889                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6890            } else {
 6891                return;
 6892            }
 6893        } else {
 6894            return;
 6895        };
 6896        self.do_paste(&text, metadata, false, cx);
 6897    }
 6898
 6899    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6900        let selections = self.selections.all::<Point>(cx);
 6901        let buffer = self.buffer.read(cx).read(cx);
 6902        let mut text = String::new();
 6903
 6904        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6905        {
 6906            let max_point = buffer.max_point();
 6907            let mut is_first = true;
 6908            for selection in selections.iter() {
 6909                let mut start = selection.start;
 6910                let mut end = selection.end;
 6911                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6912                if is_entire_line {
 6913                    start = Point::new(start.row, 0);
 6914                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6915                }
 6916                if is_first {
 6917                    is_first = false;
 6918                } else {
 6919                    text += "\n";
 6920                }
 6921                let mut len = 0;
 6922                for chunk in buffer.text_for_range(start..end) {
 6923                    text.push_str(chunk);
 6924                    len += chunk.len();
 6925                }
 6926                clipboard_selections.push(ClipboardSelection {
 6927                    len,
 6928                    is_entire_line,
 6929                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6930                });
 6931            }
 6932        }
 6933
 6934        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6935            text,
 6936            clipboard_selections,
 6937        ));
 6938    }
 6939
 6940    pub fn do_paste(
 6941        &mut self,
 6942        text: &String,
 6943        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6944        handle_entire_lines: bool,
 6945        cx: &mut ViewContext<Self>,
 6946    ) {
 6947        if self.read_only(cx) {
 6948            return;
 6949        }
 6950
 6951        let clipboard_text = Cow::Borrowed(text);
 6952
 6953        self.transact(cx, |this, cx| {
 6954            if let Some(mut clipboard_selections) = clipboard_selections {
 6955                let old_selections = this.selections.all::<usize>(cx);
 6956                let all_selections_were_entire_line =
 6957                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6958                let first_selection_indent_column =
 6959                    clipboard_selections.first().map(|s| s.first_line_indent);
 6960                if clipboard_selections.len() != old_selections.len() {
 6961                    clipboard_selections.drain(..);
 6962                }
 6963                let cursor_offset = this.selections.last::<usize>(cx).head();
 6964                let mut auto_indent_on_paste = true;
 6965
 6966                this.buffer.update(cx, |buffer, cx| {
 6967                    let snapshot = buffer.read(cx);
 6968                    auto_indent_on_paste =
 6969                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6970
 6971                    let mut start_offset = 0;
 6972                    let mut edits = Vec::new();
 6973                    let mut original_indent_columns = Vec::new();
 6974                    for (ix, selection) in old_selections.iter().enumerate() {
 6975                        let to_insert;
 6976                        let entire_line;
 6977                        let original_indent_column;
 6978                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6979                            let end_offset = start_offset + clipboard_selection.len;
 6980                            to_insert = &clipboard_text[start_offset..end_offset];
 6981                            entire_line = clipboard_selection.is_entire_line;
 6982                            start_offset = end_offset + 1;
 6983                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6984                        } else {
 6985                            to_insert = clipboard_text.as_str();
 6986                            entire_line = all_selections_were_entire_line;
 6987                            original_indent_column = first_selection_indent_column
 6988                        }
 6989
 6990                        // If the corresponding selection was empty when this slice of the
 6991                        // clipboard text was written, then the entire line containing the
 6992                        // selection was copied. If this selection is also currently empty,
 6993                        // then paste the line before the current line of the buffer.
 6994                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6995                            let column = selection.start.to_point(&snapshot).column as usize;
 6996                            let line_start = selection.start - column;
 6997                            line_start..line_start
 6998                        } else {
 6999                            selection.range()
 7000                        };
 7001
 7002                        edits.push((range, to_insert));
 7003                        original_indent_columns.extend(original_indent_column);
 7004                    }
 7005                    drop(snapshot);
 7006
 7007                    buffer.edit(
 7008                        edits,
 7009                        if auto_indent_on_paste {
 7010                            Some(AutoindentMode::Block {
 7011                                original_indent_columns,
 7012                            })
 7013                        } else {
 7014                            None
 7015                        },
 7016                        cx,
 7017                    );
 7018                });
 7019
 7020                let selections = this.selections.all::<usize>(cx);
 7021                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7022            } else {
 7023                this.insert(&clipboard_text, cx);
 7024            }
 7025        });
 7026    }
 7027
 7028    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7029        if let Some(item) = cx.read_from_clipboard() {
 7030            let entries = item.entries();
 7031
 7032            match entries.first() {
 7033                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7034                // of all the pasted entries.
 7035                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7036                    .do_paste(
 7037                        clipboard_string.text(),
 7038                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7039                        true,
 7040                        cx,
 7041                    ),
 7042                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7043            }
 7044        }
 7045    }
 7046
 7047    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7048        if self.read_only(cx) {
 7049            return;
 7050        }
 7051
 7052        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7053            if let Some((selections, _)) =
 7054                self.selection_history.transaction(transaction_id).cloned()
 7055            {
 7056                self.change_selections(None, cx, |s| {
 7057                    s.select_anchors(selections.to_vec());
 7058                });
 7059            }
 7060            self.request_autoscroll(Autoscroll::fit(), cx);
 7061            self.unmark_text(cx);
 7062            self.refresh_inline_completion(true, false, cx);
 7063            cx.emit(EditorEvent::Edited { transaction_id });
 7064            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7065        }
 7066    }
 7067
 7068    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7069        if self.read_only(cx) {
 7070            return;
 7071        }
 7072
 7073        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7074            if let Some((_, Some(selections))) =
 7075                self.selection_history.transaction(transaction_id).cloned()
 7076            {
 7077                self.change_selections(None, cx, |s| {
 7078                    s.select_anchors(selections.to_vec());
 7079                });
 7080            }
 7081            self.request_autoscroll(Autoscroll::fit(), cx);
 7082            self.unmark_text(cx);
 7083            self.refresh_inline_completion(true, false, cx);
 7084            cx.emit(EditorEvent::Edited { transaction_id });
 7085        }
 7086    }
 7087
 7088    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7089        self.buffer
 7090            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7091    }
 7092
 7093    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7094        self.buffer
 7095            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7096    }
 7097
 7098    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7099        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7100            let line_mode = s.line_mode;
 7101            s.move_with(|map, selection| {
 7102                let cursor = if selection.is_empty() && !line_mode {
 7103                    movement::left(map, selection.start)
 7104                } else {
 7105                    selection.start
 7106                };
 7107                selection.collapse_to(cursor, SelectionGoal::None);
 7108            });
 7109        })
 7110    }
 7111
 7112    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7113        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7114            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7115        })
 7116    }
 7117
 7118    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7119        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7120            let line_mode = s.line_mode;
 7121            s.move_with(|map, selection| {
 7122                let cursor = if selection.is_empty() && !line_mode {
 7123                    movement::right(map, selection.end)
 7124                } else {
 7125                    selection.end
 7126                };
 7127                selection.collapse_to(cursor, SelectionGoal::None)
 7128            });
 7129        })
 7130    }
 7131
 7132    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7133        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7134            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7135        })
 7136    }
 7137
 7138    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7139        if self.take_rename(true, cx).is_some() {
 7140            return;
 7141        }
 7142
 7143        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7144            cx.propagate();
 7145            return;
 7146        }
 7147
 7148        let text_layout_details = &self.text_layout_details(cx);
 7149        let selection_count = self.selections.count();
 7150        let first_selection = self.selections.first_anchor();
 7151
 7152        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7153            let line_mode = s.line_mode;
 7154            s.move_with(|map, selection| {
 7155                if !selection.is_empty() && !line_mode {
 7156                    selection.goal = SelectionGoal::None;
 7157                }
 7158                let (cursor, goal) = movement::up(
 7159                    map,
 7160                    selection.start,
 7161                    selection.goal,
 7162                    false,
 7163                    text_layout_details,
 7164                );
 7165                selection.collapse_to(cursor, goal);
 7166            });
 7167        });
 7168
 7169        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7170        {
 7171            cx.propagate();
 7172        }
 7173    }
 7174
 7175    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7176        if self.take_rename(true, cx).is_some() {
 7177            return;
 7178        }
 7179
 7180        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7181            cx.propagate();
 7182            return;
 7183        }
 7184
 7185        let text_layout_details = &self.text_layout_details(cx);
 7186
 7187        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7188            let line_mode = s.line_mode;
 7189            s.move_with(|map, selection| {
 7190                if !selection.is_empty() && !line_mode {
 7191                    selection.goal = SelectionGoal::None;
 7192                }
 7193                let (cursor, goal) = movement::up_by_rows(
 7194                    map,
 7195                    selection.start,
 7196                    action.lines,
 7197                    selection.goal,
 7198                    false,
 7199                    text_layout_details,
 7200                );
 7201                selection.collapse_to(cursor, goal);
 7202            });
 7203        })
 7204    }
 7205
 7206    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7207        if self.take_rename(true, cx).is_some() {
 7208            return;
 7209        }
 7210
 7211        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7212            cx.propagate();
 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            let line_mode = s.line_mode;
 7220            s.move_with(|map, selection| {
 7221                if !selection.is_empty() && !line_mode {
 7222                    selection.goal = SelectionGoal::None;
 7223                }
 7224                let (cursor, goal) = movement::down_by_rows(
 7225                    map,
 7226                    selection.start,
 7227                    action.lines,
 7228                    selection.goal,
 7229                    false,
 7230                    text_layout_details,
 7231                );
 7232                selection.collapse_to(cursor, goal);
 7233            });
 7234        })
 7235    }
 7236
 7237    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7238        let text_layout_details = &self.text_layout_details(cx);
 7239        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7240            s.move_heads_with(|map, head, goal| {
 7241                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7242            })
 7243        })
 7244    }
 7245
 7246    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7247        let text_layout_details = &self.text_layout_details(cx);
 7248        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7249            s.move_heads_with(|map, head, goal| {
 7250                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7251            })
 7252        })
 7253    }
 7254
 7255    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7256        let Some(row_count) = self.visible_row_count() else {
 7257            return;
 7258        };
 7259
 7260        let text_layout_details = &self.text_layout_details(cx);
 7261
 7262        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7263            s.move_heads_with(|map, head, goal| {
 7264                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7265            })
 7266        })
 7267    }
 7268
 7269    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7270        if self.take_rename(true, cx).is_some() {
 7271            return;
 7272        }
 7273
 7274        if self
 7275            .context_menu
 7276            .borrow_mut()
 7277            .as_mut()
 7278            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7279            .unwrap_or(false)
 7280        {
 7281            return;
 7282        }
 7283
 7284        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7285            cx.propagate();
 7286            return;
 7287        }
 7288
 7289        let Some(row_count) = self.visible_row_count() else {
 7290            return;
 7291        };
 7292
 7293        let autoscroll = if action.center_cursor {
 7294            Autoscroll::center()
 7295        } else {
 7296            Autoscroll::fit()
 7297        };
 7298
 7299        let text_layout_details = &self.text_layout_details(cx);
 7300
 7301        self.change_selections(Some(autoscroll), cx, |s| {
 7302            let line_mode = s.line_mode;
 7303            s.move_with(|map, selection| {
 7304                if !selection.is_empty() && !line_mode {
 7305                    selection.goal = SelectionGoal::None;
 7306                }
 7307                let (cursor, goal) = movement::up_by_rows(
 7308                    map,
 7309                    selection.end,
 7310                    row_count,
 7311                    selection.goal,
 7312                    false,
 7313                    text_layout_details,
 7314                );
 7315                selection.collapse_to(cursor, goal);
 7316            });
 7317        });
 7318    }
 7319
 7320    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7321        let text_layout_details = &self.text_layout_details(cx);
 7322        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7323            s.move_heads_with(|map, head, goal| {
 7324                movement::up(map, head, goal, false, text_layout_details)
 7325            })
 7326        })
 7327    }
 7328
 7329    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7330        self.take_rename(true, cx);
 7331
 7332        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7333            cx.propagate();
 7334            return;
 7335        }
 7336
 7337        let text_layout_details = &self.text_layout_details(cx);
 7338        let selection_count = self.selections.count();
 7339        let first_selection = self.selections.first_anchor();
 7340
 7341        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7342            let line_mode = s.line_mode;
 7343            s.move_with(|map, selection| {
 7344                if !selection.is_empty() && !line_mode {
 7345                    selection.goal = SelectionGoal::None;
 7346                }
 7347                let (cursor, goal) = movement::down(
 7348                    map,
 7349                    selection.end,
 7350                    selection.goal,
 7351                    false,
 7352                    text_layout_details,
 7353                );
 7354                selection.collapse_to(cursor, goal);
 7355            });
 7356        });
 7357
 7358        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7359        {
 7360            cx.propagate();
 7361        }
 7362    }
 7363
 7364    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7365        let Some(row_count) = self.visible_row_count() else {
 7366            return;
 7367        };
 7368
 7369        let text_layout_details = &self.text_layout_details(cx);
 7370
 7371        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7372            s.move_heads_with(|map, head, goal| {
 7373                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7374            })
 7375        })
 7376    }
 7377
 7378    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7379        if self.take_rename(true, cx).is_some() {
 7380            return;
 7381        }
 7382
 7383        if self
 7384            .context_menu
 7385            .borrow_mut()
 7386            .as_mut()
 7387            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7388            .unwrap_or(false)
 7389        {
 7390            return;
 7391        }
 7392
 7393        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7394            cx.propagate();
 7395            return;
 7396        }
 7397
 7398        let Some(row_count) = self.visible_row_count() else {
 7399            return;
 7400        };
 7401
 7402        let autoscroll = if action.center_cursor {
 7403            Autoscroll::center()
 7404        } else {
 7405            Autoscroll::fit()
 7406        };
 7407
 7408        let text_layout_details = &self.text_layout_details(cx);
 7409        self.change_selections(Some(autoscroll), cx, |s| {
 7410            let line_mode = s.line_mode;
 7411            s.move_with(|map, selection| {
 7412                if !selection.is_empty() && !line_mode {
 7413                    selection.goal = SelectionGoal::None;
 7414                }
 7415                let (cursor, goal) = movement::down_by_rows(
 7416                    map,
 7417                    selection.end,
 7418                    row_count,
 7419                    selection.goal,
 7420                    false,
 7421                    text_layout_details,
 7422                );
 7423                selection.collapse_to(cursor, goal);
 7424            });
 7425        });
 7426    }
 7427
 7428    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7429        let text_layout_details = &self.text_layout_details(cx);
 7430        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7431            s.move_heads_with(|map, head, goal| {
 7432                movement::down(map, head, goal, false, text_layout_details)
 7433            })
 7434        });
 7435    }
 7436
 7437    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7438        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7439            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7440        }
 7441    }
 7442
 7443    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7444        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7445            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7446        }
 7447    }
 7448
 7449    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7450        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7451            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7452        }
 7453    }
 7454
 7455    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7456        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7457            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7458        }
 7459    }
 7460
 7461    pub fn move_to_previous_word_start(
 7462        &mut self,
 7463        _: &MoveToPreviousWordStart,
 7464        cx: &mut ViewContext<Self>,
 7465    ) {
 7466        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7467            s.move_cursors_with(|map, head, _| {
 7468                (
 7469                    movement::previous_word_start(map, head),
 7470                    SelectionGoal::None,
 7471                )
 7472            });
 7473        })
 7474    }
 7475
 7476    pub fn move_to_previous_subword_start(
 7477        &mut self,
 7478        _: &MoveToPreviousSubwordStart,
 7479        cx: &mut ViewContext<Self>,
 7480    ) {
 7481        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7482            s.move_cursors_with(|map, head, _| {
 7483                (
 7484                    movement::previous_subword_start(map, head),
 7485                    SelectionGoal::None,
 7486                )
 7487            });
 7488        })
 7489    }
 7490
 7491    pub fn select_to_previous_word_start(
 7492        &mut self,
 7493        _: &SelectToPreviousWordStart,
 7494        cx: &mut ViewContext<Self>,
 7495    ) {
 7496        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7497            s.move_heads_with(|map, head, _| {
 7498                (
 7499                    movement::previous_word_start(map, head),
 7500                    SelectionGoal::None,
 7501                )
 7502            });
 7503        })
 7504    }
 7505
 7506    pub fn select_to_previous_subword_start(
 7507        &mut self,
 7508        _: &SelectToPreviousSubwordStart,
 7509        cx: &mut ViewContext<Self>,
 7510    ) {
 7511        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7512            s.move_heads_with(|map, head, _| {
 7513                (
 7514                    movement::previous_subword_start(map, head),
 7515                    SelectionGoal::None,
 7516                )
 7517            });
 7518        })
 7519    }
 7520
 7521    pub fn delete_to_previous_word_start(
 7522        &mut self,
 7523        action: &DeleteToPreviousWordStart,
 7524        cx: &mut ViewContext<Self>,
 7525    ) {
 7526        self.transact(cx, |this, cx| {
 7527            this.select_autoclose_pair(cx);
 7528            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7529                let line_mode = s.line_mode;
 7530                s.move_with(|map, selection| {
 7531                    if selection.is_empty() && !line_mode {
 7532                        let cursor = if action.ignore_newlines {
 7533                            movement::previous_word_start(map, selection.head())
 7534                        } else {
 7535                            movement::previous_word_start_or_newline(map, selection.head())
 7536                        };
 7537                        selection.set_head(cursor, SelectionGoal::None);
 7538                    }
 7539                });
 7540            });
 7541            this.insert("", cx);
 7542        });
 7543    }
 7544
 7545    pub fn delete_to_previous_subword_start(
 7546        &mut self,
 7547        _: &DeleteToPreviousSubwordStart,
 7548        cx: &mut ViewContext<Self>,
 7549    ) {
 7550        self.transact(cx, |this, cx| {
 7551            this.select_autoclose_pair(cx);
 7552            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7553                let line_mode = s.line_mode;
 7554                s.move_with(|map, selection| {
 7555                    if selection.is_empty() && !line_mode {
 7556                        let cursor = movement::previous_subword_start(map, selection.head());
 7557                        selection.set_head(cursor, SelectionGoal::None);
 7558                    }
 7559                });
 7560            });
 7561            this.insert("", cx);
 7562        });
 7563    }
 7564
 7565    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7566        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7567            s.move_cursors_with(|map, head, _| {
 7568                (movement::next_word_end(map, head), SelectionGoal::None)
 7569            });
 7570        })
 7571    }
 7572
 7573    pub fn move_to_next_subword_end(
 7574        &mut self,
 7575        _: &MoveToNextSubwordEnd,
 7576        cx: &mut ViewContext<Self>,
 7577    ) {
 7578        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7579            s.move_cursors_with(|map, head, _| {
 7580                (movement::next_subword_end(map, head), SelectionGoal::None)
 7581            });
 7582        })
 7583    }
 7584
 7585    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7586        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7587            s.move_heads_with(|map, head, _| {
 7588                (movement::next_word_end(map, head), SelectionGoal::None)
 7589            });
 7590        })
 7591    }
 7592
 7593    pub fn select_to_next_subword_end(
 7594        &mut self,
 7595        _: &SelectToNextSubwordEnd,
 7596        cx: &mut ViewContext<Self>,
 7597    ) {
 7598        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7599            s.move_heads_with(|map, head, _| {
 7600                (movement::next_subword_end(map, head), SelectionGoal::None)
 7601            });
 7602        })
 7603    }
 7604
 7605    pub fn delete_to_next_word_end(
 7606        &mut self,
 7607        action: &DeleteToNextWordEnd,
 7608        cx: &mut ViewContext<Self>,
 7609    ) {
 7610        self.transact(cx, |this, cx| {
 7611            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7612                let line_mode = s.line_mode;
 7613                s.move_with(|map, selection| {
 7614                    if selection.is_empty() && !line_mode {
 7615                        let cursor = if action.ignore_newlines {
 7616                            movement::next_word_end(map, selection.head())
 7617                        } else {
 7618                            movement::next_word_end_or_newline(map, selection.head())
 7619                        };
 7620                        selection.set_head(cursor, SelectionGoal::None);
 7621                    }
 7622                });
 7623            });
 7624            this.insert("", cx);
 7625        });
 7626    }
 7627
 7628    pub fn delete_to_next_subword_end(
 7629        &mut self,
 7630        _: &DeleteToNextSubwordEnd,
 7631        cx: &mut ViewContext<Self>,
 7632    ) {
 7633        self.transact(cx, |this, cx| {
 7634            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7635                s.move_with(|map, selection| {
 7636                    if selection.is_empty() {
 7637                        let cursor = movement::next_subword_end(map, selection.head());
 7638                        selection.set_head(cursor, SelectionGoal::None);
 7639                    }
 7640                });
 7641            });
 7642            this.insert("", cx);
 7643        });
 7644    }
 7645
 7646    pub fn move_to_beginning_of_line(
 7647        &mut self,
 7648        action: &MoveToBeginningOfLine,
 7649        cx: &mut ViewContext<Self>,
 7650    ) {
 7651        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7652            s.move_cursors_with(|map, head, _| {
 7653                (
 7654                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7655                    SelectionGoal::None,
 7656                )
 7657            });
 7658        })
 7659    }
 7660
 7661    pub fn select_to_beginning_of_line(
 7662        &mut self,
 7663        action: &SelectToBeginningOfLine,
 7664        cx: &mut ViewContext<Self>,
 7665    ) {
 7666        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7667            s.move_heads_with(|map, head, _| {
 7668                (
 7669                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7670                    SelectionGoal::None,
 7671                )
 7672            });
 7673        });
 7674    }
 7675
 7676    pub fn delete_to_beginning_of_line(
 7677        &mut self,
 7678        _: &DeleteToBeginningOfLine,
 7679        cx: &mut ViewContext<Self>,
 7680    ) {
 7681        self.transact(cx, |this, cx| {
 7682            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7683                s.move_with(|_, selection| {
 7684                    selection.reversed = true;
 7685                });
 7686            });
 7687
 7688            this.select_to_beginning_of_line(
 7689                &SelectToBeginningOfLine {
 7690                    stop_at_soft_wraps: false,
 7691                },
 7692                cx,
 7693            );
 7694            this.backspace(&Backspace, cx);
 7695        });
 7696    }
 7697
 7698    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7699        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7700            s.move_cursors_with(|map, head, _| {
 7701                (
 7702                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7703                    SelectionGoal::None,
 7704                )
 7705            });
 7706        })
 7707    }
 7708
 7709    pub fn select_to_end_of_line(
 7710        &mut self,
 7711        action: &SelectToEndOfLine,
 7712        cx: &mut ViewContext<Self>,
 7713    ) {
 7714        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7715            s.move_heads_with(|map, head, _| {
 7716                (
 7717                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7718                    SelectionGoal::None,
 7719                )
 7720            });
 7721        })
 7722    }
 7723
 7724    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7725        self.transact(cx, |this, cx| {
 7726            this.select_to_end_of_line(
 7727                &SelectToEndOfLine {
 7728                    stop_at_soft_wraps: false,
 7729                },
 7730                cx,
 7731            );
 7732            this.delete(&Delete, cx);
 7733        });
 7734    }
 7735
 7736    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7737        self.transact(cx, |this, cx| {
 7738            this.select_to_end_of_line(
 7739                &SelectToEndOfLine {
 7740                    stop_at_soft_wraps: false,
 7741                },
 7742                cx,
 7743            );
 7744            this.cut(&Cut, cx);
 7745        });
 7746    }
 7747
 7748    pub fn move_to_start_of_paragraph(
 7749        &mut self,
 7750        _: &MoveToStartOfParagraph,
 7751        cx: &mut ViewContext<Self>,
 7752    ) {
 7753        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7754            cx.propagate();
 7755            return;
 7756        }
 7757
 7758        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7759            s.move_with(|map, selection| {
 7760                selection.collapse_to(
 7761                    movement::start_of_paragraph(map, selection.head(), 1),
 7762                    SelectionGoal::None,
 7763                )
 7764            });
 7765        })
 7766    }
 7767
 7768    pub fn move_to_end_of_paragraph(
 7769        &mut self,
 7770        _: &MoveToEndOfParagraph,
 7771        cx: &mut ViewContext<Self>,
 7772    ) {
 7773        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7774            cx.propagate();
 7775            return;
 7776        }
 7777
 7778        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7779            s.move_with(|map, selection| {
 7780                selection.collapse_to(
 7781                    movement::end_of_paragraph(map, selection.head(), 1),
 7782                    SelectionGoal::None,
 7783                )
 7784            });
 7785        })
 7786    }
 7787
 7788    pub fn select_to_start_of_paragraph(
 7789        &mut self,
 7790        _: &SelectToStartOfParagraph,
 7791        cx: &mut ViewContext<Self>,
 7792    ) {
 7793        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7794            cx.propagate();
 7795            return;
 7796        }
 7797
 7798        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7799            s.move_heads_with(|map, head, _| {
 7800                (
 7801                    movement::start_of_paragraph(map, head, 1),
 7802                    SelectionGoal::None,
 7803                )
 7804            });
 7805        })
 7806    }
 7807
 7808    pub fn select_to_end_of_paragraph(
 7809        &mut self,
 7810        _: &SelectToEndOfParagraph,
 7811        cx: &mut ViewContext<Self>,
 7812    ) {
 7813        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7814            cx.propagate();
 7815            return;
 7816        }
 7817
 7818        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7819            s.move_heads_with(|map, head, _| {
 7820                (
 7821                    movement::end_of_paragraph(map, head, 1),
 7822                    SelectionGoal::None,
 7823                )
 7824            });
 7825        })
 7826    }
 7827
 7828    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7829        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7830            cx.propagate();
 7831            return;
 7832        }
 7833
 7834        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7835            s.select_ranges(vec![0..0]);
 7836        });
 7837    }
 7838
 7839    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7840        let mut selection = self.selections.last::<Point>(cx);
 7841        selection.set_head(Point::zero(), SelectionGoal::None);
 7842
 7843        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7844            s.select(vec![selection]);
 7845        });
 7846    }
 7847
 7848    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7849        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7850            cx.propagate();
 7851            return;
 7852        }
 7853
 7854        let cursor = self.buffer.read(cx).read(cx).len();
 7855        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7856            s.select_ranges(vec![cursor..cursor])
 7857        });
 7858    }
 7859
 7860    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7861        self.nav_history = nav_history;
 7862    }
 7863
 7864    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7865        self.nav_history.as_ref()
 7866    }
 7867
 7868    fn push_to_nav_history(
 7869        &mut self,
 7870        cursor_anchor: Anchor,
 7871        new_position: Option<Point>,
 7872        cx: &mut ViewContext<Self>,
 7873    ) {
 7874        if let Some(nav_history) = self.nav_history.as_mut() {
 7875            let buffer = self.buffer.read(cx).read(cx);
 7876            let cursor_position = cursor_anchor.to_point(&buffer);
 7877            let scroll_state = self.scroll_manager.anchor();
 7878            let scroll_top_row = scroll_state.top_row(&buffer);
 7879            drop(buffer);
 7880
 7881            if let Some(new_position) = new_position {
 7882                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7883                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7884                    return;
 7885                }
 7886            }
 7887
 7888            nav_history.push(
 7889                Some(NavigationData {
 7890                    cursor_anchor,
 7891                    cursor_position,
 7892                    scroll_anchor: scroll_state,
 7893                    scroll_top_row,
 7894                }),
 7895                cx,
 7896            );
 7897        }
 7898    }
 7899
 7900    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7901        let buffer = self.buffer.read(cx).snapshot(cx);
 7902        let mut selection = self.selections.first::<usize>(cx);
 7903        selection.set_head(buffer.len(), SelectionGoal::None);
 7904        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7905            s.select(vec![selection]);
 7906        });
 7907    }
 7908
 7909    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7910        let end = self.buffer.read(cx).read(cx).len();
 7911        self.change_selections(None, cx, |s| {
 7912            s.select_ranges(vec![0..end]);
 7913        });
 7914    }
 7915
 7916    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7917        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7918        let mut selections = self.selections.all::<Point>(cx);
 7919        let max_point = display_map.buffer_snapshot.max_point();
 7920        for selection in &mut selections {
 7921            let rows = selection.spanned_rows(true, &display_map);
 7922            selection.start = Point::new(rows.start.0, 0);
 7923            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7924            selection.reversed = false;
 7925        }
 7926        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7927            s.select(selections);
 7928        });
 7929    }
 7930
 7931    pub fn split_selection_into_lines(
 7932        &mut self,
 7933        _: &SplitSelectionIntoLines,
 7934        cx: &mut ViewContext<Self>,
 7935    ) {
 7936        let mut to_unfold = Vec::new();
 7937        let mut new_selection_ranges = Vec::new();
 7938        {
 7939            let selections = self.selections.all::<Point>(cx);
 7940            let buffer = self.buffer.read(cx).read(cx);
 7941            for selection in selections {
 7942                for row in selection.start.row..selection.end.row {
 7943                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7944                    new_selection_ranges.push(cursor..cursor);
 7945                }
 7946                new_selection_ranges.push(selection.end..selection.end);
 7947                to_unfold.push(selection.start..selection.end);
 7948            }
 7949        }
 7950        self.unfold_ranges(&to_unfold, true, true, cx);
 7951        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7952            s.select_ranges(new_selection_ranges);
 7953        });
 7954    }
 7955
 7956    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7957        self.add_selection(true, cx);
 7958    }
 7959
 7960    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7961        self.add_selection(false, cx);
 7962    }
 7963
 7964    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7965        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7966        let mut selections = self.selections.all::<Point>(cx);
 7967        let text_layout_details = self.text_layout_details(cx);
 7968        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7969            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7970            let range = oldest_selection.display_range(&display_map).sorted();
 7971
 7972            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7973            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7974            let positions = start_x.min(end_x)..start_x.max(end_x);
 7975
 7976            selections.clear();
 7977            let mut stack = Vec::new();
 7978            for row in range.start.row().0..=range.end.row().0 {
 7979                if let Some(selection) = self.selections.build_columnar_selection(
 7980                    &display_map,
 7981                    DisplayRow(row),
 7982                    &positions,
 7983                    oldest_selection.reversed,
 7984                    &text_layout_details,
 7985                ) {
 7986                    stack.push(selection.id);
 7987                    selections.push(selection);
 7988                }
 7989            }
 7990
 7991            if above {
 7992                stack.reverse();
 7993            }
 7994
 7995            AddSelectionsState { above, stack }
 7996        });
 7997
 7998        let last_added_selection = *state.stack.last().unwrap();
 7999        let mut new_selections = Vec::new();
 8000        if above == state.above {
 8001            let end_row = if above {
 8002                DisplayRow(0)
 8003            } else {
 8004                display_map.max_point().row()
 8005            };
 8006
 8007            'outer: for selection in selections {
 8008                if selection.id == last_added_selection {
 8009                    let range = selection.display_range(&display_map).sorted();
 8010                    debug_assert_eq!(range.start.row(), range.end.row());
 8011                    let mut row = range.start.row();
 8012                    let positions =
 8013                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8014                            px(start)..px(end)
 8015                        } else {
 8016                            let start_x =
 8017                                display_map.x_for_display_point(range.start, &text_layout_details);
 8018                            let end_x =
 8019                                display_map.x_for_display_point(range.end, &text_layout_details);
 8020                            start_x.min(end_x)..start_x.max(end_x)
 8021                        };
 8022
 8023                    while row != end_row {
 8024                        if above {
 8025                            row.0 -= 1;
 8026                        } else {
 8027                            row.0 += 1;
 8028                        }
 8029
 8030                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8031                            &display_map,
 8032                            row,
 8033                            &positions,
 8034                            selection.reversed,
 8035                            &text_layout_details,
 8036                        ) {
 8037                            state.stack.push(new_selection.id);
 8038                            if above {
 8039                                new_selections.push(new_selection);
 8040                                new_selections.push(selection);
 8041                            } else {
 8042                                new_selections.push(selection);
 8043                                new_selections.push(new_selection);
 8044                            }
 8045
 8046                            continue 'outer;
 8047                        }
 8048                    }
 8049                }
 8050
 8051                new_selections.push(selection);
 8052            }
 8053        } else {
 8054            new_selections = selections;
 8055            new_selections.retain(|s| s.id != last_added_selection);
 8056            state.stack.pop();
 8057        }
 8058
 8059        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8060            s.select(new_selections);
 8061        });
 8062        if state.stack.len() > 1 {
 8063            self.add_selections_state = Some(state);
 8064        }
 8065    }
 8066
 8067    pub fn select_next_match_internal(
 8068        &mut self,
 8069        display_map: &DisplaySnapshot,
 8070        replace_newest: bool,
 8071        autoscroll: Option<Autoscroll>,
 8072        cx: &mut ViewContext<Self>,
 8073    ) -> Result<()> {
 8074        fn select_next_match_ranges(
 8075            this: &mut Editor,
 8076            range: Range<usize>,
 8077            replace_newest: bool,
 8078            auto_scroll: Option<Autoscroll>,
 8079            cx: &mut ViewContext<Editor>,
 8080        ) {
 8081            this.unfold_ranges(&[range.clone()], false, true, cx);
 8082            this.change_selections(auto_scroll, cx, |s| {
 8083                if replace_newest {
 8084                    s.delete(s.newest_anchor().id);
 8085                }
 8086                s.insert_range(range.clone());
 8087            });
 8088        }
 8089
 8090        let buffer = &display_map.buffer_snapshot;
 8091        let mut selections = self.selections.all::<usize>(cx);
 8092        if let Some(mut select_next_state) = self.select_next_state.take() {
 8093            let query = &select_next_state.query;
 8094            if !select_next_state.done {
 8095                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8096                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8097                let mut next_selected_range = None;
 8098
 8099                let bytes_after_last_selection =
 8100                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8101                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8102                let query_matches = query
 8103                    .stream_find_iter(bytes_after_last_selection)
 8104                    .map(|result| (last_selection.end, result))
 8105                    .chain(
 8106                        query
 8107                            .stream_find_iter(bytes_before_first_selection)
 8108                            .map(|result| (0, result)),
 8109                    );
 8110
 8111                for (start_offset, query_match) in query_matches {
 8112                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8113                    let offset_range =
 8114                        start_offset + query_match.start()..start_offset + query_match.end();
 8115                    let display_range = offset_range.start.to_display_point(display_map)
 8116                        ..offset_range.end.to_display_point(display_map);
 8117
 8118                    if !select_next_state.wordwise
 8119                        || (!movement::is_inside_word(display_map, display_range.start)
 8120                            && !movement::is_inside_word(display_map, display_range.end))
 8121                    {
 8122                        // TODO: This is n^2, because we might check all the selections
 8123                        if !selections
 8124                            .iter()
 8125                            .any(|selection| selection.range().overlaps(&offset_range))
 8126                        {
 8127                            next_selected_range = Some(offset_range);
 8128                            break;
 8129                        }
 8130                    }
 8131                }
 8132
 8133                if let Some(next_selected_range) = next_selected_range {
 8134                    select_next_match_ranges(
 8135                        self,
 8136                        next_selected_range,
 8137                        replace_newest,
 8138                        autoscroll,
 8139                        cx,
 8140                    );
 8141                } else {
 8142                    select_next_state.done = true;
 8143                }
 8144            }
 8145
 8146            self.select_next_state = Some(select_next_state);
 8147        } else {
 8148            let mut only_carets = true;
 8149            let mut same_text_selected = true;
 8150            let mut selected_text = None;
 8151
 8152            let mut selections_iter = selections.iter().peekable();
 8153            while let Some(selection) = selections_iter.next() {
 8154                if selection.start != selection.end {
 8155                    only_carets = false;
 8156                }
 8157
 8158                if same_text_selected {
 8159                    if selected_text.is_none() {
 8160                        selected_text =
 8161                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8162                    }
 8163
 8164                    if let Some(next_selection) = selections_iter.peek() {
 8165                        if next_selection.range().len() == selection.range().len() {
 8166                            let next_selected_text = buffer
 8167                                .text_for_range(next_selection.range())
 8168                                .collect::<String>();
 8169                            if Some(next_selected_text) != selected_text {
 8170                                same_text_selected = false;
 8171                                selected_text = None;
 8172                            }
 8173                        } else {
 8174                            same_text_selected = false;
 8175                            selected_text = None;
 8176                        }
 8177                    }
 8178                }
 8179            }
 8180
 8181            if only_carets {
 8182                for selection in &mut selections {
 8183                    let word_range = movement::surrounding_word(
 8184                        display_map,
 8185                        selection.start.to_display_point(display_map),
 8186                    );
 8187                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8188                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8189                    selection.goal = SelectionGoal::None;
 8190                    selection.reversed = false;
 8191                    select_next_match_ranges(
 8192                        self,
 8193                        selection.start..selection.end,
 8194                        replace_newest,
 8195                        autoscroll,
 8196                        cx,
 8197                    );
 8198                }
 8199
 8200                if selections.len() == 1 {
 8201                    let selection = selections
 8202                        .last()
 8203                        .expect("ensured that there's only one selection");
 8204                    let query = buffer
 8205                        .text_for_range(selection.start..selection.end)
 8206                        .collect::<String>();
 8207                    let is_empty = query.is_empty();
 8208                    let select_state = SelectNextState {
 8209                        query: AhoCorasick::new(&[query])?,
 8210                        wordwise: true,
 8211                        done: is_empty,
 8212                    };
 8213                    self.select_next_state = Some(select_state);
 8214                } else {
 8215                    self.select_next_state = None;
 8216                }
 8217            } else if let Some(selected_text) = selected_text {
 8218                self.select_next_state = Some(SelectNextState {
 8219                    query: AhoCorasick::new(&[selected_text])?,
 8220                    wordwise: false,
 8221                    done: false,
 8222                });
 8223                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8224            }
 8225        }
 8226        Ok(())
 8227    }
 8228
 8229    pub fn select_all_matches(
 8230        &mut self,
 8231        _action: &SelectAllMatches,
 8232        cx: &mut ViewContext<Self>,
 8233    ) -> Result<()> {
 8234        self.push_to_selection_history();
 8235        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8236
 8237        self.select_next_match_internal(&display_map, false, None, cx)?;
 8238        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8239            return Ok(());
 8240        };
 8241        if select_next_state.done {
 8242            return Ok(());
 8243        }
 8244
 8245        let mut new_selections = self.selections.all::<usize>(cx);
 8246
 8247        let buffer = &display_map.buffer_snapshot;
 8248        let query_matches = select_next_state
 8249            .query
 8250            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8251
 8252        for query_match in query_matches {
 8253            let query_match = query_match.unwrap(); // can only fail due to I/O
 8254            let offset_range = query_match.start()..query_match.end();
 8255            let display_range = offset_range.start.to_display_point(&display_map)
 8256                ..offset_range.end.to_display_point(&display_map);
 8257
 8258            if !select_next_state.wordwise
 8259                || (!movement::is_inside_word(&display_map, display_range.start)
 8260                    && !movement::is_inside_word(&display_map, display_range.end))
 8261            {
 8262                self.selections.change_with(cx, |selections| {
 8263                    new_selections.push(Selection {
 8264                        id: selections.new_selection_id(),
 8265                        start: offset_range.start,
 8266                        end: offset_range.end,
 8267                        reversed: false,
 8268                        goal: SelectionGoal::None,
 8269                    });
 8270                });
 8271            }
 8272        }
 8273
 8274        new_selections.sort_by_key(|selection| selection.start);
 8275        let mut ix = 0;
 8276        while ix + 1 < new_selections.len() {
 8277            let current_selection = &new_selections[ix];
 8278            let next_selection = &new_selections[ix + 1];
 8279            if current_selection.range().overlaps(&next_selection.range()) {
 8280                if current_selection.id < next_selection.id {
 8281                    new_selections.remove(ix + 1);
 8282                } else {
 8283                    new_selections.remove(ix);
 8284                }
 8285            } else {
 8286                ix += 1;
 8287            }
 8288        }
 8289
 8290        select_next_state.done = true;
 8291        self.unfold_ranges(
 8292            &new_selections
 8293                .iter()
 8294                .map(|selection| selection.range())
 8295                .collect::<Vec<_>>(),
 8296            false,
 8297            false,
 8298            cx,
 8299        );
 8300        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8301            selections.select(new_selections)
 8302        });
 8303
 8304        Ok(())
 8305    }
 8306
 8307    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8308        self.push_to_selection_history();
 8309        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8310        self.select_next_match_internal(
 8311            &display_map,
 8312            action.replace_newest,
 8313            Some(Autoscroll::newest()),
 8314            cx,
 8315        )?;
 8316        Ok(())
 8317    }
 8318
 8319    pub fn select_previous(
 8320        &mut self,
 8321        action: &SelectPrevious,
 8322        cx: &mut ViewContext<Self>,
 8323    ) -> Result<()> {
 8324        self.push_to_selection_history();
 8325        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8326        let buffer = &display_map.buffer_snapshot;
 8327        let mut selections = self.selections.all::<usize>(cx);
 8328        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8329            let query = &select_prev_state.query;
 8330            if !select_prev_state.done {
 8331                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8332                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8333                let mut next_selected_range = None;
 8334                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8335                let bytes_before_last_selection =
 8336                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8337                let bytes_after_first_selection =
 8338                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8339                let query_matches = query
 8340                    .stream_find_iter(bytes_before_last_selection)
 8341                    .map(|result| (last_selection.start, result))
 8342                    .chain(
 8343                        query
 8344                            .stream_find_iter(bytes_after_first_selection)
 8345                            .map(|result| (buffer.len(), result)),
 8346                    );
 8347                for (end_offset, query_match) in query_matches {
 8348                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8349                    let offset_range =
 8350                        end_offset - query_match.end()..end_offset - query_match.start();
 8351                    let display_range = offset_range.start.to_display_point(&display_map)
 8352                        ..offset_range.end.to_display_point(&display_map);
 8353
 8354                    if !select_prev_state.wordwise
 8355                        || (!movement::is_inside_word(&display_map, display_range.start)
 8356                            && !movement::is_inside_word(&display_map, display_range.end))
 8357                    {
 8358                        next_selected_range = Some(offset_range);
 8359                        break;
 8360                    }
 8361                }
 8362
 8363                if let Some(next_selected_range) = next_selected_range {
 8364                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8365                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8366                        if action.replace_newest {
 8367                            s.delete(s.newest_anchor().id);
 8368                        }
 8369                        s.insert_range(next_selected_range);
 8370                    });
 8371                } else {
 8372                    select_prev_state.done = true;
 8373                }
 8374            }
 8375
 8376            self.select_prev_state = Some(select_prev_state);
 8377        } else {
 8378            let mut only_carets = true;
 8379            let mut same_text_selected = true;
 8380            let mut selected_text = None;
 8381
 8382            let mut selections_iter = selections.iter().peekable();
 8383            while let Some(selection) = selections_iter.next() {
 8384                if selection.start != selection.end {
 8385                    only_carets = false;
 8386                }
 8387
 8388                if same_text_selected {
 8389                    if selected_text.is_none() {
 8390                        selected_text =
 8391                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8392                    }
 8393
 8394                    if let Some(next_selection) = selections_iter.peek() {
 8395                        if next_selection.range().len() == selection.range().len() {
 8396                            let next_selected_text = buffer
 8397                                .text_for_range(next_selection.range())
 8398                                .collect::<String>();
 8399                            if Some(next_selected_text) != selected_text {
 8400                                same_text_selected = false;
 8401                                selected_text = None;
 8402                            }
 8403                        } else {
 8404                            same_text_selected = false;
 8405                            selected_text = None;
 8406                        }
 8407                    }
 8408                }
 8409            }
 8410
 8411            if only_carets {
 8412                for selection in &mut selections {
 8413                    let word_range = movement::surrounding_word(
 8414                        &display_map,
 8415                        selection.start.to_display_point(&display_map),
 8416                    );
 8417                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8418                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8419                    selection.goal = SelectionGoal::None;
 8420                    selection.reversed = false;
 8421                }
 8422                if selections.len() == 1 {
 8423                    let selection = selections
 8424                        .last()
 8425                        .expect("ensured that there's only one selection");
 8426                    let query = buffer
 8427                        .text_for_range(selection.start..selection.end)
 8428                        .collect::<String>();
 8429                    let is_empty = query.is_empty();
 8430                    let select_state = SelectNextState {
 8431                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8432                        wordwise: true,
 8433                        done: is_empty,
 8434                    };
 8435                    self.select_prev_state = Some(select_state);
 8436                } else {
 8437                    self.select_prev_state = None;
 8438                }
 8439
 8440                self.unfold_ranges(
 8441                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8442                    false,
 8443                    true,
 8444                    cx,
 8445                );
 8446                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8447                    s.select(selections);
 8448                });
 8449            } else if let Some(selected_text) = selected_text {
 8450                self.select_prev_state = Some(SelectNextState {
 8451                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8452                    wordwise: false,
 8453                    done: false,
 8454                });
 8455                self.select_previous(action, cx)?;
 8456            }
 8457        }
 8458        Ok(())
 8459    }
 8460
 8461    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8462        if self.read_only(cx) {
 8463            return;
 8464        }
 8465        let text_layout_details = &self.text_layout_details(cx);
 8466        self.transact(cx, |this, cx| {
 8467            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8468            let mut edits = Vec::new();
 8469            let mut selection_edit_ranges = Vec::new();
 8470            let mut last_toggled_row = None;
 8471            let snapshot = this.buffer.read(cx).read(cx);
 8472            let empty_str: Arc<str> = Arc::default();
 8473            let mut suffixes_inserted = Vec::new();
 8474            let ignore_indent = action.ignore_indent;
 8475
 8476            fn comment_prefix_range(
 8477                snapshot: &MultiBufferSnapshot,
 8478                row: MultiBufferRow,
 8479                comment_prefix: &str,
 8480                comment_prefix_whitespace: &str,
 8481                ignore_indent: bool,
 8482            ) -> Range<Point> {
 8483                let indent_size = if ignore_indent {
 8484                    0
 8485                } else {
 8486                    snapshot.indent_size_for_line(row).len
 8487                };
 8488
 8489                let start = Point::new(row.0, indent_size);
 8490
 8491                let mut line_bytes = snapshot
 8492                    .bytes_in_range(start..snapshot.max_point())
 8493                    .flatten()
 8494                    .copied();
 8495
 8496                // If this line currently begins with the line comment prefix, then record
 8497                // the range containing the prefix.
 8498                if line_bytes
 8499                    .by_ref()
 8500                    .take(comment_prefix.len())
 8501                    .eq(comment_prefix.bytes())
 8502                {
 8503                    // Include any whitespace that matches the comment prefix.
 8504                    let matching_whitespace_len = line_bytes
 8505                        .zip(comment_prefix_whitespace.bytes())
 8506                        .take_while(|(a, b)| a == b)
 8507                        .count() as u32;
 8508                    let end = Point::new(
 8509                        start.row,
 8510                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8511                    );
 8512                    start..end
 8513                } else {
 8514                    start..start
 8515                }
 8516            }
 8517
 8518            fn comment_suffix_range(
 8519                snapshot: &MultiBufferSnapshot,
 8520                row: MultiBufferRow,
 8521                comment_suffix: &str,
 8522                comment_suffix_has_leading_space: bool,
 8523            ) -> Range<Point> {
 8524                let end = Point::new(row.0, snapshot.line_len(row));
 8525                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8526
 8527                let mut line_end_bytes = snapshot
 8528                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8529                    .flatten()
 8530                    .copied();
 8531
 8532                let leading_space_len = if suffix_start_column > 0
 8533                    && line_end_bytes.next() == Some(b' ')
 8534                    && comment_suffix_has_leading_space
 8535                {
 8536                    1
 8537                } else {
 8538                    0
 8539                };
 8540
 8541                // If this line currently begins with the line comment prefix, then record
 8542                // the range containing the prefix.
 8543                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8544                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8545                    start..end
 8546                } else {
 8547                    end..end
 8548                }
 8549            }
 8550
 8551            // TODO: Handle selections that cross excerpts
 8552            for selection in &mut selections {
 8553                let start_column = snapshot
 8554                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8555                    .len;
 8556                let language = if let Some(language) =
 8557                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8558                {
 8559                    language
 8560                } else {
 8561                    continue;
 8562                };
 8563
 8564                selection_edit_ranges.clear();
 8565
 8566                // If multiple selections contain a given row, avoid processing that
 8567                // row more than once.
 8568                let mut start_row = MultiBufferRow(selection.start.row);
 8569                if last_toggled_row == Some(start_row) {
 8570                    start_row = start_row.next_row();
 8571                }
 8572                let end_row =
 8573                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8574                        MultiBufferRow(selection.end.row - 1)
 8575                    } else {
 8576                        MultiBufferRow(selection.end.row)
 8577                    };
 8578                last_toggled_row = Some(end_row);
 8579
 8580                if start_row > end_row {
 8581                    continue;
 8582                }
 8583
 8584                // If the language has line comments, toggle those.
 8585                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8586
 8587                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8588                if ignore_indent {
 8589                    full_comment_prefixes = full_comment_prefixes
 8590                        .into_iter()
 8591                        .map(|s| Arc::from(s.trim_end()))
 8592                        .collect();
 8593                }
 8594
 8595                if !full_comment_prefixes.is_empty() {
 8596                    let first_prefix = full_comment_prefixes
 8597                        .first()
 8598                        .expect("prefixes is non-empty");
 8599                    let prefix_trimmed_lengths = full_comment_prefixes
 8600                        .iter()
 8601                        .map(|p| p.trim_end_matches(' ').len())
 8602                        .collect::<SmallVec<[usize; 4]>>();
 8603
 8604                    let mut all_selection_lines_are_comments = true;
 8605
 8606                    for row in start_row.0..=end_row.0 {
 8607                        let row = MultiBufferRow(row);
 8608                        if start_row < end_row && snapshot.is_line_blank(row) {
 8609                            continue;
 8610                        }
 8611
 8612                        let prefix_range = full_comment_prefixes
 8613                            .iter()
 8614                            .zip(prefix_trimmed_lengths.iter().copied())
 8615                            .map(|(prefix, trimmed_prefix_len)| {
 8616                                comment_prefix_range(
 8617                                    snapshot.deref(),
 8618                                    row,
 8619                                    &prefix[..trimmed_prefix_len],
 8620                                    &prefix[trimmed_prefix_len..],
 8621                                    ignore_indent,
 8622                                )
 8623                            })
 8624                            .max_by_key(|range| range.end.column - range.start.column)
 8625                            .expect("prefixes is non-empty");
 8626
 8627                        if prefix_range.is_empty() {
 8628                            all_selection_lines_are_comments = false;
 8629                        }
 8630
 8631                        selection_edit_ranges.push(prefix_range);
 8632                    }
 8633
 8634                    if all_selection_lines_are_comments {
 8635                        edits.extend(
 8636                            selection_edit_ranges
 8637                                .iter()
 8638                                .cloned()
 8639                                .map(|range| (range, empty_str.clone())),
 8640                        );
 8641                    } else {
 8642                        let min_column = selection_edit_ranges
 8643                            .iter()
 8644                            .map(|range| range.start.column)
 8645                            .min()
 8646                            .unwrap_or(0);
 8647                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8648                            let position = Point::new(range.start.row, min_column);
 8649                            (position..position, first_prefix.clone())
 8650                        }));
 8651                    }
 8652                } else if let Some((full_comment_prefix, comment_suffix)) =
 8653                    language.block_comment_delimiters()
 8654                {
 8655                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8656                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8657                    let prefix_range = comment_prefix_range(
 8658                        snapshot.deref(),
 8659                        start_row,
 8660                        comment_prefix,
 8661                        comment_prefix_whitespace,
 8662                        ignore_indent,
 8663                    );
 8664                    let suffix_range = comment_suffix_range(
 8665                        snapshot.deref(),
 8666                        end_row,
 8667                        comment_suffix.trim_start_matches(' '),
 8668                        comment_suffix.starts_with(' '),
 8669                    );
 8670
 8671                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8672                        edits.push((
 8673                            prefix_range.start..prefix_range.start,
 8674                            full_comment_prefix.clone(),
 8675                        ));
 8676                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8677                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8678                    } else {
 8679                        edits.push((prefix_range, empty_str.clone()));
 8680                        edits.push((suffix_range, empty_str.clone()));
 8681                    }
 8682                } else {
 8683                    continue;
 8684                }
 8685            }
 8686
 8687            drop(snapshot);
 8688            this.buffer.update(cx, |buffer, cx| {
 8689                buffer.edit(edits, None, cx);
 8690            });
 8691
 8692            // Adjust selections so that they end before any comment suffixes that
 8693            // were inserted.
 8694            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8695            let mut selections = this.selections.all::<Point>(cx);
 8696            let snapshot = this.buffer.read(cx).read(cx);
 8697            for selection in &mut selections {
 8698                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8699                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8700                        Ordering::Less => {
 8701                            suffixes_inserted.next();
 8702                            continue;
 8703                        }
 8704                        Ordering::Greater => break,
 8705                        Ordering::Equal => {
 8706                            if selection.end.column == snapshot.line_len(row) {
 8707                                if selection.is_empty() {
 8708                                    selection.start.column -= suffix_len as u32;
 8709                                }
 8710                                selection.end.column -= suffix_len as u32;
 8711                            }
 8712                            break;
 8713                        }
 8714                    }
 8715                }
 8716            }
 8717
 8718            drop(snapshot);
 8719            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8720
 8721            let selections = this.selections.all::<Point>(cx);
 8722            let selections_on_single_row = selections.windows(2).all(|selections| {
 8723                selections[0].start.row == selections[1].start.row
 8724                    && selections[0].end.row == selections[1].end.row
 8725                    && selections[0].start.row == selections[0].end.row
 8726            });
 8727            let selections_selecting = selections
 8728                .iter()
 8729                .any(|selection| selection.start != selection.end);
 8730            let advance_downwards = action.advance_downwards
 8731                && selections_on_single_row
 8732                && !selections_selecting
 8733                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8734
 8735            if advance_downwards {
 8736                let snapshot = this.buffer.read(cx).snapshot(cx);
 8737
 8738                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8739                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8740                        let mut point = display_point.to_point(display_snapshot);
 8741                        point.row += 1;
 8742                        point = snapshot.clip_point(point, Bias::Left);
 8743                        let display_point = point.to_display_point(display_snapshot);
 8744                        let goal = SelectionGoal::HorizontalPosition(
 8745                            display_snapshot
 8746                                .x_for_display_point(display_point, text_layout_details)
 8747                                .into(),
 8748                        );
 8749                        (display_point, goal)
 8750                    })
 8751                });
 8752            }
 8753        });
 8754    }
 8755
 8756    pub fn select_enclosing_symbol(
 8757        &mut self,
 8758        _: &SelectEnclosingSymbol,
 8759        cx: &mut ViewContext<Self>,
 8760    ) {
 8761        let buffer = self.buffer.read(cx).snapshot(cx);
 8762        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8763
 8764        fn update_selection(
 8765            selection: &Selection<usize>,
 8766            buffer_snap: &MultiBufferSnapshot,
 8767        ) -> Option<Selection<usize>> {
 8768            let cursor = selection.head();
 8769            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8770            for symbol in symbols.iter().rev() {
 8771                let start = symbol.range.start.to_offset(buffer_snap);
 8772                let end = symbol.range.end.to_offset(buffer_snap);
 8773                let new_range = start..end;
 8774                if start < selection.start || end > selection.end {
 8775                    return Some(Selection {
 8776                        id: selection.id,
 8777                        start: new_range.start,
 8778                        end: new_range.end,
 8779                        goal: SelectionGoal::None,
 8780                        reversed: selection.reversed,
 8781                    });
 8782                }
 8783            }
 8784            None
 8785        }
 8786
 8787        let mut selected_larger_symbol = false;
 8788        let new_selections = old_selections
 8789            .iter()
 8790            .map(|selection| match update_selection(selection, &buffer) {
 8791                Some(new_selection) => {
 8792                    if new_selection.range() != selection.range() {
 8793                        selected_larger_symbol = true;
 8794                    }
 8795                    new_selection
 8796                }
 8797                None => selection.clone(),
 8798            })
 8799            .collect::<Vec<_>>();
 8800
 8801        if selected_larger_symbol {
 8802            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8803                s.select(new_selections);
 8804            });
 8805        }
 8806    }
 8807
 8808    pub fn select_larger_syntax_node(
 8809        &mut self,
 8810        _: &SelectLargerSyntaxNode,
 8811        cx: &mut ViewContext<Self>,
 8812    ) {
 8813        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8814        let buffer = self.buffer.read(cx).snapshot(cx);
 8815        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8816
 8817        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8818        let mut selected_larger_node = false;
 8819        let new_selections = old_selections
 8820            .iter()
 8821            .map(|selection| {
 8822                let old_range = selection.start..selection.end;
 8823                let mut new_range = old_range.clone();
 8824                let mut new_node = None;
 8825                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 8826                {
 8827                    new_node = Some(node);
 8828                    new_range = containing_range;
 8829                    if !display_map.intersects_fold(new_range.start)
 8830                        && !display_map.intersects_fold(new_range.end)
 8831                    {
 8832                        break;
 8833                    }
 8834                }
 8835
 8836                if let Some(node) = new_node {
 8837                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 8838                    // nodes. Parent and grandparent are also logged because this operation will not
 8839                    // visit nodes that have the same range as their parent.
 8840                    log::info!("Node: {node:?}");
 8841                    let parent = node.parent();
 8842                    log::info!("Parent: {parent:?}");
 8843                    let grandparent = parent.and_then(|x| x.parent());
 8844                    log::info!("Grandparent: {grandparent:?}");
 8845                }
 8846
 8847                selected_larger_node |= new_range != old_range;
 8848                Selection {
 8849                    id: selection.id,
 8850                    start: new_range.start,
 8851                    end: new_range.end,
 8852                    goal: SelectionGoal::None,
 8853                    reversed: selection.reversed,
 8854                }
 8855            })
 8856            .collect::<Vec<_>>();
 8857
 8858        if selected_larger_node {
 8859            stack.push(old_selections);
 8860            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8861                s.select(new_selections);
 8862            });
 8863        }
 8864        self.select_larger_syntax_node_stack = stack;
 8865    }
 8866
 8867    pub fn select_smaller_syntax_node(
 8868        &mut self,
 8869        _: &SelectSmallerSyntaxNode,
 8870        cx: &mut ViewContext<Self>,
 8871    ) {
 8872        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8873        if let Some(selections) = stack.pop() {
 8874            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8875                s.select(selections.to_vec());
 8876            });
 8877        }
 8878        self.select_larger_syntax_node_stack = stack;
 8879    }
 8880
 8881    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8882        if !EditorSettings::get_global(cx).gutter.runnables {
 8883            self.clear_tasks();
 8884            return Task::ready(());
 8885        }
 8886        let project = self.project.as_ref().map(Model::downgrade);
 8887        cx.spawn(|this, mut cx| async move {
 8888            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8889            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8890                return;
 8891            };
 8892            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8893                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8894            }) else {
 8895                return;
 8896            };
 8897
 8898            let hide_runnables = project
 8899                .update(&mut cx, |project, cx| {
 8900                    // Do not display any test indicators in non-dev server remote projects.
 8901                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8902                })
 8903                .unwrap_or(true);
 8904            if hide_runnables {
 8905                return;
 8906            }
 8907            let new_rows =
 8908                cx.background_executor()
 8909                    .spawn({
 8910                        let snapshot = display_snapshot.clone();
 8911                        async move {
 8912                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8913                        }
 8914                    })
 8915                    .await;
 8916            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8917
 8918            this.update(&mut cx, |this, _| {
 8919                this.clear_tasks();
 8920                for (key, value) in rows {
 8921                    this.insert_tasks(key, value);
 8922                }
 8923            })
 8924            .ok();
 8925        })
 8926    }
 8927    fn fetch_runnable_ranges(
 8928        snapshot: &DisplaySnapshot,
 8929        range: Range<Anchor>,
 8930    ) -> Vec<language::RunnableRange> {
 8931        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8932    }
 8933
 8934    fn runnable_rows(
 8935        project: Model<Project>,
 8936        snapshot: DisplaySnapshot,
 8937        runnable_ranges: Vec<RunnableRange>,
 8938        mut cx: AsyncWindowContext,
 8939    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8940        runnable_ranges
 8941            .into_iter()
 8942            .filter_map(|mut runnable| {
 8943                let tasks = cx
 8944                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8945                    .ok()?;
 8946                if tasks.is_empty() {
 8947                    return None;
 8948                }
 8949
 8950                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8951
 8952                let row = snapshot
 8953                    .buffer_snapshot
 8954                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8955                    .1
 8956                    .start
 8957                    .row;
 8958
 8959                let context_range =
 8960                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8961                Some((
 8962                    (runnable.buffer_id, row),
 8963                    RunnableTasks {
 8964                        templates: tasks,
 8965                        offset: MultiBufferOffset(runnable.run_range.start),
 8966                        context_range,
 8967                        column: point.column,
 8968                        extra_variables: runnable.extra_captures,
 8969                    },
 8970                ))
 8971            })
 8972            .collect()
 8973    }
 8974
 8975    fn templates_with_tags(
 8976        project: &Model<Project>,
 8977        runnable: &mut Runnable,
 8978        cx: &WindowContext,
 8979    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8980        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8981            let (worktree_id, file) = project
 8982                .buffer_for_id(runnable.buffer, cx)
 8983                .and_then(|buffer| buffer.read(cx).file())
 8984                .map(|file| (file.worktree_id(cx), file.clone()))
 8985                .unzip();
 8986
 8987            (
 8988                project.task_store().read(cx).task_inventory().cloned(),
 8989                worktree_id,
 8990                file,
 8991            )
 8992        });
 8993
 8994        let tags = mem::take(&mut runnable.tags);
 8995        let mut tags: Vec<_> = tags
 8996            .into_iter()
 8997            .flat_map(|tag| {
 8998                let tag = tag.0.clone();
 8999                inventory
 9000                    .as_ref()
 9001                    .into_iter()
 9002                    .flat_map(|inventory| {
 9003                        inventory.read(cx).list_tasks(
 9004                            file.clone(),
 9005                            Some(runnable.language.clone()),
 9006                            worktree_id,
 9007                            cx,
 9008                        )
 9009                    })
 9010                    .filter(move |(_, template)| {
 9011                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9012                    })
 9013            })
 9014            .sorted_by_key(|(kind, _)| kind.to_owned())
 9015            .collect();
 9016        if let Some((leading_tag_source, _)) = tags.first() {
 9017            // Strongest source wins; if we have worktree tag binding, prefer that to
 9018            // global and language bindings;
 9019            // if we have a global binding, prefer that to language binding.
 9020            let first_mismatch = tags
 9021                .iter()
 9022                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9023            if let Some(index) = first_mismatch {
 9024                tags.truncate(index);
 9025            }
 9026        }
 9027
 9028        tags
 9029    }
 9030
 9031    pub fn move_to_enclosing_bracket(
 9032        &mut self,
 9033        _: &MoveToEnclosingBracket,
 9034        cx: &mut ViewContext<Self>,
 9035    ) {
 9036        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9037            s.move_offsets_with(|snapshot, selection| {
 9038                let Some(enclosing_bracket_ranges) =
 9039                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9040                else {
 9041                    return;
 9042                };
 9043
 9044                let mut best_length = usize::MAX;
 9045                let mut best_inside = false;
 9046                let mut best_in_bracket_range = false;
 9047                let mut best_destination = None;
 9048                for (open, close) in enclosing_bracket_ranges {
 9049                    let close = close.to_inclusive();
 9050                    let length = close.end() - open.start;
 9051                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9052                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9053                        || close.contains(&selection.head());
 9054
 9055                    // If best is next to a bracket and current isn't, skip
 9056                    if !in_bracket_range && best_in_bracket_range {
 9057                        continue;
 9058                    }
 9059
 9060                    // Prefer smaller lengths unless best is inside and current isn't
 9061                    if length > best_length && (best_inside || !inside) {
 9062                        continue;
 9063                    }
 9064
 9065                    best_length = length;
 9066                    best_inside = inside;
 9067                    best_in_bracket_range = in_bracket_range;
 9068                    best_destination = Some(
 9069                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9070                            if inside {
 9071                                open.end
 9072                            } else {
 9073                                open.start
 9074                            }
 9075                        } else if inside {
 9076                            *close.start()
 9077                        } else {
 9078                            *close.end()
 9079                        },
 9080                    );
 9081                }
 9082
 9083                if let Some(destination) = best_destination {
 9084                    selection.collapse_to(destination, SelectionGoal::None);
 9085                }
 9086            })
 9087        });
 9088    }
 9089
 9090    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9091        self.end_selection(cx);
 9092        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9093        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9094            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9095            self.select_next_state = entry.select_next_state;
 9096            self.select_prev_state = entry.select_prev_state;
 9097            self.add_selections_state = entry.add_selections_state;
 9098            self.request_autoscroll(Autoscroll::newest(), cx);
 9099        }
 9100        self.selection_history.mode = SelectionHistoryMode::Normal;
 9101    }
 9102
 9103    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9104        self.end_selection(cx);
 9105        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9106        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9107            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9108            self.select_next_state = entry.select_next_state;
 9109            self.select_prev_state = entry.select_prev_state;
 9110            self.add_selections_state = entry.add_selections_state;
 9111            self.request_autoscroll(Autoscroll::newest(), cx);
 9112        }
 9113        self.selection_history.mode = SelectionHistoryMode::Normal;
 9114    }
 9115
 9116    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9117        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9118    }
 9119
 9120    pub fn expand_excerpts_down(
 9121        &mut self,
 9122        action: &ExpandExcerptsDown,
 9123        cx: &mut ViewContext<Self>,
 9124    ) {
 9125        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9126    }
 9127
 9128    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9129        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9130    }
 9131
 9132    pub fn expand_excerpts_for_direction(
 9133        &mut self,
 9134        lines: u32,
 9135        direction: ExpandExcerptDirection,
 9136        cx: &mut ViewContext<Self>,
 9137    ) {
 9138        let selections = self.selections.disjoint_anchors();
 9139
 9140        let lines = if lines == 0 {
 9141            EditorSettings::get_global(cx).expand_excerpt_lines
 9142        } else {
 9143            lines
 9144        };
 9145
 9146        self.buffer.update(cx, |buffer, cx| {
 9147            let snapshot = buffer.snapshot(cx);
 9148            let mut excerpt_ids = selections
 9149                .iter()
 9150                .flat_map(|selection| {
 9151                    snapshot
 9152                        .excerpts_for_range(selection.range())
 9153                        .map(|excerpt| excerpt.id())
 9154                })
 9155                .collect::<Vec<_>>();
 9156            excerpt_ids.sort();
 9157            excerpt_ids.dedup();
 9158            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9159        })
 9160    }
 9161
 9162    pub fn expand_excerpt(
 9163        &mut self,
 9164        excerpt: ExcerptId,
 9165        direction: ExpandExcerptDirection,
 9166        cx: &mut ViewContext<Self>,
 9167    ) {
 9168        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9169        self.buffer.update(cx, |buffer, cx| {
 9170            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9171        })
 9172    }
 9173
 9174    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9175        self.go_to_diagnostic_impl(Direction::Next, cx)
 9176    }
 9177
 9178    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9179        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9180    }
 9181
 9182    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9183        let buffer = self.buffer.read(cx).snapshot(cx);
 9184        let selection = self.selections.newest::<usize>(cx);
 9185
 9186        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9187        if direction == Direction::Next {
 9188            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9189                self.activate_diagnostics(popover.group_id(), cx);
 9190                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9191                    let primary_range_start = active_diagnostics.primary_range.start;
 9192                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9193                        let mut new_selection = s.newest_anchor().clone();
 9194                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9195                        s.select_anchors(vec![new_selection.clone()]);
 9196                    });
 9197                }
 9198                return;
 9199            }
 9200        }
 9201
 9202        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9203            active_diagnostics
 9204                .primary_range
 9205                .to_offset(&buffer)
 9206                .to_inclusive()
 9207        });
 9208        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9209            if active_primary_range.contains(&selection.head()) {
 9210                *active_primary_range.start()
 9211            } else {
 9212                selection.head()
 9213            }
 9214        } else {
 9215            selection.head()
 9216        };
 9217        let snapshot = self.snapshot(cx);
 9218        loop {
 9219            let diagnostics = if direction == Direction::Prev {
 9220                buffer
 9221                    .diagnostics_in_range(0..search_start, true)
 9222                    .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
 9223                        diagnostic,
 9224                        range: range.to_offset(&buffer),
 9225                    })
 9226                    .collect::<Vec<_>>()
 9227            } else {
 9228                buffer
 9229                    .diagnostics_in_range(search_start..buffer.len(), false)
 9230                    .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
 9231                        diagnostic,
 9232                        range: range.to_offset(&buffer),
 9233                    })
 9234                    .collect::<Vec<_>>()
 9235            }
 9236            .into_iter()
 9237            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9238            let group = diagnostics
 9239                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9240                // be sorted in a stable way
 9241                // skip until we are at current active diagnostic, if it exists
 9242                .skip_while(|entry| {
 9243                    (match direction {
 9244                        Direction::Prev => entry.range.start >= search_start,
 9245                        Direction::Next => entry.range.start <= search_start,
 9246                    }) && self
 9247                        .active_diagnostics
 9248                        .as_ref()
 9249                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9250                })
 9251                .find_map(|entry| {
 9252                    if entry.diagnostic.is_primary
 9253                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9254                        && !entry.range.is_empty()
 9255                        // if we match with the active diagnostic, skip it
 9256                        && Some(entry.diagnostic.group_id)
 9257                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9258                    {
 9259                        Some((entry.range, entry.diagnostic.group_id))
 9260                    } else {
 9261                        None
 9262                    }
 9263                });
 9264
 9265            if let Some((primary_range, group_id)) = group {
 9266                self.activate_diagnostics(group_id, cx);
 9267                if self.active_diagnostics.is_some() {
 9268                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9269                        s.select(vec![Selection {
 9270                            id: selection.id,
 9271                            start: primary_range.start,
 9272                            end: primary_range.start,
 9273                            reversed: false,
 9274                            goal: SelectionGoal::None,
 9275                        }]);
 9276                    });
 9277                }
 9278                break;
 9279            } else {
 9280                // Cycle around to the start of the buffer, potentially moving back to the start of
 9281                // the currently active diagnostic.
 9282                active_primary_range.take();
 9283                if direction == Direction::Prev {
 9284                    if search_start == buffer.len() {
 9285                        break;
 9286                    } else {
 9287                        search_start = buffer.len();
 9288                    }
 9289                } else if search_start == 0 {
 9290                    break;
 9291                } else {
 9292                    search_start = 0;
 9293                }
 9294            }
 9295        }
 9296    }
 9297
 9298    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9299        let snapshot = self.snapshot(cx);
 9300        let selection = self.selections.newest::<Point>(cx);
 9301        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9302    }
 9303
 9304    fn go_to_hunk_after_position(
 9305        &mut self,
 9306        snapshot: &EditorSnapshot,
 9307        position: Point,
 9308        cx: &mut ViewContext<Editor>,
 9309    ) -> Option<MultiBufferDiffHunk> {
 9310        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9311            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9312                snapshot,
 9313                position,
 9314                ix > 0,
 9315                snapshot.diff_map.diff_hunks_in_range(
 9316                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9317                    &snapshot.buffer_snapshot,
 9318                ),
 9319                cx,
 9320            ) {
 9321                return Some(hunk);
 9322            }
 9323        }
 9324        None
 9325    }
 9326
 9327    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9328        let snapshot = self.snapshot(cx);
 9329        let selection = self.selections.newest::<Point>(cx);
 9330        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9331    }
 9332
 9333    fn go_to_hunk_before_position(
 9334        &mut self,
 9335        snapshot: &EditorSnapshot,
 9336        position: Point,
 9337        cx: &mut ViewContext<Editor>,
 9338    ) -> Option<MultiBufferDiffHunk> {
 9339        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9340            .into_iter()
 9341            .enumerate()
 9342        {
 9343            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9344                snapshot,
 9345                position,
 9346                ix > 0,
 9347                snapshot
 9348                    .diff_map
 9349                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9350                cx,
 9351            ) {
 9352                return Some(hunk);
 9353            }
 9354        }
 9355        None
 9356    }
 9357
 9358    fn go_to_next_hunk_in_direction(
 9359        &mut self,
 9360        snapshot: &DisplaySnapshot,
 9361        initial_point: Point,
 9362        is_wrapped: bool,
 9363        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9364        cx: &mut ViewContext<Editor>,
 9365    ) -> Option<MultiBufferDiffHunk> {
 9366        let display_point = initial_point.to_display_point(snapshot);
 9367        let mut hunks = hunks
 9368            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9369            .filter(|(display_hunk, _)| {
 9370                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9371            })
 9372            .dedup();
 9373
 9374        if let Some((display_hunk, hunk)) = hunks.next() {
 9375            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9376                let row = display_hunk.start_display_row();
 9377                let point = DisplayPoint::new(row, 0);
 9378                s.select_display_ranges([point..point]);
 9379            });
 9380
 9381            Some(hunk)
 9382        } else {
 9383            None
 9384        }
 9385    }
 9386
 9387    pub fn go_to_definition(
 9388        &mut self,
 9389        _: &GoToDefinition,
 9390        cx: &mut ViewContext<Self>,
 9391    ) -> Task<Result<Navigated>> {
 9392        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9393        cx.spawn(|editor, mut cx| async move {
 9394            if definition.await? == Navigated::Yes {
 9395                return Ok(Navigated::Yes);
 9396            }
 9397            match editor.update(&mut cx, |editor, cx| {
 9398                editor.find_all_references(&FindAllReferences, cx)
 9399            })? {
 9400                Some(references) => references.await,
 9401                None => Ok(Navigated::No),
 9402            }
 9403        })
 9404    }
 9405
 9406    pub fn go_to_declaration(
 9407        &mut self,
 9408        _: &GoToDeclaration,
 9409        cx: &mut ViewContext<Self>,
 9410    ) -> Task<Result<Navigated>> {
 9411        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9412    }
 9413
 9414    pub fn go_to_declaration_split(
 9415        &mut self,
 9416        _: &GoToDeclaration,
 9417        cx: &mut ViewContext<Self>,
 9418    ) -> Task<Result<Navigated>> {
 9419        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9420    }
 9421
 9422    pub fn go_to_implementation(
 9423        &mut self,
 9424        _: &GoToImplementation,
 9425        cx: &mut ViewContext<Self>,
 9426    ) -> Task<Result<Navigated>> {
 9427        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9428    }
 9429
 9430    pub fn go_to_implementation_split(
 9431        &mut self,
 9432        _: &GoToImplementationSplit,
 9433        cx: &mut ViewContext<Self>,
 9434    ) -> Task<Result<Navigated>> {
 9435        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9436    }
 9437
 9438    pub fn go_to_type_definition(
 9439        &mut self,
 9440        _: &GoToTypeDefinition,
 9441        cx: &mut ViewContext<Self>,
 9442    ) -> Task<Result<Navigated>> {
 9443        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9444    }
 9445
 9446    pub fn go_to_definition_split(
 9447        &mut self,
 9448        _: &GoToDefinitionSplit,
 9449        cx: &mut ViewContext<Self>,
 9450    ) -> Task<Result<Navigated>> {
 9451        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9452    }
 9453
 9454    pub fn go_to_type_definition_split(
 9455        &mut self,
 9456        _: &GoToTypeDefinitionSplit,
 9457        cx: &mut ViewContext<Self>,
 9458    ) -> Task<Result<Navigated>> {
 9459        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9460    }
 9461
 9462    fn go_to_definition_of_kind(
 9463        &mut self,
 9464        kind: GotoDefinitionKind,
 9465        split: bool,
 9466        cx: &mut ViewContext<Self>,
 9467    ) -> Task<Result<Navigated>> {
 9468        let Some(provider) = self.semantics_provider.clone() else {
 9469            return Task::ready(Ok(Navigated::No));
 9470        };
 9471        let head = self.selections.newest::<usize>(cx).head();
 9472        let buffer = self.buffer.read(cx);
 9473        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9474            text_anchor
 9475        } else {
 9476            return Task::ready(Ok(Navigated::No));
 9477        };
 9478
 9479        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9480            return Task::ready(Ok(Navigated::No));
 9481        };
 9482
 9483        cx.spawn(|editor, mut cx| async move {
 9484            let definitions = definitions.await?;
 9485            let navigated = editor
 9486                .update(&mut cx, |editor, cx| {
 9487                    editor.navigate_to_hover_links(
 9488                        Some(kind),
 9489                        definitions
 9490                            .into_iter()
 9491                            .filter(|location| {
 9492                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9493                            })
 9494                            .map(HoverLink::Text)
 9495                            .collect::<Vec<_>>(),
 9496                        split,
 9497                        cx,
 9498                    )
 9499                })?
 9500                .await?;
 9501            anyhow::Ok(navigated)
 9502        })
 9503    }
 9504
 9505    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9506        let selection = self.selections.newest_anchor();
 9507        let head = selection.head();
 9508        let tail = selection.tail();
 9509
 9510        let Some((buffer, start_position)) =
 9511            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9512        else {
 9513            return;
 9514        };
 9515
 9516        let end_position = if head != tail {
 9517            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9518                return;
 9519            };
 9520            Some(pos)
 9521        } else {
 9522            None
 9523        };
 9524
 9525        let url_finder = cx.spawn(|editor, mut cx| async move {
 9526            let url = if let Some(end_pos) = end_position {
 9527                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9528            } else {
 9529                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9530            };
 9531
 9532            if let Some(url) = url {
 9533                editor.update(&mut cx, |_, cx| {
 9534                    cx.open_url(&url);
 9535                })
 9536            } else {
 9537                Ok(())
 9538            }
 9539        });
 9540
 9541        url_finder.detach();
 9542    }
 9543
 9544    pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
 9545        let Some(workspace) = self.workspace() else {
 9546            return;
 9547        };
 9548
 9549        let position = self.selections.newest_anchor().head();
 9550
 9551        let Some((buffer, buffer_position)) =
 9552            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9553        else {
 9554            return;
 9555        };
 9556
 9557        let project = self.project.clone();
 9558
 9559        cx.spawn(|_, mut cx| async move {
 9560            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9561
 9562            if let Some((_, path)) = result {
 9563                workspace
 9564                    .update(&mut cx, |workspace, cx| {
 9565                        workspace.open_resolved_path(path, cx)
 9566                    })?
 9567                    .await?;
 9568            }
 9569            anyhow::Ok(())
 9570        })
 9571        .detach();
 9572    }
 9573
 9574    pub(crate) fn navigate_to_hover_links(
 9575        &mut self,
 9576        kind: Option<GotoDefinitionKind>,
 9577        mut definitions: Vec<HoverLink>,
 9578        split: bool,
 9579        cx: &mut ViewContext<Editor>,
 9580    ) -> Task<Result<Navigated>> {
 9581        // If there is one definition, just open it directly
 9582        if definitions.len() == 1 {
 9583            let definition = definitions.pop().unwrap();
 9584
 9585            enum TargetTaskResult {
 9586                Location(Option<Location>),
 9587                AlreadyNavigated,
 9588            }
 9589
 9590            let target_task = match definition {
 9591                HoverLink::Text(link) => {
 9592                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9593                }
 9594                HoverLink::InlayHint(lsp_location, server_id) => {
 9595                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9596                    cx.background_executor().spawn(async move {
 9597                        let location = computation.await?;
 9598                        Ok(TargetTaskResult::Location(location))
 9599                    })
 9600                }
 9601                HoverLink::Url(url) => {
 9602                    cx.open_url(&url);
 9603                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9604                }
 9605                HoverLink::File(path) => {
 9606                    if let Some(workspace) = self.workspace() {
 9607                        cx.spawn(|_, mut cx| async move {
 9608                            workspace
 9609                                .update(&mut cx, |workspace, cx| {
 9610                                    workspace.open_resolved_path(path, cx)
 9611                                })?
 9612                                .await
 9613                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9614                        })
 9615                    } else {
 9616                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9617                    }
 9618                }
 9619            };
 9620            cx.spawn(|editor, mut cx| async move {
 9621                let target = match target_task.await.context("target resolution task")? {
 9622                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9623                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9624                    TargetTaskResult::Location(Some(target)) => target,
 9625                };
 9626
 9627                editor.update(&mut cx, |editor, cx| {
 9628                    let Some(workspace) = editor.workspace() else {
 9629                        return Navigated::No;
 9630                    };
 9631                    let pane = workspace.read(cx).active_pane().clone();
 9632
 9633                    let range = target.range.to_offset(target.buffer.read(cx));
 9634                    let range = editor.range_for_match(&range);
 9635
 9636                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9637                        let buffer = target.buffer.read(cx);
 9638                        let range = check_multiline_range(buffer, range);
 9639                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9640                            s.select_ranges([range]);
 9641                        });
 9642                    } else {
 9643                        cx.window_context().defer(move |cx| {
 9644                            let target_editor: View<Self> =
 9645                                workspace.update(cx, |workspace, cx| {
 9646                                    let pane = if split {
 9647                                        workspace.adjacent_pane(cx)
 9648                                    } else {
 9649                                        workspace.active_pane().clone()
 9650                                    };
 9651
 9652                                    workspace.open_project_item(
 9653                                        pane,
 9654                                        target.buffer.clone(),
 9655                                        true,
 9656                                        true,
 9657                                        cx,
 9658                                    )
 9659                                });
 9660                            target_editor.update(cx, |target_editor, cx| {
 9661                                // When selecting a definition in a different buffer, disable the nav history
 9662                                // to avoid creating a history entry at the previous cursor location.
 9663                                pane.update(cx, |pane, _| pane.disable_history());
 9664                                let buffer = target.buffer.read(cx);
 9665                                let range = check_multiline_range(buffer, range);
 9666                                target_editor.change_selections(
 9667                                    Some(Autoscroll::focused()),
 9668                                    cx,
 9669                                    |s| {
 9670                                        s.select_ranges([range]);
 9671                                    },
 9672                                );
 9673                                pane.update(cx, |pane, _| pane.enable_history());
 9674                            });
 9675                        });
 9676                    }
 9677                    Navigated::Yes
 9678                })
 9679            })
 9680        } else if !definitions.is_empty() {
 9681            cx.spawn(|editor, mut cx| async move {
 9682                let (title, location_tasks, workspace) = editor
 9683                    .update(&mut cx, |editor, cx| {
 9684                        let tab_kind = match kind {
 9685                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9686                            _ => "Definitions",
 9687                        };
 9688                        let title = definitions
 9689                            .iter()
 9690                            .find_map(|definition| match definition {
 9691                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9692                                    let buffer = origin.buffer.read(cx);
 9693                                    format!(
 9694                                        "{} for {}",
 9695                                        tab_kind,
 9696                                        buffer
 9697                                            .text_for_range(origin.range.clone())
 9698                                            .collect::<String>()
 9699                                    )
 9700                                }),
 9701                                HoverLink::InlayHint(_, _) => None,
 9702                                HoverLink::Url(_) => None,
 9703                                HoverLink::File(_) => None,
 9704                            })
 9705                            .unwrap_or(tab_kind.to_string());
 9706                        let location_tasks = definitions
 9707                            .into_iter()
 9708                            .map(|definition| match definition {
 9709                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9710                                HoverLink::InlayHint(lsp_location, server_id) => {
 9711                                    editor.compute_target_location(lsp_location, server_id, cx)
 9712                                }
 9713                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9714                                HoverLink::File(_) => Task::ready(Ok(None)),
 9715                            })
 9716                            .collect::<Vec<_>>();
 9717                        (title, location_tasks, editor.workspace().clone())
 9718                    })
 9719                    .context("location tasks preparation")?;
 9720
 9721                let locations = future::join_all(location_tasks)
 9722                    .await
 9723                    .into_iter()
 9724                    .filter_map(|location| location.transpose())
 9725                    .collect::<Result<_>>()
 9726                    .context("location tasks")?;
 9727
 9728                let Some(workspace) = workspace else {
 9729                    return Ok(Navigated::No);
 9730                };
 9731                let opened = workspace
 9732                    .update(&mut cx, |workspace, cx| {
 9733                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9734                    })
 9735                    .ok();
 9736
 9737                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9738            })
 9739        } else {
 9740            Task::ready(Ok(Navigated::No))
 9741        }
 9742    }
 9743
 9744    fn compute_target_location(
 9745        &self,
 9746        lsp_location: lsp::Location,
 9747        server_id: LanguageServerId,
 9748        cx: &mut ViewContext<Self>,
 9749    ) -> Task<anyhow::Result<Option<Location>>> {
 9750        let Some(project) = self.project.clone() else {
 9751            return Task::ready(Ok(None));
 9752        };
 9753
 9754        cx.spawn(move |editor, mut cx| async move {
 9755            let location_task = editor.update(&mut cx, |_, cx| {
 9756                project.update(cx, |project, cx| {
 9757                    let language_server_name = project
 9758                        .language_server_statuses(cx)
 9759                        .find(|(id, _)| server_id == *id)
 9760                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9761                    language_server_name.map(|language_server_name| {
 9762                        project.open_local_buffer_via_lsp(
 9763                            lsp_location.uri.clone(),
 9764                            server_id,
 9765                            language_server_name,
 9766                            cx,
 9767                        )
 9768                    })
 9769                })
 9770            })?;
 9771            let location = match location_task {
 9772                Some(task) => Some({
 9773                    let target_buffer_handle = task.await.context("open local buffer")?;
 9774                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9775                        let target_start = target_buffer
 9776                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9777                        let target_end = target_buffer
 9778                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9779                        target_buffer.anchor_after(target_start)
 9780                            ..target_buffer.anchor_before(target_end)
 9781                    })?;
 9782                    Location {
 9783                        buffer: target_buffer_handle,
 9784                        range,
 9785                    }
 9786                }),
 9787                None => None,
 9788            };
 9789            Ok(location)
 9790        })
 9791    }
 9792
 9793    pub fn find_all_references(
 9794        &mut self,
 9795        _: &FindAllReferences,
 9796        cx: &mut ViewContext<Self>,
 9797    ) -> Option<Task<Result<Navigated>>> {
 9798        let selection = self.selections.newest::<usize>(cx);
 9799        let multi_buffer = self.buffer.read(cx);
 9800        let head = selection.head();
 9801
 9802        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9803        let head_anchor = multi_buffer_snapshot.anchor_at(
 9804            head,
 9805            if head < selection.tail() {
 9806                Bias::Right
 9807            } else {
 9808                Bias::Left
 9809            },
 9810        );
 9811
 9812        match self
 9813            .find_all_references_task_sources
 9814            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9815        {
 9816            Ok(_) => {
 9817                log::info!(
 9818                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9819                );
 9820                return None;
 9821            }
 9822            Err(i) => {
 9823                self.find_all_references_task_sources.insert(i, head_anchor);
 9824            }
 9825        }
 9826
 9827        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9828        let workspace = self.workspace()?;
 9829        let project = workspace.read(cx).project().clone();
 9830        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9831        Some(cx.spawn(|editor, mut cx| async move {
 9832            let _cleanup = defer({
 9833                let mut cx = cx.clone();
 9834                move || {
 9835                    let _ = editor.update(&mut cx, |editor, _| {
 9836                        if let Ok(i) =
 9837                            editor
 9838                                .find_all_references_task_sources
 9839                                .binary_search_by(|anchor| {
 9840                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9841                                })
 9842                        {
 9843                            editor.find_all_references_task_sources.remove(i);
 9844                        }
 9845                    });
 9846                }
 9847            });
 9848
 9849            let locations = references.await?;
 9850            if locations.is_empty() {
 9851                return anyhow::Ok(Navigated::No);
 9852            }
 9853
 9854            workspace.update(&mut cx, |workspace, cx| {
 9855                let title = locations
 9856                    .first()
 9857                    .as_ref()
 9858                    .map(|location| {
 9859                        let buffer = location.buffer.read(cx);
 9860                        format!(
 9861                            "References to `{}`",
 9862                            buffer
 9863                                .text_for_range(location.range.clone())
 9864                                .collect::<String>()
 9865                        )
 9866                    })
 9867                    .unwrap();
 9868                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9869                Navigated::Yes
 9870            })
 9871        }))
 9872    }
 9873
 9874    /// Opens a multibuffer with the given project locations in it
 9875    pub fn open_locations_in_multibuffer(
 9876        workspace: &mut Workspace,
 9877        mut locations: Vec<Location>,
 9878        title: String,
 9879        split: bool,
 9880        cx: &mut ViewContext<Workspace>,
 9881    ) {
 9882        // If there are multiple definitions, open them in a multibuffer
 9883        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9884        let mut locations = locations.into_iter().peekable();
 9885        let mut ranges_to_highlight = Vec::new();
 9886        let capability = workspace.project().read(cx).capability();
 9887
 9888        let excerpt_buffer = cx.new_model(|cx| {
 9889            let mut multibuffer = MultiBuffer::new(capability);
 9890            while let Some(location) = locations.next() {
 9891                let buffer = location.buffer.read(cx);
 9892                let mut ranges_for_buffer = Vec::new();
 9893                let range = location.range.to_offset(buffer);
 9894                ranges_for_buffer.push(range.clone());
 9895
 9896                while let Some(next_location) = locations.peek() {
 9897                    if next_location.buffer == location.buffer {
 9898                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9899                        locations.next();
 9900                    } else {
 9901                        break;
 9902                    }
 9903                }
 9904
 9905                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9906                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9907                    location.buffer.clone(),
 9908                    ranges_for_buffer,
 9909                    DEFAULT_MULTIBUFFER_CONTEXT,
 9910                    cx,
 9911                ))
 9912            }
 9913
 9914            multibuffer.with_title(title)
 9915        });
 9916
 9917        let editor = cx.new_view(|cx| {
 9918            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9919        });
 9920        editor.update(cx, |editor, cx| {
 9921            if let Some(first_range) = ranges_to_highlight.first() {
 9922                editor.change_selections(None, cx, |selections| {
 9923                    selections.clear_disjoint();
 9924                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9925                });
 9926            }
 9927            editor.highlight_background::<Self>(
 9928                &ranges_to_highlight,
 9929                |theme| theme.editor_highlighted_line_background,
 9930                cx,
 9931            );
 9932            editor.register_buffers_with_language_servers(cx);
 9933        });
 9934
 9935        let item = Box::new(editor);
 9936        let item_id = item.item_id();
 9937
 9938        if split {
 9939            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9940        } else {
 9941            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9942                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9943                    pane.close_current_preview_item(cx)
 9944                } else {
 9945                    None
 9946                }
 9947            });
 9948            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9949        }
 9950        workspace.active_pane().update(cx, |pane, cx| {
 9951            pane.set_preview_item_id(Some(item_id), cx);
 9952        });
 9953    }
 9954
 9955    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9956        use language::ToOffset as _;
 9957
 9958        let provider = self.semantics_provider.clone()?;
 9959        let selection = self.selections.newest_anchor().clone();
 9960        let (cursor_buffer, cursor_buffer_position) = self
 9961            .buffer
 9962            .read(cx)
 9963            .text_anchor_for_position(selection.head(), cx)?;
 9964        let (tail_buffer, cursor_buffer_position_end) = self
 9965            .buffer
 9966            .read(cx)
 9967            .text_anchor_for_position(selection.tail(), cx)?;
 9968        if tail_buffer != cursor_buffer {
 9969            return None;
 9970        }
 9971
 9972        let snapshot = cursor_buffer.read(cx).snapshot();
 9973        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9974        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9975        let prepare_rename = provider
 9976            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9977            .unwrap_or_else(|| Task::ready(Ok(None)));
 9978        drop(snapshot);
 9979
 9980        Some(cx.spawn(|this, mut cx| async move {
 9981            let rename_range = if let Some(range) = prepare_rename.await? {
 9982                Some(range)
 9983            } else {
 9984                this.update(&mut cx, |this, cx| {
 9985                    let buffer = this.buffer.read(cx).snapshot(cx);
 9986                    let mut buffer_highlights = this
 9987                        .document_highlights_for_position(selection.head(), &buffer)
 9988                        .filter(|highlight| {
 9989                            highlight.start.excerpt_id == selection.head().excerpt_id
 9990                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9991                        });
 9992                    buffer_highlights
 9993                        .next()
 9994                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9995                })?
 9996            };
 9997            if let Some(rename_range) = rename_range {
 9998                this.update(&mut cx, |this, cx| {
 9999                    let snapshot = cursor_buffer.read(cx).snapshot();
10000                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10001                    let cursor_offset_in_rename_range =
10002                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10003                    let cursor_offset_in_rename_range_end =
10004                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10005
10006                    this.take_rename(false, cx);
10007                    let buffer = this.buffer.read(cx).read(cx);
10008                    let cursor_offset = selection.head().to_offset(&buffer);
10009                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10010                    let rename_end = rename_start + rename_buffer_range.len();
10011                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10012                    let mut old_highlight_id = None;
10013                    let old_name: Arc<str> = buffer
10014                        .chunks(rename_start..rename_end, true)
10015                        .map(|chunk| {
10016                            if old_highlight_id.is_none() {
10017                                old_highlight_id = chunk.syntax_highlight_id;
10018                            }
10019                            chunk.text
10020                        })
10021                        .collect::<String>()
10022                        .into();
10023
10024                    drop(buffer);
10025
10026                    // Position the selection in the rename editor so that it matches the current selection.
10027                    this.show_local_selections = false;
10028                    let rename_editor = cx.new_view(|cx| {
10029                        let mut editor = Editor::single_line(cx);
10030                        editor.buffer.update(cx, |buffer, cx| {
10031                            buffer.edit([(0..0, old_name.clone())], None, cx)
10032                        });
10033                        let rename_selection_range = match cursor_offset_in_rename_range
10034                            .cmp(&cursor_offset_in_rename_range_end)
10035                        {
10036                            Ordering::Equal => {
10037                                editor.select_all(&SelectAll, cx);
10038                                return editor;
10039                            }
10040                            Ordering::Less => {
10041                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10042                            }
10043                            Ordering::Greater => {
10044                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10045                            }
10046                        };
10047                        if rename_selection_range.end > old_name.len() {
10048                            editor.select_all(&SelectAll, cx);
10049                        } else {
10050                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10051                                s.select_ranges([rename_selection_range]);
10052                            });
10053                        }
10054                        editor
10055                    });
10056                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10057                        if e == &EditorEvent::Focused {
10058                            cx.emit(EditorEvent::FocusedIn)
10059                        }
10060                    })
10061                    .detach();
10062
10063                    let write_highlights =
10064                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10065                    let read_highlights =
10066                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10067                    let ranges = write_highlights
10068                        .iter()
10069                        .flat_map(|(_, ranges)| ranges.iter())
10070                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10071                        .cloned()
10072                        .collect();
10073
10074                    this.highlight_text::<Rename>(
10075                        ranges,
10076                        HighlightStyle {
10077                            fade_out: Some(0.6),
10078                            ..Default::default()
10079                        },
10080                        cx,
10081                    );
10082                    let rename_focus_handle = rename_editor.focus_handle(cx);
10083                    cx.focus(&rename_focus_handle);
10084                    let block_id = this.insert_blocks(
10085                        [BlockProperties {
10086                            style: BlockStyle::Flex,
10087                            placement: BlockPlacement::Below(range.start),
10088                            height: 1,
10089                            render: Arc::new({
10090                                let rename_editor = rename_editor.clone();
10091                                move |cx: &mut BlockContext| {
10092                                    let mut text_style = cx.editor_style.text.clone();
10093                                    if let Some(highlight_style) = old_highlight_id
10094                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10095                                    {
10096                                        text_style = text_style.highlight(highlight_style);
10097                                    }
10098                                    div()
10099                                        .block_mouse_down()
10100                                        .pl(cx.anchor_x)
10101                                        .child(EditorElement::new(
10102                                            &rename_editor,
10103                                            EditorStyle {
10104                                                background: cx.theme().system().transparent,
10105                                                local_player: cx.editor_style.local_player,
10106                                                text: text_style,
10107                                                scrollbar_width: cx.editor_style.scrollbar_width,
10108                                                syntax: cx.editor_style.syntax.clone(),
10109                                                status: cx.editor_style.status.clone(),
10110                                                inlay_hints_style: HighlightStyle {
10111                                                    font_weight: Some(FontWeight::BOLD),
10112                                                    ..make_inlay_hints_style(cx)
10113                                                },
10114                                                inline_completion_styles: make_suggestion_styles(
10115                                                    cx,
10116                                                ),
10117                                                ..EditorStyle::default()
10118                                            },
10119                                        ))
10120                                        .into_any_element()
10121                                }
10122                            }),
10123                            priority: 0,
10124                        }],
10125                        Some(Autoscroll::fit()),
10126                        cx,
10127                    )[0];
10128                    this.pending_rename = Some(RenameState {
10129                        range,
10130                        old_name,
10131                        editor: rename_editor,
10132                        block_id,
10133                    });
10134                })?;
10135            }
10136
10137            Ok(())
10138        }))
10139    }
10140
10141    pub fn confirm_rename(
10142        &mut self,
10143        _: &ConfirmRename,
10144        cx: &mut ViewContext<Self>,
10145    ) -> Option<Task<Result<()>>> {
10146        let rename = self.take_rename(false, cx)?;
10147        let workspace = self.workspace()?.downgrade();
10148        let (buffer, start) = self
10149            .buffer
10150            .read(cx)
10151            .text_anchor_for_position(rename.range.start, cx)?;
10152        let (end_buffer, _) = self
10153            .buffer
10154            .read(cx)
10155            .text_anchor_for_position(rename.range.end, cx)?;
10156        if buffer != end_buffer {
10157            return None;
10158        }
10159
10160        let old_name = rename.old_name;
10161        let new_name = rename.editor.read(cx).text(cx);
10162
10163        let rename = self.semantics_provider.as_ref()?.perform_rename(
10164            &buffer,
10165            start,
10166            new_name.clone(),
10167            cx,
10168        )?;
10169
10170        Some(cx.spawn(|editor, mut cx| async move {
10171            let project_transaction = rename.await?;
10172            Self::open_project_transaction(
10173                &editor,
10174                workspace,
10175                project_transaction,
10176                format!("Rename: {}{}", old_name, new_name),
10177                cx.clone(),
10178            )
10179            .await?;
10180
10181            editor.update(&mut cx, |editor, cx| {
10182                editor.refresh_document_highlights(cx);
10183            })?;
10184            Ok(())
10185        }))
10186    }
10187
10188    fn take_rename(
10189        &mut self,
10190        moving_cursor: bool,
10191        cx: &mut ViewContext<Self>,
10192    ) -> Option<RenameState> {
10193        let rename = self.pending_rename.take()?;
10194        if rename.editor.focus_handle(cx).is_focused(cx) {
10195            cx.focus(&self.focus_handle);
10196        }
10197
10198        self.remove_blocks(
10199            [rename.block_id].into_iter().collect(),
10200            Some(Autoscroll::fit()),
10201            cx,
10202        );
10203        self.clear_highlights::<Rename>(cx);
10204        self.show_local_selections = true;
10205
10206        if moving_cursor {
10207            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10208                editor.selections.newest::<usize>(cx).head()
10209            });
10210
10211            // Update the selection to match the position of the selection inside
10212            // the rename editor.
10213            let snapshot = self.buffer.read(cx).read(cx);
10214            let rename_range = rename.range.to_offset(&snapshot);
10215            let cursor_in_editor = snapshot
10216                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10217                .min(rename_range.end);
10218            drop(snapshot);
10219
10220            self.change_selections(None, cx, |s| {
10221                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10222            });
10223        } else {
10224            self.refresh_document_highlights(cx);
10225        }
10226
10227        Some(rename)
10228    }
10229
10230    pub fn pending_rename(&self) -> Option<&RenameState> {
10231        self.pending_rename.as_ref()
10232    }
10233
10234    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10235        let project = match &self.project {
10236            Some(project) => project.clone(),
10237            None => return None,
10238        };
10239
10240        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10241    }
10242
10243    fn format_selections(
10244        &mut self,
10245        _: &FormatSelections,
10246        cx: &mut ViewContext<Self>,
10247    ) -> Option<Task<Result<()>>> {
10248        let project = match &self.project {
10249            Some(project) => project.clone(),
10250            None => return None,
10251        };
10252
10253        let selections = self
10254            .selections
10255            .all_adjusted(cx)
10256            .into_iter()
10257            .filter(|s| !s.is_empty())
10258            .collect_vec();
10259
10260        Some(self.perform_format(
10261            project,
10262            FormatTrigger::Manual,
10263            FormatTarget::Ranges(selections),
10264            cx,
10265        ))
10266    }
10267
10268    fn perform_format(
10269        &mut self,
10270        project: Model<Project>,
10271        trigger: FormatTrigger,
10272        target: FormatTarget,
10273        cx: &mut ViewContext<Self>,
10274    ) -> Task<Result<()>> {
10275        let buffer = self.buffer().clone();
10276        let mut buffers = buffer.read(cx).all_buffers();
10277        if trigger == FormatTrigger::Save {
10278            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10279        }
10280
10281        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10282        let format = project.update(cx, |project, cx| {
10283            project.format(buffers, true, trigger, target, cx)
10284        });
10285
10286        cx.spawn(|_, mut cx| async move {
10287            let transaction = futures::select_biased! {
10288                () = timeout => {
10289                    log::warn!("timed out waiting for formatting");
10290                    None
10291                }
10292                transaction = format.log_err().fuse() => transaction,
10293            };
10294
10295            buffer
10296                .update(&mut cx, |buffer, cx| {
10297                    if let Some(transaction) = transaction {
10298                        if !buffer.is_singleton() {
10299                            buffer.push_transaction(&transaction.0, cx);
10300                        }
10301                    }
10302
10303                    cx.notify();
10304                })
10305                .ok();
10306
10307            Ok(())
10308        })
10309    }
10310
10311    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10312        if let Some(project) = self.project.clone() {
10313            self.buffer.update(cx, |multi_buffer, cx| {
10314                project.update(cx, |project, cx| {
10315                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10316                });
10317            })
10318        }
10319    }
10320
10321    fn cancel_language_server_work(
10322        &mut self,
10323        _: &actions::CancelLanguageServerWork,
10324        cx: &mut ViewContext<Self>,
10325    ) {
10326        if let Some(project) = self.project.clone() {
10327            self.buffer.update(cx, |multi_buffer, cx| {
10328                project.update(cx, |project, cx| {
10329                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10330                });
10331            })
10332        }
10333    }
10334
10335    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10336        cx.show_character_palette();
10337    }
10338
10339    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10340        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10341            let buffer = self.buffer.read(cx).snapshot(cx);
10342            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10343            let is_valid = buffer
10344                .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10345                .any(|entry| {
10346                    let range = entry.range.to_offset(&buffer);
10347                    entry.diagnostic.is_primary
10348                        && !range.is_empty()
10349                        && range.start == primary_range_start
10350                        && entry.diagnostic.message == active_diagnostics.primary_message
10351                });
10352
10353            if is_valid != active_diagnostics.is_valid {
10354                active_diagnostics.is_valid = is_valid;
10355                let mut new_styles = HashMap::default();
10356                for (block_id, diagnostic) in &active_diagnostics.blocks {
10357                    new_styles.insert(
10358                        *block_id,
10359                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10360                    );
10361                }
10362                self.display_map.update(cx, |display_map, _cx| {
10363                    display_map.replace_blocks(new_styles)
10364                });
10365            }
10366        }
10367    }
10368
10369    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10370        self.dismiss_diagnostics(cx);
10371        let snapshot = self.snapshot(cx);
10372        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10373            let buffer = self.buffer.read(cx).snapshot(cx);
10374
10375            let mut primary_range = None;
10376            let mut primary_message = None;
10377            let mut group_end = Point::zero();
10378            let diagnostic_group = buffer
10379                .diagnostic_group(group_id)
10380                .filter_map(|entry| {
10381                    let start = entry.range.start.to_point(&buffer);
10382                    let end = entry.range.end.to_point(&buffer);
10383                    if snapshot.is_line_folded(MultiBufferRow(start.row))
10384                        && (start.row == end.row
10385                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
10386                    {
10387                        return None;
10388                    }
10389                    if end > group_end {
10390                        group_end = end;
10391                    }
10392                    if entry.diagnostic.is_primary {
10393                        primary_range = Some(entry.range.clone());
10394                        primary_message = Some(entry.diagnostic.message.clone());
10395                    }
10396                    Some(entry)
10397                })
10398                .collect::<Vec<_>>();
10399            let primary_range = primary_range?;
10400            let primary_message = primary_message?;
10401
10402            let blocks = display_map
10403                .insert_blocks(
10404                    diagnostic_group.iter().map(|entry| {
10405                        let diagnostic = entry.diagnostic.clone();
10406                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10407                        BlockProperties {
10408                            style: BlockStyle::Fixed,
10409                            placement: BlockPlacement::Below(
10410                                buffer.anchor_after(entry.range.start),
10411                            ),
10412                            height: message_height,
10413                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10414                            priority: 0,
10415                        }
10416                    }),
10417                    cx,
10418                )
10419                .into_iter()
10420                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10421                .collect();
10422
10423            Some(ActiveDiagnosticGroup {
10424                primary_range,
10425                primary_message,
10426                group_id,
10427                blocks,
10428                is_valid: true,
10429            })
10430        });
10431    }
10432
10433    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10434        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10435            self.display_map.update(cx, |display_map, cx| {
10436                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10437            });
10438            cx.notify();
10439        }
10440    }
10441
10442    pub fn set_selections_from_remote(
10443        &mut self,
10444        selections: Vec<Selection<Anchor>>,
10445        pending_selection: Option<Selection<Anchor>>,
10446        cx: &mut ViewContext<Self>,
10447    ) {
10448        let old_cursor_position = self.selections.newest_anchor().head();
10449        self.selections.change_with(cx, |s| {
10450            s.select_anchors(selections);
10451            if let Some(pending_selection) = pending_selection {
10452                s.set_pending(pending_selection, SelectMode::Character);
10453            } else {
10454                s.clear_pending();
10455            }
10456        });
10457        self.selections_did_change(false, &old_cursor_position, true, cx);
10458    }
10459
10460    fn push_to_selection_history(&mut self) {
10461        self.selection_history.push(SelectionHistoryEntry {
10462            selections: self.selections.disjoint_anchors(),
10463            select_next_state: self.select_next_state.clone(),
10464            select_prev_state: self.select_prev_state.clone(),
10465            add_selections_state: self.add_selections_state.clone(),
10466        });
10467    }
10468
10469    pub fn transact(
10470        &mut self,
10471        cx: &mut ViewContext<Self>,
10472        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10473    ) -> Option<TransactionId> {
10474        self.start_transaction_at(Instant::now(), cx);
10475        update(self, cx);
10476        self.end_transaction_at(Instant::now(), cx)
10477    }
10478
10479    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10480        self.end_selection(cx);
10481        if let Some(tx_id) = self
10482            .buffer
10483            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10484        {
10485            self.selection_history
10486                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10487            cx.emit(EditorEvent::TransactionBegun {
10488                transaction_id: tx_id,
10489            })
10490        }
10491    }
10492
10493    pub fn end_transaction_at(
10494        &mut self,
10495        now: Instant,
10496        cx: &mut ViewContext<Self>,
10497    ) -> Option<TransactionId> {
10498        if let Some(transaction_id) = self
10499            .buffer
10500            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10501        {
10502            if let Some((_, end_selections)) =
10503                self.selection_history.transaction_mut(transaction_id)
10504            {
10505                *end_selections = Some(self.selections.disjoint_anchors());
10506            } else {
10507                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10508            }
10509
10510            cx.emit(EditorEvent::Edited { transaction_id });
10511            Some(transaction_id)
10512        } else {
10513            None
10514        }
10515    }
10516
10517    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10518        if self.is_singleton(cx) {
10519            let selection = self.selections.newest::<Point>(cx);
10520
10521            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10522            let range = if selection.is_empty() {
10523                let point = selection.head().to_display_point(&display_map);
10524                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10525                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10526                    .to_point(&display_map);
10527                start..end
10528            } else {
10529                selection.range()
10530            };
10531            if display_map.folds_in_range(range).next().is_some() {
10532                self.unfold_lines(&Default::default(), cx)
10533            } else {
10534                self.fold(&Default::default(), cx)
10535            }
10536        } else {
10537            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10538            let mut toggled_buffers = HashSet::default();
10539            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10540                self.selections
10541                    .disjoint_anchors()
10542                    .into_iter()
10543                    .map(|selection| selection.range()),
10544            ) {
10545                let buffer_id = buffer_snapshot.remote_id();
10546                if toggled_buffers.insert(buffer_id) {
10547                    if self.buffer_folded(buffer_id, cx) {
10548                        self.unfold_buffer(buffer_id, cx);
10549                    } else {
10550                        self.fold_buffer(buffer_id, cx);
10551                    }
10552                }
10553            }
10554        }
10555    }
10556
10557    pub fn toggle_fold_recursive(
10558        &mut self,
10559        _: &actions::ToggleFoldRecursive,
10560        cx: &mut ViewContext<Self>,
10561    ) {
10562        let selection = self.selections.newest::<Point>(cx);
10563
10564        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10565        let range = if selection.is_empty() {
10566            let point = selection.head().to_display_point(&display_map);
10567            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10568            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10569                .to_point(&display_map);
10570            start..end
10571        } else {
10572            selection.range()
10573        };
10574        if display_map.folds_in_range(range).next().is_some() {
10575            self.unfold_recursive(&Default::default(), cx)
10576        } else {
10577            self.fold_recursive(&Default::default(), cx)
10578        }
10579    }
10580
10581    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10582        if self.is_singleton(cx) {
10583            let mut to_fold = Vec::new();
10584            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10585            let selections = self.selections.all_adjusted(cx);
10586
10587            for selection in selections {
10588                let range = selection.range().sorted();
10589                let buffer_start_row = range.start.row;
10590
10591                if range.start.row != range.end.row {
10592                    let mut found = false;
10593                    let mut row = range.start.row;
10594                    while row <= range.end.row {
10595                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10596                        {
10597                            found = true;
10598                            row = crease.range().end.row + 1;
10599                            to_fold.push(crease);
10600                        } else {
10601                            row += 1
10602                        }
10603                    }
10604                    if found {
10605                        continue;
10606                    }
10607                }
10608
10609                for row in (0..=range.start.row).rev() {
10610                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10611                        if crease.range().end.row >= buffer_start_row {
10612                            to_fold.push(crease);
10613                            if row <= range.start.row {
10614                                break;
10615                            }
10616                        }
10617                    }
10618                }
10619            }
10620
10621            self.fold_creases(to_fold, true, cx);
10622        } else {
10623            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10624            let mut folded_buffers = HashSet::default();
10625            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10626                self.selections
10627                    .disjoint_anchors()
10628                    .into_iter()
10629                    .map(|selection| selection.range()),
10630            ) {
10631                let buffer_id = buffer_snapshot.remote_id();
10632                if folded_buffers.insert(buffer_id) {
10633                    self.fold_buffer(buffer_id, cx);
10634                }
10635            }
10636        }
10637    }
10638
10639    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10640        if !self.buffer.read(cx).is_singleton() {
10641            return;
10642        }
10643
10644        let fold_at_level = fold_at.level;
10645        let snapshot = self.buffer.read(cx).snapshot(cx);
10646        let mut to_fold = Vec::new();
10647        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10648
10649        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10650            while start_row < end_row {
10651                match self
10652                    .snapshot(cx)
10653                    .crease_for_buffer_row(MultiBufferRow(start_row))
10654                {
10655                    Some(crease) => {
10656                        let nested_start_row = crease.range().start.row + 1;
10657                        let nested_end_row = crease.range().end.row;
10658
10659                        if current_level < fold_at_level {
10660                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10661                        } else if current_level == fold_at_level {
10662                            to_fold.push(crease);
10663                        }
10664
10665                        start_row = nested_end_row + 1;
10666                    }
10667                    None => start_row += 1,
10668                }
10669            }
10670        }
10671
10672        self.fold_creases(to_fold, true, cx);
10673    }
10674
10675    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10676        if self.buffer.read(cx).is_singleton() {
10677            let mut fold_ranges = Vec::new();
10678            let snapshot = self.buffer.read(cx).snapshot(cx);
10679
10680            for row in 0..snapshot.max_row().0 {
10681                if let Some(foldable_range) =
10682                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10683                {
10684                    fold_ranges.push(foldable_range);
10685                }
10686            }
10687
10688            self.fold_creases(fold_ranges, true, cx);
10689        } else {
10690            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10691                editor
10692                    .update(&mut cx, |editor, cx| {
10693                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10694                            editor.fold_buffer(buffer_id, cx);
10695                        }
10696                    })
10697                    .ok();
10698            });
10699        }
10700    }
10701
10702    pub fn fold_function_bodies(
10703        &mut self,
10704        _: &actions::FoldFunctionBodies,
10705        cx: &mut ViewContext<Self>,
10706    ) {
10707        let snapshot = self.buffer.read(cx).snapshot(cx);
10708        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10709            return;
10710        };
10711        let creases = buffer
10712            .function_body_fold_ranges(0..buffer.len())
10713            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10714            .collect();
10715
10716        self.fold_creases(creases, true, cx);
10717    }
10718
10719    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10720        let mut to_fold = Vec::new();
10721        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10722        let selections = self.selections.all_adjusted(cx);
10723
10724        for selection in selections {
10725            let range = selection.range().sorted();
10726            let buffer_start_row = range.start.row;
10727
10728            if range.start.row != range.end.row {
10729                let mut found = false;
10730                for row in range.start.row..=range.end.row {
10731                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10732                        found = true;
10733                        to_fold.push(crease);
10734                    }
10735                }
10736                if found {
10737                    continue;
10738                }
10739            }
10740
10741            for row in (0..=range.start.row).rev() {
10742                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10743                    if crease.range().end.row >= buffer_start_row {
10744                        to_fold.push(crease);
10745                    } else {
10746                        break;
10747                    }
10748                }
10749            }
10750        }
10751
10752        self.fold_creases(to_fold, true, cx);
10753    }
10754
10755    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10756        let buffer_row = fold_at.buffer_row;
10757        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10758
10759        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10760            let autoscroll = self
10761                .selections
10762                .all::<Point>(cx)
10763                .iter()
10764                .any(|selection| crease.range().overlaps(&selection.range()));
10765
10766            self.fold_creases(vec![crease], autoscroll, cx);
10767        }
10768    }
10769
10770    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10771        if self.is_singleton(cx) {
10772            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10773            let buffer = &display_map.buffer_snapshot;
10774            let selections = self.selections.all::<Point>(cx);
10775            let ranges = selections
10776                .iter()
10777                .map(|s| {
10778                    let range = s.display_range(&display_map).sorted();
10779                    let mut start = range.start.to_point(&display_map);
10780                    let mut end = range.end.to_point(&display_map);
10781                    start.column = 0;
10782                    end.column = buffer.line_len(MultiBufferRow(end.row));
10783                    start..end
10784                })
10785                .collect::<Vec<_>>();
10786
10787            self.unfold_ranges(&ranges, true, true, cx);
10788        } else {
10789            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10790            let mut unfolded_buffers = HashSet::default();
10791            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10792                self.selections
10793                    .disjoint_anchors()
10794                    .into_iter()
10795                    .map(|selection| selection.range()),
10796            ) {
10797                let buffer_id = buffer_snapshot.remote_id();
10798                if unfolded_buffers.insert(buffer_id) {
10799                    self.unfold_buffer(buffer_id, cx);
10800                }
10801            }
10802        }
10803    }
10804
10805    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10806        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10807        let selections = self.selections.all::<Point>(cx);
10808        let ranges = selections
10809            .iter()
10810            .map(|s| {
10811                let mut range = s.display_range(&display_map).sorted();
10812                *range.start.column_mut() = 0;
10813                *range.end.column_mut() = display_map.line_len(range.end.row());
10814                let start = range.start.to_point(&display_map);
10815                let end = range.end.to_point(&display_map);
10816                start..end
10817            })
10818            .collect::<Vec<_>>();
10819
10820        self.unfold_ranges(&ranges, true, true, cx);
10821    }
10822
10823    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10824        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10825
10826        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10827            ..Point::new(
10828                unfold_at.buffer_row.0,
10829                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10830            );
10831
10832        let autoscroll = self
10833            .selections
10834            .all::<Point>(cx)
10835            .iter()
10836            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10837
10838        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10839    }
10840
10841    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10842        if self.buffer.read(cx).is_singleton() {
10843            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10844            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10845        } else {
10846            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10847                editor
10848                    .update(&mut cx, |editor, cx| {
10849                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10850                            editor.unfold_buffer(buffer_id, cx);
10851                        }
10852                    })
10853                    .ok();
10854            });
10855        }
10856    }
10857
10858    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10859        let selections = self.selections.all::<Point>(cx);
10860        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10861        let line_mode = self.selections.line_mode;
10862        let ranges = selections
10863            .into_iter()
10864            .map(|s| {
10865                if line_mode {
10866                    let start = Point::new(s.start.row, 0);
10867                    let end = Point::new(
10868                        s.end.row,
10869                        display_map
10870                            .buffer_snapshot
10871                            .line_len(MultiBufferRow(s.end.row)),
10872                    );
10873                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10874                } else {
10875                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10876                }
10877            })
10878            .collect::<Vec<_>>();
10879        self.fold_creases(ranges, true, cx);
10880    }
10881
10882    pub fn fold_creases<T: ToOffset + Clone>(
10883        &mut self,
10884        creases: Vec<Crease<T>>,
10885        auto_scroll: bool,
10886        cx: &mut ViewContext<Self>,
10887    ) {
10888        if creases.is_empty() {
10889            return;
10890        }
10891
10892        let mut buffers_affected = HashSet::default();
10893        let multi_buffer = self.buffer().read(cx);
10894        for crease in &creases {
10895            if let Some((_, buffer, _)) =
10896                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10897            {
10898                buffers_affected.insert(buffer.read(cx).remote_id());
10899            };
10900        }
10901
10902        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10903
10904        if auto_scroll {
10905            self.request_autoscroll(Autoscroll::fit(), cx);
10906        }
10907
10908        for buffer_id in buffers_affected {
10909            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10910        }
10911
10912        cx.notify();
10913
10914        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10915            // Clear diagnostics block when folding a range that contains it.
10916            let snapshot = self.snapshot(cx);
10917            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10918                drop(snapshot);
10919                self.active_diagnostics = Some(active_diagnostics);
10920                self.dismiss_diagnostics(cx);
10921            } else {
10922                self.active_diagnostics = Some(active_diagnostics);
10923            }
10924        }
10925
10926        self.scrollbar_marker_state.dirty = true;
10927    }
10928
10929    /// Removes any folds whose ranges intersect any of the given ranges.
10930    pub fn unfold_ranges<T: ToOffset + Clone>(
10931        &mut self,
10932        ranges: &[Range<T>],
10933        inclusive: bool,
10934        auto_scroll: bool,
10935        cx: &mut ViewContext<Self>,
10936    ) {
10937        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10938            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10939        });
10940    }
10941
10942    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10943        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10944            return;
10945        }
10946        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10947            return;
10948        };
10949        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10950        self.display_map
10951            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10952        cx.emit(EditorEvent::BufferFoldToggled {
10953            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10954            folded: true,
10955        });
10956        cx.notify();
10957    }
10958
10959    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10960        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10961            return;
10962        }
10963        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10964            return;
10965        };
10966        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10967        self.display_map.update(cx, |display_map, cx| {
10968            display_map.unfold_buffer(buffer_id, cx);
10969        });
10970        cx.emit(EditorEvent::BufferFoldToggled {
10971            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10972            folded: false,
10973        });
10974        cx.notify();
10975    }
10976
10977    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10978        self.display_map.read(cx).buffer_folded(buffer)
10979    }
10980
10981    /// Removes any folds with the given ranges.
10982    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10983        &mut self,
10984        ranges: &[Range<T>],
10985        type_id: TypeId,
10986        auto_scroll: bool,
10987        cx: &mut ViewContext<Self>,
10988    ) {
10989        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10990            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10991        });
10992    }
10993
10994    fn remove_folds_with<T: ToOffset + Clone>(
10995        &mut self,
10996        ranges: &[Range<T>],
10997        auto_scroll: bool,
10998        cx: &mut ViewContext<Self>,
10999        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11000    ) {
11001        if ranges.is_empty() {
11002            return;
11003        }
11004
11005        let mut buffers_affected = HashSet::default();
11006        let multi_buffer = self.buffer().read(cx);
11007        for range in ranges {
11008            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11009                buffers_affected.insert(buffer.read(cx).remote_id());
11010            };
11011        }
11012
11013        self.display_map.update(cx, update);
11014
11015        if auto_scroll {
11016            self.request_autoscroll(Autoscroll::fit(), cx);
11017        }
11018
11019        for buffer_id in buffers_affected {
11020            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11021        }
11022
11023        cx.notify();
11024        self.scrollbar_marker_state.dirty = true;
11025        self.active_indent_guides_state.dirty = true;
11026    }
11027
11028    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11029        self.display_map.read(cx).fold_placeholder.clone()
11030    }
11031
11032    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11033        if hovered != self.gutter_hovered {
11034            self.gutter_hovered = hovered;
11035            cx.notify();
11036        }
11037    }
11038
11039    pub fn insert_blocks(
11040        &mut self,
11041        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11042        autoscroll: Option<Autoscroll>,
11043        cx: &mut ViewContext<Self>,
11044    ) -> Vec<CustomBlockId> {
11045        let blocks = self
11046            .display_map
11047            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11048        if let Some(autoscroll) = autoscroll {
11049            self.request_autoscroll(autoscroll, cx);
11050        }
11051        cx.notify();
11052        blocks
11053    }
11054
11055    pub fn resize_blocks(
11056        &mut self,
11057        heights: HashMap<CustomBlockId, u32>,
11058        autoscroll: Option<Autoscroll>,
11059        cx: &mut ViewContext<Self>,
11060    ) {
11061        self.display_map
11062            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11063        if let Some(autoscroll) = autoscroll {
11064            self.request_autoscroll(autoscroll, cx);
11065        }
11066        cx.notify();
11067    }
11068
11069    pub fn replace_blocks(
11070        &mut self,
11071        renderers: HashMap<CustomBlockId, RenderBlock>,
11072        autoscroll: Option<Autoscroll>,
11073        cx: &mut ViewContext<Self>,
11074    ) {
11075        self.display_map
11076            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11077        if let Some(autoscroll) = autoscroll {
11078            self.request_autoscroll(autoscroll, cx);
11079        }
11080        cx.notify();
11081    }
11082
11083    pub fn remove_blocks(
11084        &mut self,
11085        block_ids: HashSet<CustomBlockId>,
11086        autoscroll: Option<Autoscroll>,
11087        cx: &mut ViewContext<Self>,
11088    ) {
11089        self.display_map.update(cx, |display_map, cx| {
11090            display_map.remove_blocks(block_ids, cx)
11091        });
11092        if let Some(autoscroll) = autoscroll {
11093            self.request_autoscroll(autoscroll, cx);
11094        }
11095        cx.notify();
11096    }
11097
11098    pub fn row_for_block(
11099        &self,
11100        block_id: CustomBlockId,
11101        cx: &mut ViewContext<Self>,
11102    ) -> Option<DisplayRow> {
11103        self.display_map
11104            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11105    }
11106
11107    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11108        self.focused_block = Some(focused_block);
11109    }
11110
11111    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11112        self.focused_block.take()
11113    }
11114
11115    pub fn insert_creases(
11116        &mut self,
11117        creases: impl IntoIterator<Item = Crease<Anchor>>,
11118        cx: &mut ViewContext<Self>,
11119    ) -> Vec<CreaseId> {
11120        self.display_map
11121            .update(cx, |map, cx| map.insert_creases(creases, cx))
11122    }
11123
11124    pub fn remove_creases(
11125        &mut self,
11126        ids: impl IntoIterator<Item = CreaseId>,
11127        cx: &mut ViewContext<Self>,
11128    ) {
11129        self.display_map
11130            .update(cx, |map, cx| map.remove_creases(ids, cx));
11131    }
11132
11133    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11134        self.display_map
11135            .update(cx, |map, cx| map.snapshot(cx))
11136            .longest_row()
11137    }
11138
11139    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11140        self.display_map
11141            .update(cx, |map, cx| map.snapshot(cx))
11142            .max_point()
11143    }
11144
11145    pub fn text(&self, cx: &AppContext) -> String {
11146        self.buffer.read(cx).read(cx).text()
11147    }
11148
11149    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11150        let text = self.text(cx);
11151        let text = text.trim();
11152
11153        if text.is_empty() {
11154            return None;
11155        }
11156
11157        Some(text.to_string())
11158    }
11159
11160    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11161        self.transact(cx, |this, cx| {
11162            this.buffer
11163                .read(cx)
11164                .as_singleton()
11165                .expect("you can only call set_text on editors for singleton buffers")
11166                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11167        });
11168    }
11169
11170    pub fn display_text(&self, cx: &mut AppContext) -> String {
11171        self.display_map
11172            .update(cx, |map, cx| map.snapshot(cx))
11173            .text()
11174    }
11175
11176    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11177        let mut wrap_guides = smallvec::smallvec![];
11178
11179        if self.show_wrap_guides == Some(false) {
11180            return wrap_guides;
11181        }
11182
11183        let settings = self.buffer.read(cx).settings_at(0, cx);
11184        if settings.show_wrap_guides {
11185            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11186                wrap_guides.push((soft_wrap as usize, true));
11187            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11188                wrap_guides.push((soft_wrap as usize, true));
11189            }
11190            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11191        }
11192
11193        wrap_guides
11194    }
11195
11196    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11197        let settings = self.buffer.read(cx).settings_at(0, cx);
11198        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11199        match mode {
11200            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11201                SoftWrap::None
11202            }
11203            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11204            language_settings::SoftWrap::PreferredLineLength => {
11205                SoftWrap::Column(settings.preferred_line_length)
11206            }
11207            language_settings::SoftWrap::Bounded => {
11208                SoftWrap::Bounded(settings.preferred_line_length)
11209            }
11210        }
11211    }
11212
11213    pub fn set_soft_wrap_mode(
11214        &mut self,
11215        mode: language_settings::SoftWrap,
11216        cx: &mut ViewContext<Self>,
11217    ) {
11218        self.soft_wrap_mode_override = Some(mode);
11219        cx.notify();
11220    }
11221
11222    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11223        self.text_style_refinement = Some(style);
11224    }
11225
11226    /// called by the Element so we know what style we were most recently rendered with.
11227    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11228        let rem_size = cx.rem_size();
11229        self.display_map.update(cx, |map, cx| {
11230            map.set_font(
11231                style.text.font(),
11232                style.text.font_size.to_pixels(rem_size),
11233                cx,
11234            )
11235        });
11236        self.style = Some(style);
11237    }
11238
11239    pub fn style(&self) -> Option<&EditorStyle> {
11240        self.style.as_ref()
11241    }
11242
11243    // Called by the element. This method is not designed to be called outside of the editor
11244    // element's layout code because it does not notify when rewrapping is computed synchronously.
11245    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11246        self.display_map
11247            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11248    }
11249
11250    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11251        if self.soft_wrap_mode_override.is_some() {
11252            self.soft_wrap_mode_override.take();
11253        } else {
11254            let soft_wrap = match self.soft_wrap_mode(cx) {
11255                SoftWrap::GitDiff => return,
11256                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11257                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11258                    language_settings::SoftWrap::None
11259                }
11260            };
11261            self.soft_wrap_mode_override = Some(soft_wrap);
11262        }
11263        cx.notify();
11264    }
11265
11266    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11267        let Some(workspace) = self.workspace() else {
11268            return;
11269        };
11270        let fs = workspace.read(cx).app_state().fs.clone();
11271        let current_show = TabBarSettings::get_global(cx).show;
11272        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11273            setting.show = Some(!current_show);
11274        });
11275    }
11276
11277    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11278        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11279            self.buffer
11280                .read(cx)
11281                .settings_at(0, cx)
11282                .indent_guides
11283                .enabled
11284        });
11285        self.show_indent_guides = Some(!currently_enabled);
11286        cx.notify();
11287    }
11288
11289    fn should_show_indent_guides(&self) -> Option<bool> {
11290        self.show_indent_guides
11291    }
11292
11293    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11294        let mut editor_settings = EditorSettings::get_global(cx).clone();
11295        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11296        EditorSettings::override_global(editor_settings, cx);
11297    }
11298
11299    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11300        self.use_relative_line_numbers
11301            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11302    }
11303
11304    pub fn toggle_relative_line_numbers(
11305        &mut self,
11306        _: &ToggleRelativeLineNumbers,
11307        cx: &mut ViewContext<Self>,
11308    ) {
11309        let is_relative = self.should_use_relative_line_numbers(cx);
11310        self.set_relative_line_number(Some(!is_relative), cx)
11311    }
11312
11313    pub fn set_relative_line_number(
11314        &mut self,
11315        is_relative: Option<bool>,
11316        cx: &mut ViewContext<Self>,
11317    ) {
11318        self.use_relative_line_numbers = is_relative;
11319        cx.notify();
11320    }
11321
11322    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11323        self.show_gutter = show_gutter;
11324        cx.notify();
11325    }
11326
11327    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11328        self.show_scrollbars = show_scrollbars;
11329        cx.notify();
11330    }
11331
11332    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11333        self.show_line_numbers = Some(show_line_numbers);
11334        cx.notify();
11335    }
11336
11337    pub fn set_show_git_diff_gutter(
11338        &mut self,
11339        show_git_diff_gutter: bool,
11340        cx: &mut ViewContext<Self>,
11341    ) {
11342        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11343        cx.notify();
11344    }
11345
11346    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11347        self.show_code_actions = Some(show_code_actions);
11348        cx.notify();
11349    }
11350
11351    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11352        self.show_runnables = Some(show_runnables);
11353        cx.notify();
11354    }
11355
11356    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11357        if self.display_map.read(cx).masked != masked {
11358            self.display_map.update(cx, |map, _| map.masked = masked);
11359        }
11360        cx.notify()
11361    }
11362
11363    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11364        self.show_wrap_guides = Some(show_wrap_guides);
11365        cx.notify();
11366    }
11367
11368    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11369        self.show_indent_guides = Some(show_indent_guides);
11370        cx.notify();
11371    }
11372
11373    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11374        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11375            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11376                if let Some(dir) = file.abs_path(cx).parent() {
11377                    return Some(dir.to_owned());
11378                }
11379            }
11380
11381            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11382                return Some(project_path.path.to_path_buf());
11383            }
11384        }
11385
11386        None
11387    }
11388
11389    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11390        self.active_excerpt(cx)?
11391            .1
11392            .read(cx)
11393            .file()
11394            .and_then(|f| f.as_local())
11395    }
11396
11397    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11398        if let Some(target) = self.target_file(cx) {
11399            cx.reveal_path(&target.abs_path(cx));
11400        }
11401    }
11402
11403    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11404        if let Some(file) = self.target_file(cx) {
11405            if let Some(path) = file.abs_path(cx).to_str() {
11406                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11407            }
11408        }
11409    }
11410
11411    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11412        if let Some(file) = self.target_file(cx) {
11413            if let Some(path) = file.path().to_str() {
11414                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11415            }
11416        }
11417    }
11418
11419    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11420        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11421
11422        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11423            self.start_git_blame(true, cx);
11424        }
11425
11426        cx.notify();
11427    }
11428
11429    pub fn toggle_git_blame_inline(
11430        &mut self,
11431        _: &ToggleGitBlameInline,
11432        cx: &mut ViewContext<Self>,
11433    ) {
11434        self.toggle_git_blame_inline_internal(true, cx);
11435        cx.notify();
11436    }
11437
11438    pub fn git_blame_inline_enabled(&self) -> bool {
11439        self.git_blame_inline_enabled
11440    }
11441
11442    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11443        self.show_selection_menu = self
11444            .show_selection_menu
11445            .map(|show_selections_menu| !show_selections_menu)
11446            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11447
11448        cx.notify();
11449    }
11450
11451    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11452        self.show_selection_menu
11453            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11454    }
11455
11456    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11457        if let Some(project) = self.project.as_ref() {
11458            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11459                return;
11460            };
11461
11462            if buffer.read(cx).file().is_none() {
11463                return;
11464            }
11465
11466            let focused = self.focus_handle(cx).contains_focused(cx);
11467
11468            let project = project.clone();
11469            let blame =
11470                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11471            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11472            self.blame = Some(blame);
11473        }
11474    }
11475
11476    fn toggle_git_blame_inline_internal(
11477        &mut self,
11478        user_triggered: bool,
11479        cx: &mut ViewContext<Self>,
11480    ) {
11481        if self.git_blame_inline_enabled {
11482            self.git_blame_inline_enabled = false;
11483            self.show_git_blame_inline = false;
11484            self.show_git_blame_inline_delay_task.take();
11485        } else {
11486            self.git_blame_inline_enabled = true;
11487            self.start_git_blame_inline(user_triggered, cx);
11488        }
11489
11490        cx.notify();
11491    }
11492
11493    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11494        self.start_git_blame(user_triggered, cx);
11495
11496        if ProjectSettings::get_global(cx)
11497            .git
11498            .inline_blame_delay()
11499            .is_some()
11500        {
11501            self.start_inline_blame_timer(cx);
11502        } else {
11503            self.show_git_blame_inline = true
11504        }
11505    }
11506
11507    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11508        self.blame.as_ref()
11509    }
11510
11511    pub fn show_git_blame_gutter(&self) -> bool {
11512        self.show_git_blame_gutter
11513    }
11514
11515    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11516        self.show_git_blame_gutter && self.has_blame_entries(cx)
11517    }
11518
11519    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11520        self.show_git_blame_inline
11521            && self.focus_handle.is_focused(cx)
11522            && !self.newest_selection_head_on_empty_line(cx)
11523            && self.has_blame_entries(cx)
11524    }
11525
11526    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11527        self.blame()
11528            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11529    }
11530
11531    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11532        let cursor_anchor = self.selections.newest_anchor().head();
11533
11534        let snapshot = self.buffer.read(cx).snapshot(cx);
11535        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11536
11537        snapshot.line_len(buffer_row) == 0
11538    }
11539
11540    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11541        let buffer_and_selection = maybe!({
11542            let selection = self.selections.newest::<Point>(cx);
11543            let selection_range = selection.range();
11544
11545            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11546                (buffer, selection_range.start.row..selection_range.end.row)
11547            } else {
11548                let multi_buffer = self.buffer().read(cx);
11549                let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11550                let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11551
11552                let (excerpt, range) = if selection.reversed {
11553                    buffer_ranges.first()
11554                } else {
11555                    buffer_ranges.last()
11556                }?;
11557
11558                let snapshot = excerpt.buffer();
11559                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11560                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11561                (
11562                    multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11563                    selection,
11564                )
11565            };
11566
11567            Some((buffer, selection))
11568        });
11569
11570        let Some((buffer, selection)) = buffer_and_selection else {
11571            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11572        };
11573
11574        let Some(project) = self.project.as_ref() else {
11575            return Task::ready(Err(anyhow!("editor does not have project")));
11576        };
11577
11578        project.update(cx, |project, cx| {
11579            project.get_permalink_to_line(&buffer, selection, cx)
11580        })
11581    }
11582
11583    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11584        let permalink_task = self.get_permalink_to_line(cx);
11585        let workspace = self.workspace();
11586
11587        cx.spawn(|_, mut cx| async move {
11588            match permalink_task.await {
11589                Ok(permalink) => {
11590                    cx.update(|cx| {
11591                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11592                    })
11593                    .ok();
11594                }
11595                Err(err) => {
11596                    let message = format!("Failed to copy permalink: {err}");
11597
11598                    Err::<(), anyhow::Error>(err).log_err();
11599
11600                    if let Some(workspace) = workspace {
11601                        workspace
11602                            .update(&mut cx, |workspace, cx| {
11603                                struct CopyPermalinkToLine;
11604
11605                                workspace.show_toast(
11606                                    Toast::new(
11607                                        NotificationId::unique::<CopyPermalinkToLine>(),
11608                                        message,
11609                                    ),
11610                                    cx,
11611                                )
11612                            })
11613                            .ok();
11614                    }
11615                }
11616            }
11617        })
11618        .detach();
11619    }
11620
11621    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11622        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11623        if let Some(file) = self.target_file(cx) {
11624            if let Some(path) = file.path().to_str() {
11625                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11626            }
11627        }
11628    }
11629
11630    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11631        let permalink_task = self.get_permalink_to_line(cx);
11632        let workspace = self.workspace();
11633
11634        cx.spawn(|_, mut cx| async move {
11635            match permalink_task.await {
11636                Ok(permalink) => {
11637                    cx.update(|cx| {
11638                        cx.open_url(permalink.as_ref());
11639                    })
11640                    .ok();
11641                }
11642                Err(err) => {
11643                    let message = format!("Failed to open permalink: {err}");
11644
11645                    Err::<(), anyhow::Error>(err).log_err();
11646
11647                    if let Some(workspace) = workspace {
11648                        workspace
11649                            .update(&mut cx, |workspace, cx| {
11650                                struct OpenPermalinkToLine;
11651
11652                                workspace.show_toast(
11653                                    Toast::new(
11654                                        NotificationId::unique::<OpenPermalinkToLine>(),
11655                                        message,
11656                                    ),
11657                                    cx,
11658                                )
11659                            })
11660                            .ok();
11661                    }
11662                }
11663            }
11664        })
11665        .detach();
11666    }
11667
11668    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11669        self.insert_uuid(UuidVersion::V4, cx);
11670    }
11671
11672    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11673        self.insert_uuid(UuidVersion::V7, cx);
11674    }
11675
11676    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11677        self.transact(cx, |this, cx| {
11678            let edits = this
11679                .selections
11680                .all::<Point>(cx)
11681                .into_iter()
11682                .map(|selection| {
11683                    let uuid = match version {
11684                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11685                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11686                    };
11687
11688                    (selection.range(), uuid.to_string())
11689                });
11690            this.edit(edits, cx);
11691            this.refresh_inline_completion(true, false, cx);
11692        });
11693    }
11694
11695    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11696    /// last highlight added will be used.
11697    ///
11698    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11699    pub fn highlight_rows<T: 'static>(
11700        &mut self,
11701        range: Range<Anchor>,
11702        color: Hsla,
11703        should_autoscroll: bool,
11704        cx: &mut ViewContext<Self>,
11705    ) {
11706        let snapshot = self.buffer().read(cx).snapshot(cx);
11707        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11708        let ix = row_highlights.binary_search_by(|highlight| {
11709            Ordering::Equal
11710                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11711                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11712        });
11713
11714        if let Err(mut ix) = ix {
11715            let index = post_inc(&mut self.highlight_order);
11716
11717            // If this range intersects with the preceding highlight, then merge it with
11718            // the preceding highlight. Otherwise insert a new highlight.
11719            let mut merged = false;
11720            if ix > 0 {
11721                let prev_highlight = &mut row_highlights[ix - 1];
11722                if prev_highlight
11723                    .range
11724                    .end
11725                    .cmp(&range.start, &snapshot)
11726                    .is_ge()
11727                {
11728                    ix -= 1;
11729                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11730                        prev_highlight.range.end = range.end;
11731                    }
11732                    merged = true;
11733                    prev_highlight.index = index;
11734                    prev_highlight.color = color;
11735                    prev_highlight.should_autoscroll = should_autoscroll;
11736                }
11737            }
11738
11739            if !merged {
11740                row_highlights.insert(
11741                    ix,
11742                    RowHighlight {
11743                        range: range.clone(),
11744                        index,
11745                        color,
11746                        should_autoscroll,
11747                    },
11748                );
11749            }
11750
11751            // If any of the following highlights intersect with this one, merge them.
11752            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11753                let highlight = &row_highlights[ix];
11754                if next_highlight
11755                    .range
11756                    .start
11757                    .cmp(&highlight.range.end, &snapshot)
11758                    .is_le()
11759                {
11760                    if next_highlight
11761                        .range
11762                        .end
11763                        .cmp(&highlight.range.end, &snapshot)
11764                        .is_gt()
11765                    {
11766                        row_highlights[ix].range.end = next_highlight.range.end;
11767                    }
11768                    row_highlights.remove(ix + 1);
11769                } else {
11770                    break;
11771                }
11772            }
11773        }
11774    }
11775
11776    /// Remove any highlighted row ranges of the given type that intersect the
11777    /// given ranges.
11778    pub fn remove_highlighted_rows<T: 'static>(
11779        &mut self,
11780        ranges_to_remove: Vec<Range<Anchor>>,
11781        cx: &mut ViewContext<Self>,
11782    ) {
11783        let snapshot = self.buffer().read(cx).snapshot(cx);
11784        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11785        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11786        row_highlights.retain(|highlight| {
11787            while let Some(range_to_remove) = ranges_to_remove.peek() {
11788                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11789                    Ordering::Less | Ordering::Equal => {
11790                        ranges_to_remove.next();
11791                    }
11792                    Ordering::Greater => {
11793                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11794                            Ordering::Less | Ordering::Equal => {
11795                                return false;
11796                            }
11797                            Ordering::Greater => break,
11798                        }
11799                    }
11800                }
11801            }
11802
11803            true
11804        })
11805    }
11806
11807    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11808    pub fn clear_row_highlights<T: 'static>(&mut self) {
11809        self.highlighted_rows.remove(&TypeId::of::<T>());
11810    }
11811
11812    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11813    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11814        self.highlighted_rows
11815            .get(&TypeId::of::<T>())
11816            .map_or(&[] as &[_], |vec| vec.as_slice())
11817            .iter()
11818            .map(|highlight| (highlight.range.clone(), highlight.color))
11819    }
11820
11821    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11822    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11823    /// Allows to ignore certain kinds of highlights.
11824    pub fn highlighted_display_rows(
11825        &mut self,
11826        cx: &mut WindowContext,
11827    ) -> BTreeMap<DisplayRow, Hsla> {
11828        let snapshot = self.snapshot(cx);
11829        let mut used_highlight_orders = HashMap::default();
11830        self.highlighted_rows
11831            .iter()
11832            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11833            .fold(
11834                BTreeMap::<DisplayRow, Hsla>::new(),
11835                |mut unique_rows, highlight| {
11836                    let start = highlight.range.start.to_display_point(&snapshot);
11837                    let end = highlight.range.end.to_display_point(&snapshot);
11838                    let start_row = start.row().0;
11839                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11840                        && end.column() == 0
11841                    {
11842                        end.row().0.saturating_sub(1)
11843                    } else {
11844                        end.row().0
11845                    };
11846                    for row in start_row..=end_row {
11847                        let used_index =
11848                            used_highlight_orders.entry(row).or_insert(highlight.index);
11849                        if highlight.index >= *used_index {
11850                            *used_index = highlight.index;
11851                            unique_rows.insert(DisplayRow(row), highlight.color);
11852                        }
11853                    }
11854                    unique_rows
11855                },
11856            )
11857    }
11858
11859    pub fn highlighted_display_row_for_autoscroll(
11860        &self,
11861        snapshot: &DisplaySnapshot,
11862    ) -> Option<DisplayRow> {
11863        self.highlighted_rows
11864            .values()
11865            .flat_map(|highlighted_rows| highlighted_rows.iter())
11866            .filter_map(|highlight| {
11867                if highlight.should_autoscroll {
11868                    Some(highlight.range.start.to_display_point(snapshot).row())
11869                } else {
11870                    None
11871                }
11872            })
11873            .min()
11874    }
11875
11876    pub fn set_search_within_ranges(
11877        &mut self,
11878        ranges: &[Range<Anchor>],
11879        cx: &mut ViewContext<Self>,
11880    ) {
11881        self.highlight_background::<SearchWithinRange>(
11882            ranges,
11883            |colors| colors.editor_document_highlight_read_background,
11884            cx,
11885        )
11886    }
11887
11888    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11889        self.breadcrumb_header = Some(new_header);
11890    }
11891
11892    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11893        self.clear_background_highlights::<SearchWithinRange>(cx);
11894    }
11895
11896    pub fn highlight_background<T: 'static>(
11897        &mut self,
11898        ranges: &[Range<Anchor>],
11899        color_fetcher: fn(&ThemeColors) -> Hsla,
11900        cx: &mut ViewContext<Self>,
11901    ) {
11902        self.background_highlights
11903            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11904        self.scrollbar_marker_state.dirty = true;
11905        cx.notify();
11906    }
11907
11908    pub fn clear_background_highlights<T: 'static>(
11909        &mut self,
11910        cx: &mut ViewContext<Self>,
11911    ) -> Option<BackgroundHighlight> {
11912        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11913        if !text_highlights.1.is_empty() {
11914            self.scrollbar_marker_state.dirty = true;
11915            cx.notify();
11916        }
11917        Some(text_highlights)
11918    }
11919
11920    pub fn highlight_gutter<T: 'static>(
11921        &mut self,
11922        ranges: &[Range<Anchor>],
11923        color_fetcher: fn(&AppContext) -> Hsla,
11924        cx: &mut ViewContext<Self>,
11925    ) {
11926        self.gutter_highlights
11927            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11928        cx.notify();
11929    }
11930
11931    pub fn clear_gutter_highlights<T: 'static>(
11932        &mut self,
11933        cx: &mut ViewContext<Self>,
11934    ) -> Option<GutterHighlight> {
11935        cx.notify();
11936        self.gutter_highlights.remove(&TypeId::of::<T>())
11937    }
11938
11939    #[cfg(feature = "test-support")]
11940    pub fn all_text_background_highlights(
11941        &mut self,
11942        cx: &mut ViewContext<Self>,
11943    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11944        let snapshot = self.snapshot(cx);
11945        let buffer = &snapshot.buffer_snapshot;
11946        let start = buffer.anchor_before(0);
11947        let end = buffer.anchor_after(buffer.len());
11948        let theme = cx.theme().colors();
11949        self.background_highlights_in_range(start..end, &snapshot, theme)
11950    }
11951
11952    #[cfg(feature = "test-support")]
11953    pub fn search_background_highlights(
11954        &mut self,
11955        cx: &mut ViewContext<Self>,
11956    ) -> Vec<Range<Point>> {
11957        let snapshot = self.buffer().read(cx).snapshot(cx);
11958
11959        let highlights = self
11960            .background_highlights
11961            .get(&TypeId::of::<items::BufferSearchHighlights>());
11962
11963        if let Some((_color, ranges)) = highlights {
11964            ranges
11965                .iter()
11966                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11967                .collect_vec()
11968        } else {
11969            vec![]
11970        }
11971    }
11972
11973    fn document_highlights_for_position<'a>(
11974        &'a self,
11975        position: Anchor,
11976        buffer: &'a MultiBufferSnapshot,
11977    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11978        let read_highlights = self
11979            .background_highlights
11980            .get(&TypeId::of::<DocumentHighlightRead>())
11981            .map(|h| &h.1);
11982        let write_highlights = self
11983            .background_highlights
11984            .get(&TypeId::of::<DocumentHighlightWrite>())
11985            .map(|h| &h.1);
11986        let left_position = position.bias_left(buffer);
11987        let right_position = position.bias_right(buffer);
11988        read_highlights
11989            .into_iter()
11990            .chain(write_highlights)
11991            .flat_map(move |ranges| {
11992                let start_ix = match ranges.binary_search_by(|probe| {
11993                    let cmp = probe.end.cmp(&left_position, buffer);
11994                    if cmp.is_ge() {
11995                        Ordering::Greater
11996                    } else {
11997                        Ordering::Less
11998                    }
11999                }) {
12000                    Ok(i) | Err(i) => i,
12001                };
12002
12003                ranges[start_ix..]
12004                    .iter()
12005                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12006            })
12007    }
12008
12009    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12010        self.background_highlights
12011            .get(&TypeId::of::<T>())
12012            .map_or(false, |(_, highlights)| !highlights.is_empty())
12013    }
12014
12015    pub fn background_highlights_in_range(
12016        &self,
12017        search_range: Range<Anchor>,
12018        display_snapshot: &DisplaySnapshot,
12019        theme: &ThemeColors,
12020    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12021        let mut results = Vec::new();
12022        for (color_fetcher, ranges) in self.background_highlights.values() {
12023            let color = color_fetcher(theme);
12024            let start_ix = match ranges.binary_search_by(|probe| {
12025                let cmp = probe
12026                    .end
12027                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12028                if cmp.is_gt() {
12029                    Ordering::Greater
12030                } else {
12031                    Ordering::Less
12032                }
12033            }) {
12034                Ok(i) | Err(i) => i,
12035            };
12036            for range in &ranges[start_ix..] {
12037                if range
12038                    .start
12039                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12040                    .is_ge()
12041                {
12042                    break;
12043                }
12044
12045                let start = range.start.to_display_point(display_snapshot);
12046                let end = range.end.to_display_point(display_snapshot);
12047                results.push((start..end, color))
12048            }
12049        }
12050        results
12051    }
12052
12053    pub fn background_highlight_row_ranges<T: 'static>(
12054        &self,
12055        search_range: Range<Anchor>,
12056        display_snapshot: &DisplaySnapshot,
12057        count: usize,
12058    ) -> Vec<RangeInclusive<DisplayPoint>> {
12059        let mut results = Vec::new();
12060        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12061            return vec![];
12062        };
12063
12064        let start_ix = match ranges.binary_search_by(|probe| {
12065            let cmp = probe
12066                .end
12067                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12068            if cmp.is_gt() {
12069                Ordering::Greater
12070            } else {
12071                Ordering::Less
12072            }
12073        }) {
12074            Ok(i) | Err(i) => i,
12075        };
12076        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12077            if let (Some(start_display), Some(end_display)) = (start, end) {
12078                results.push(
12079                    start_display.to_display_point(display_snapshot)
12080                        ..=end_display.to_display_point(display_snapshot),
12081                );
12082            }
12083        };
12084        let mut start_row: Option<Point> = None;
12085        let mut end_row: Option<Point> = None;
12086        if ranges.len() > count {
12087            return Vec::new();
12088        }
12089        for range in &ranges[start_ix..] {
12090            if range
12091                .start
12092                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12093                .is_ge()
12094            {
12095                break;
12096            }
12097            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12098            if let Some(current_row) = &end_row {
12099                if end.row == current_row.row {
12100                    continue;
12101                }
12102            }
12103            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12104            if start_row.is_none() {
12105                assert_eq!(end_row, None);
12106                start_row = Some(start);
12107                end_row = Some(end);
12108                continue;
12109            }
12110            if let Some(current_end) = end_row.as_mut() {
12111                if start.row > current_end.row + 1 {
12112                    push_region(start_row, end_row);
12113                    start_row = Some(start);
12114                    end_row = Some(end);
12115                } else {
12116                    // Merge two hunks.
12117                    *current_end = end;
12118                }
12119            } else {
12120                unreachable!();
12121            }
12122        }
12123        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12124        push_region(start_row, end_row);
12125        results
12126    }
12127
12128    pub fn gutter_highlights_in_range(
12129        &self,
12130        search_range: Range<Anchor>,
12131        display_snapshot: &DisplaySnapshot,
12132        cx: &AppContext,
12133    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12134        let mut results = Vec::new();
12135        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12136            let color = color_fetcher(cx);
12137            let start_ix = match ranges.binary_search_by(|probe| {
12138                let cmp = probe
12139                    .end
12140                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12141                if cmp.is_gt() {
12142                    Ordering::Greater
12143                } else {
12144                    Ordering::Less
12145                }
12146            }) {
12147                Ok(i) | Err(i) => i,
12148            };
12149            for range in &ranges[start_ix..] {
12150                if range
12151                    .start
12152                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12153                    .is_ge()
12154                {
12155                    break;
12156                }
12157
12158                let start = range.start.to_display_point(display_snapshot);
12159                let end = range.end.to_display_point(display_snapshot);
12160                results.push((start..end, color))
12161            }
12162        }
12163        results
12164    }
12165
12166    /// Get the text ranges corresponding to the redaction query
12167    pub fn redacted_ranges(
12168        &self,
12169        search_range: Range<Anchor>,
12170        display_snapshot: &DisplaySnapshot,
12171        cx: &WindowContext,
12172    ) -> Vec<Range<DisplayPoint>> {
12173        display_snapshot
12174            .buffer_snapshot
12175            .redacted_ranges(search_range, |file| {
12176                if let Some(file) = file {
12177                    file.is_private()
12178                        && EditorSettings::get(
12179                            Some(SettingsLocation {
12180                                worktree_id: file.worktree_id(cx),
12181                                path: file.path().as_ref(),
12182                            }),
12183                            cx,
12184                        )
12185                        .redact_private_values
12186                } else {
12187                    false
12188                }
12189            })
12190            .map(|range| {
12191                range.start.to_display_point(display_snapshot)
12192                    ..range.end.to_display_point(display_snapshot)
12193            })
12194            .collect()
12195    }
12196
12197    pub fn highlight_text<T: 'static>(
12198        &mut self,
12199        ranges: Vec<Range<Anchor>>,
12200        style: HighlightStyle,
12201        cx: &mut ViewContext<Self>,
12202    ) {
12203        self.display_map.update(cx, |map, _| {
12204            map.highlight_text(TypeId::of::<T>(), ranges, style)
12205        });
12206        cx.notify();
12207    }
12208
12209    pub(crate) fn highlight_inlays<T: 'static>(
12210        &mut self,
12211        highlights: Vec<InlayHighlight>,
12212        style: HighlightStyle,
12213        cx: &mut ViewContext<Self>,
12214    ) {
12215        self.display_map.update(cx, |map, _| {
12216            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12217        });
12218        cx.notify();
12219    }
12220
12221    pub fn text_highlights<'a, T: 'static>(
12222        &'a self,
12223        cx: &'a AppContext,
12224    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12225        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12226    }
12227
12228    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12229        let cleared = self
12230            .display_map
12231            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12232        if cleared {
12233            cx.notify();
12234        }
12235    }
12236
12237    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12238        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12239            && self.focus_handle.is_focused(cx)
12240    }
12241
12242    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12243        self.show_cursor_when_unfocused = is_enabled;
12244        cx.notify();
12245    }
12246
12247    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12248        self.project
12249            .as_ref()
12250            .map(|project| project.read(cx).lsp_store())
12251    }
12252
12253    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12254        cx.notify();
12255    }
12256
12257    fn on_buffer_event(
12258        &mut self,
12259        multibuffer: Model<MultiBuffer>,
12260        event: &multi_buffer::Event,
12261        cx: &mut ViewContext<Self>,
12262    ) {
12263        match event {
12264            multi_buffer::Event::Edited {
12265                singleton_buffer_edited,
12266                edited_buffer: buffer_edited,
12267            } => {
12268                self.scrollbar_marker_state.dirty = true;
12269                self.active_indent_guides_state.dirty = true;
12270                self.refresh_active_diagnostics(cx);
12271                self.refresh_code_actions(cx);
12272                if self.has_active_inline_completion() {
12273                    self.update_visible_inline_completion(cx);
12274                }
12275                if let Some(buffer) = buffer_edited {
12276                    let buffer_id = buffer.read(cx).remote_id();
12277                    if !self.registered_buffers.contains_key(&buffer_id) {
12278                        if let Some(lsp_store) = self.lsp_store(cx) {
12279                            lsp_store.update(cx, |lsp_store, cx| {
12280                                self.registered_buffers.insert(
12281                                    buffer_id,
12282                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12283                                );
12284                            })
12285                        }
12286                    }
12287                }
12288                cx.emit(EditorEvent::BufferEdited);
12289                cx.emit(SearchEvent::MatchesInvalidated);
12290                if *singleton_buffer_edited {
12291                    if let Some(project) = &self.project {
12292                        let project = project.read(cx);
12293                        #[allow(clippy::mutable_key_type)]
12294                        let languages_affected = multibuffer
12295                            .read(cx)
12296                            .all_buffers()
12297                            .into_iter()
12298                            .filter_map(|buffer| {
12299                                let buffer = buffer.read(cx);
12300                                let language = buffer.language()?;
12301                                if project.is_local()
12302                                    && project
12303                                        .language_servers_for_local_buffer(buffer, cx)
12304                                        .count()
12305                                        == 0
12306                                {
12307                                    None
12308                                } else {
12309                                    Some(language)
12310                                }
12311                            })
12312                            .cloned()
12313                            .collect::<HashSet<_>>();
12314                        if !languages_affected.is_empty() {
12315                            self.refresh_inlay_hints(
12316                                InlayHintRefreshReason::BufferEdited(languages_affected),
12317                                cx,
12318                            );
12319                        }
12320                    }
12321                }
12322
12323                let Some(project) = &self.project else { return };
12324                let (telemetry, is_via_ssh) = {
12325                    let project = project.read(cx);
12326                    let telemetry = project.client().telemetry().clone();
12327                    let is_via_ssh = project.is_via_ssh();
12328                    (telemetry, is_via_ssh)
12329                };
12330                refresh_linked_ranges(self, cx);
12331                telemetry.log_edit_event("editor", is_via_ssh);
12332            }
12333            multi_buffer::Event::ExcerptsAdded {
12334                buffer,
12335                predecessor,
12336                excerpts,
12337            } => {
12338                self.tasks_update_task = Some(self.refresh_runnables(cx));
12339                let buffer_id = buffer.read(cx).remote_id();
12340                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12341                    if let Some(project) = &self.project {
12342                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12343                    }
12344                }
12345                cx.emit(EditorEvent::ExcerptsAdded {
12346                    buffer: buffer.clone(),
12347                    predecessor: *predecessor,
12348                    excerpts: excerpts.clone(),
12349                });
12350                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12351            }
12352            multi_buffer::Event::ExcerptsRemoved { ids } => {
12353                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12354                let buffer = self.buffer.read(cx);
12355                self.registered_buffers
12356                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12357                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12358            }
12359            multi_buffer::Event::ExcerptsEdited { ids } => {
12360                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12361            }
12362            multi_buffer::Event::ExcerptsExpanded { ids } => {
12363                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12364            }
12365            multi_buffer::Event::Reparsed(buffer_id) => {
12366                self.tasks_update_task = Some(self.refresh_runnables(cx));
12367
12368                cx.emit(EditorEvent::Reparsed(*buffer_id));
12369            }
12370            multi_buffer::Event::LanguageChanged(buffer_id) => {
12371                linked_editing_ranges::refresh_linked_ranges(self, cx);
12372                cx.emit(EditorEvent::Reparsed(*buffer_id));
12373                cx.notify();
12374            }
12375            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12376            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12377            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12378                cx.emit(EditorEvent::TitleChanged)
12379            }
12380            // multi_buffer::Event::DiffBaseChanged => {
12381            //     self.scrollbar_marker_state.dirty = true;
12382            //     cx.emit(EditorEvent::DiffBaseChanged);
12383            //     cx.notify();
12384            // }
12385            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12386            multi_buffer::Event::DiagnosticsUpdated => {
12387                self.refresh_active_diagnostics(cx);
12388                self.scrollbar_marker_state.dirty = true;
12389                cx.notify();
12390            }
12391            _ => {}
12392        };
12393    }
12394
12395    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12396        cx.notify();
12397    }
12398
12399    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12400        self.tasks_update_task = Some(self.refresh_runnables(cx));
12401        self.refresh_inline_completion(true, false, cx);
12402        self.refresh_inlay_hints(
12403            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12404                self.selections.newest_anchor().head(),
12405                &self.buffer.read(cx).snapshot(cx),
12406                cx,
12407            )),
12408            cx,
12409        );
12410
12411        let old_cursor_shape = self.cursor_shape;
12412
12413        {
12414            let editor_settings = EditorSettings::get_global(cx);
12415            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12416            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12417            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12418        }
12419
12420        if old_cursor_shape != self.cursor_shape {
12421            cx.emit(EditorEvent::CursorShapeChanged);
12422        }
12423
12424        let project_settings = ProjectSettings::get_global(cx);
12425        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12426
12427        if self.mode == EditorMode::Full {
12428            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12429            if self.git_blame_inline_enabled != inline_blame_enabled {
12430                self.toggle_git_blame_inline_internal(false, cx);
12431            }
12432        }
12433
12434        cx.notify();
12435    }
12436
12437    pub fn set_searchable(&mut self, searchable: bool) {
12438        self.searchable = searchable;
12439    }
12440
12441    pub fn searchable(&self) -> bool {
12442        self.searchable
12443    }
12444
12445    fn open_proposed_changes_editor(
12446        &mut self,
12447        _: &OpenProposedChangesEditor,
12448        cx: &mut ViewContext<Self>,
12449    ) {
12450        let Some(workspace) = self.workspace() else {
12451            cx.propagate();
12452            return;
12453        };
12454
12455        let selections = self.selections.all::<usize>(cx);
12456        let multi_buffer = self.buffer.read(cx);
12457        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12458        let mut new_selections_by_buffer = HashMap::default();
12459        for selection in selections {
12460            for (excerpt, range) in
12461                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12462            {
12463                let mut range = range.to_point(excerpt.buffer());
12464                range.start.column = 0;
12465                range.end.column = excerpt.buffer().line_len(range.end.row);
12466                new_selections_by_buffer
12467                    .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12468                    .or_insert(Vec::new())
12469                    .push(range)
12470            }
12471        }
12472
12473        let proposed_changes_buffers = new_selections_by_buffer
12474            .into_iter()
12475            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12476            .collect::<Vec<_>>();
12477        let proposed_changes_editor = cx.new_view(|cx| {
12478            ProposedChangesEditor::new(
12479                "Proposed changes",
12480                proposed_changes_buffers,
12481                self.project.clone(),
12482                cx,
12483            )
12484        });
12485
12486        cx.window_context().defer(move |cx| {
12487            workspace.update(cx, |workspace, cx| {
12488                workspace.active_pane().update(cx, |pane, cx| {
12489                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12490                });
12491            });
12492        });
12493    }
12494
12495    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12496        self.open_excerpts_common(None, true, cx)
12497    }
12498
12499    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12500        self.open_excerpts_common(None, false, cx)
12501    }
12502
12503    fn open_excerpts_common(
12504        &mut self,
12505        jump_data: Option<JumpData>,
12506        split: bool,
12507        cx: &mut ViewContext<Self>,
12508    ) {
12509        let Some(workspace) = self.workspace() else {
12510            cx.propagate();
12511            return;
12512        };
12513
12514        if self.buffer.read(cx).is_singleton() {
12515            cx.propagate();
12516            return;
12517        }
12518
12519        let mut new_selections_by_buffer = HashMap::default();
12520        match &jump_data {
12521            Some(JumpData::MultiBufferPoint {
12522                excerpt_id,
12523                position,
12524                anchor,
12525                line_offset_from_top,
12526            }) => {
12527                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12528                if let Some(buffer) = multi_buffer_snapshot
12529                    .buffer_id_for_excerpt(*excerpt_id)
12530                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12531                {
12532                    let buffer_snapshot = buffer.read(cx).snapshot();
12533                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12534                        language::ToPoint::to_point(anchor, &buffer_snapshot)
12535                    } else {
12536                        buffer_snapshot.clip_point(*position, Bias::Left)
12537                    };
12538                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12539                    new_selections_by_buffer.insert(
12540                        buffer,
12541                        (
12542                            vec![jump_to_offset..jump_to_offset],
12543                            Some(*line_offset_from_top),
12544                        ),
12545                    );
12546                }
12547            }
12548            Some(JumpData::MultiBufferRow {
12549                row,
12550                line_offset_from_top,
12551            }) => {
12552                let point = MultiBufferPoint::new(row.0, 0);
12553                if let Some((buffer, buffer_point, _)) =
12554                    self.buffer.read(cx).point_to_buffer_point(point, cx)
12555                {
12556                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12557                    new_selections_by_buffer
12558                        .entry(buffer)
12559                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
12560                        .0
12561                        .push(buffer_offset..buffer_offset)
12562                }
12563            }
12564            None => {
12565                let selections = self.selections.all::<usize>(cx);
12566                let multi_buffer = self.buffer.read(cx);
12567                for selection in selections {
12568                    for (excerpt, mut range) in multi_buffer
12569                        .snapshot(cx)
12570                        .range_to_buffer_ranges(selection.range())
12571                    {
12572                        // When editing branch buffers, jump to the corresponding location
12573                        // in their base buffer.
12574                        let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12575                        let buffer = buffer_handle.read(cx);
12576                        if let Some(base_buffer) = buffer.base_buffer() {
12577                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12578                            buffer_handle = base_buffer;
12579                        }
12580
12581                        if selection.reversed {
12582                            mem::swap(&mut range.start, &mut range.end);
12583                        }
12584                        new_selections_by_buffer
12585                            .entry(buffer_handle)
12586                            .or_insert((Vec::new(), None))
12587                            .0
12588                            .push(range)
12589                    }
12590                }
12591            }
12592        }
12593
12594        if new_selections_by_buffer.is_empty() {
12595            return;
12596        }
12597
12598        // We defer the pane interaction because we ourselves are a workspace item
12599        // and activating a new item causes the pane to call a method on us reentrantly,
12600        // which panics if we're on the stack.
12601        cx.window_context().defer(move |cx| {
12602            workspace.update(cx, |workspace, cx| {
12603                let pane = if split {
12604                    workspace.adjacent_pane(cx)
12605                } else {
12606                    workspace.active_pane().clone()
12607                };
12608
12609                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12610                    let editor = buffer
12611                        .read(cx)
12612                        .file()
12613                        .is_none()
12614                        .then(|| {
12615                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12616                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12617                            // Instead, we try to activate the existing editor in the pane first.
12618                            let (editor, pane_item_index) =
12619                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12620                                    let editor = item.downcast::<Editor>()?;
12621                                    let singleton_buffer =
12622                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12623                                    if singleton_buffer == buffer {
12624                                        Some((editor, i))
12625                                    } else {
12626                                        None
12627                                    }
12628                                })?;
12629                            pane.update(cx, |pane, cx| {
12630                                pane.activate_item(pane_item_index, true, true, cx)
12631                            });
12632                            Some(editor)
12633                        })
12634                        .flatten()
12635                        .unwrap_or_else(|| {
12636                            workspace.open_project_item::<Self>(
12637                                pane.clone(),
12638                                buffer,
12639                                true,
12640                                true,
12641                                cx,
12642                            )
12643                        });
12644
12645                    editor.update(cx, |editor, cx| {
12646                        let autoscroll = match scroll_offset {
12647                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12648                            None => Autoscroll::newest(),
12649                        };
12650                        let nav_history = editor.nav_history.take();
12651                        editor.change_selections(Some(autoscroll), cx, |s| {
12652                            s.select_ranges(ranges);
12653                        });
12654                        editor.nav_history = nav_history;
12655                    });
12656                }
12657            })
12658        });
12659    }
12660
12661    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12662        let snapshot = self.buffer.read(cx).read(cx);
12663        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12664        Some(
12665            ranges
12666                .iter()
12667                .map(move |range| {
12668                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12669                })
12670                .collect(),
12671        )
12672    }
12673
12674    fn selection_replacement_ranges(
12675        &self,
12676        range: Range<OffsetUtf16>,
12677        cx: &mut AppContext,
12678    ) -> Vec<Range<OffsetUtf16>> {
12679        let selections = self.selections.all::<OffsetUtf16>(cx);
12680        let newest_selection = selections
12681            .iter()
12682            .max_by_key(|selection| selection.id)
12683            .unwrap();
12684        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12685        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12686        let snapshot = self.buffer.read(cx).read(cx);
12687        selections
12688            .into_iter()
12689            .map(|mut selection| {
12690                selection.start.0 =
12691                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12692                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12693                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12694                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12695            })
12696            .collect()
12697    }
12698
12699    fn report_editor_event(
12700        &self,
12701        event_type: &'static str,
12702        file_extension: Option<String>,
12703        cx: &AppContext,
12704    ) {
12705        if cfg!(any(test, feature = "test-support")) {
12706            return;
12707        }
12708
12709        let Some(project) = &self.project else { return };
12710
12711        // If None, we are in a file without an extension
12712        let file = self
12713            .buffer
12714            .read(cx)
12715            .as_singleton()
12716            .and_then(|b| b.read(cx).file());
12717        let file_extension = file_extension.or(file
12718            .as_ref()
12719            .and_then(|file| Path::new(file.file_name(cx)).extension())
12720            .and_then(|e| e.to_str())
12721            .map(|a| a.to_string()));
12722
12723        let vim_mode = cx
12724            .global::<SettingsStore>()
12725            .raw_user_settings()
12726            .get("vim_mode")
12727            == Some(&serde_json::Value::Bool(true));
12728
12729        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12730            == language::language_settings::InlineCompletionProvider::Copilot;
12731        let copilot_enabled_for_language = self
12732            .buffer
12733            .read(cx)
12734            .settings_at(0, cx)
12735            .show_inline_completions;
12736
12737        let project = project.read(cx);
12738        telemetry::event!(
12739            event_type,
12740            file_extension,
12741            vim_mode,
12742            copilot_enabled,
12743            copilot_enabled_for_language,
12744            is_via_ssh = project.is_via_ssh(),
12745        );
12746    }
12747
12748    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12749    /// with each line being an array of {text, highlight} objects.
12750    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12751        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12752            return;
12753        };
12754
12755        #[derive(Serialize)]
12756        struct Chunk<'a> {
12757            text: String,
12758            highlight: Option<&'a str>,
12759        }
12760
12761        let snapshot = buffer.read(cx).snapshot();
12762        let range = self
12763            .selected_text_range(false, cx)
12764            .and_then(|selection| {
12765                if selection.range.is_empty() {
12766                    None
12767                } else {
12768                    Some(selection.range)
12769                }
12770            })
12771            .unwrap_or_else(|| 0..snapshot.len());
12772
12773        let chunks = snapshot.chunks(range, true);
12774        let mut lines = Vec::new();
12775        let mut line: VecDeque<Chunk> = VecDeque::new();
12776
12777        let Some(style) = self.style.as_ref() else {
12778            return;
12779        };
12780
12781        for chunk in chunks {
12782            let highlight = chunk
12783                .syntax_highlight_id
12784                .and_then(|id| id.name(&style.syntax));
12785            let mut chunk_lines = chunk.text.split('\n').peekable();
12786            while let Some(text) = chunk_lines.next() {
12787                let mut merged_with_last_token = false;
12788                if let Some(last_token) = line.back_mut() {
12789                    if last_token.highlight == highlight {
12790                        last_token.text.push_str(text);
12791                        merged_with_last_token = true;
12792                    }
12793                }
12794
12795                if !merged_with_last_token {
12796                    line.push_back(Chunk {
12797                        text: text.into(),
12798                        highlight,
12799                    });
12800                }
12801
12802                if chunk_lines.peek().is_some() {
12803                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12804                        line.pop_front();
12805                    }
12806                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12807                        line.pop_back();
12808                    }
12809
12810                    lines.push(mem::take(&mut line));
12811                }
12812            }
12813        }
12814
12815        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12816            return;
12817        };
12818        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12819    }
12820
12821    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12822        self.request_autoscroll(Autoscroll::newest(), cx);
12823        let position = self.selections.newest_display(cx).start;
12824        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12825    }
12826
12827    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12828        &self.inlay_hint_cache
12829    }
12830
12831    pub fn replay_insert_event(
12832        &mut self,
12833        text: &str,
12834        relative_utf16_range: Option<Range<isize>>,
12835        cx: &mut ViewContext<Self>,
12836    ) {
12837        if !self.input_enabled {
12838            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12839            return;
12840        }
12841        if let Some(relative_utf16_range) = relative_utf16_range {
12842            let selections = self.selections.all::<OffsetUtf16>(cx);
12843            self.change_selections(None, cx, |s| {
12844                let new_ranges = selections.into_iter().map(|range| {
12845                    let start = OffsetUtf16(
12846                        range
12847                            .head()
12848                            .0
12849                            .saturating_add_signed(relative_utf16_range.start),
12850                    );
12851                    let end = OffsetUtf16(
12852                        range
12853                            .head()
12854                            .0
12855                            .saturating_add_signed(relative_utf16_range.end),
12856                    );
12857                    start..end
12858                });
12859                s.select_ranges(new_ranges);
12860            });
12861        }
12862
12863        self.handle_input(text, cx);
12864    }
12865
12866    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12867        let Some(provider) = self.semantics_provider.as_ref() else {
12868            return false;
12869        };
12870
12871        let mut supports = false;
12872        self.buffer().read(cx).for_each_buffer(|buffer| {
12873            supports |= provider.supports_inlay_hints(buffer, cx);
12874        });
12875        supports
12876    }
12877
12878    pub fn focus(&self, cx: &mut WindowContext) {
12879        cx.focus(&self.focus_handle)
12880    }
12881
12882    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12883        self.focus_handle.is_focused(cx)
12884    }
12885
12886    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12887        cx.emit(EditorEvent::Focused);
12888
12889        if let Some(descendant) = self
12890            .last_focused_descendant
12891            .take()
12892            .and_then(|descendant| descendant.upgrade())
12893        {
12894            cx.focus(&descendant);
12895        } else {
12896            if let Some(blame) = self.blame.as_ref() {
12897                blame.update(cx, GitBlame::focus)
12898            }
12899
12900            self.blink_manager.update(cx, BlinkManager::enable);
12901            self.show_cursor_names(cx);
12902            self.buffer.update(cx, |buffer, cx| {
12903                buffer.finalize_last_transaction(cx);
12904                if self.leader_peer_id.is_none() {
12905                    buffer.set_active_selections(
12906                        &self.selections.disjoint_anchors(),
12907                        self.selections.line_mode,
12908                        self.cursor_shape,
12909                        cx,
12910                    );
12911                }
12912            });
12913        }
12914    }
12915
12916    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12917        cx.emit(EditorEvent::FocusedIn)
12918    }
12919
12920    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12921        if event.blurred != self.focus_handle {
12922            self.last_focused_descendant = Some(event.blurred);
12923        }
12924    }
12925
12926    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12927        self.blink_manager.update(cx, BlinkManager::disable);
12928        self.buffer
12929            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12930
12931        if let Some(blame) = self.blame.as_ref() {
12932            blame.update(cx, GitBlame::blur)
12933        }
12934        if !self.hover_state.focused(cx) {
12935            hide_hover(self, cx);
12936        }
12937
12938        self.hide_context_menu(cx);
12939        cx.emit(EditorEvent::Blurred);
12940        cx.notify();
12941    }
12942
12943    pub fn register_action<A: Action>(
12944        &mut self,
12945        listener: impl Fn(&A, &mut WindowContext) + 'static,
12946    ) -> Subscription {
12947        let id = self.next_editor_action_id.post_inc();
12948        let listener = Arc::new(listener);
12949        self.editor_actions.borrow_mut().insert(
12950            id,
12951            Box::new(move |cx| {
12952                let cx = cx.window_context();
12953                let listener = listener.clone();
12954                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12955                    let action = action.downcast_ref().unwrap();
12956                    if phase == DispatchPhase::Bubble {
12957                        listener(action, cx)
12958                    }
12959                })
12960            }),
12961        );
12962
12963        let editor_actions = self.editor_actions.clone();
12964        Subscription::new(move || {
12965            editor_actions.borrow_mut().remove(&id);
12966        })
12967    }
12968
12969    pub fn file_header_size(&self) -> u32 {
12970        FILE_HEADER_HEIGHT
12971    }
12972
12973    pub fn revert(
12974        &mut self,
12975        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12976        cx: &mut ViewContext<Self>,
12977    ) {
12978        self.buffer().update(cx, |multi_buffer, cx| {
12979            for (buffer_id, changes) in revert_changes {
12980                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12981                    buffer.update(cx, |buffer, cx| {
12982                        buffer.edit(
12983                            changes.into_iter().map(|(range, text)| {
12984                                (range, text.to_string().map(Arc::<str>::from))
12985                            }),
12986                            None,
12987                            cx,
12988                        );
12989                    });
12990                }
12991            }
12992        });
12993        self.change_selections(None, cx, |selections| selections.refresh());
12994    }
12995
12996    pub fn to_pixel_point(
12997        &mut self,
12998        source: multi_buffer::Anchor,
12999        editor_snapshot: &EditorSnapshot,
13000        cx: &mut ViewContext<Self>,
13001    ) -> Option<gpui::Point<Pixels>> {
13002        let source_point = source.to_display_point(editor_snapshot);
13003        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13004    }
13005
13006    pub fn display_to_pixel_point(
13007        &self,
13008        source: DisplayPoint,
13009        editor_snapshot: &EditorSnapshot,
13010        cx: &WindowContext,
13011    ) -> Option<gpui::Point<Pixels>> {
13012        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13013        let text_layout_details = self.text_layout_details(cx);
13014        let scroll_top = text_layout_details
13015            .scroll_anchor
13016            .scroll_position(editor_snapshot)
13017            .y;
13018
13019        if source.row().as_f32() < scroll_top.floor() {
13020            return None;
13021        }
13022        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13023        let source_y = line_height * (source.row().as_f32() - scroll_top);
13024        Some(gpui::Point::new(source_x, source_y))
13025    }
13026
13027    pub fn has_active_completions_menu(&self) -> bool {
13028        self.context_menu.borrow().as_ref().map_or(false, |menu| {
13029            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13030        })
13031    }
13032
13033    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13034        self.addons
13035            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13036    }
13037
13038    pub fn unregister_addon<T: Addon>(&mut self) {
13039        self.addons.remove(&std::any::TypeId::of::<T>());
13040    }
13041
13042    pub fn addon<T: Addon>(&self) -> Option<&T> {
13043        let type_id = std::any::TypeId::of::<T>();
13044        self.addons
13045            .get(&type_id)
13046            .and_then(|item| item.to_any().downcast_ref::<T>())
13047    }
13048
13049    pub fn add_change_set(
13050        &mut self,
13051        change_set: Model<BufferChangeSet>,
13052        cx: &mut ViewContext<Self>,
13053    ) {
13054        self.diff_map.add_change_set(change_set, cx);
13055    }
13056
13057    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13058        let text_layout_details = self.text_layout_details(cx);
13059        let style = &text_layout_details.editor_style;
13060        let font_id = cx.text_system().resolve_font(&style.text.font());
13061        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13062        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13063
13064        let em_width = cx
13065            .text_system()
13066            .typographic_bounds(font_id, font_size, 'm')
13067            .unwrap()
13068            .size
13069            .width;
13070
13071        gpui::Point::new(em_width, line_height)
13072    }
13073}
13074
13075fn get_unstaged_changes_for_buffers(
13076    project: &Model<Project>,
13077    buffers: impl IntoIterator<Item = Model<Buffer>>,
13078    cx: &mut ViewContext<Editor>,
13079) {
13080    let mut tasks = Vec::new();
13081    project.update(cx, |project, cx| {
13082        for buffer in buffers {
13083            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13084        }
13085    });
13086    cx.spawn(|this, mut cx| async move {
13087        let change_sets = futures::future::join_all(tasks).await;
13088        this.update(&mut cx, |this, cx| {
13089            for change_set in change_sets {
13090                if let Some(change_set) = change_set.log_err() {
13091                    this.diff_map.add_change_set(change_set, cx);
13092                }
13093            }
13094        })
13095        .ok();
13096    })
13097    .detach();
13098}
13099
13100fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13101    let tab_size = tab_size.get() as usize;
13102    let mut width = offset;
13103
13104    for ch in text.chars() {
13105        width += if ch == '\t' {
13106            tab_size - (width % tab_size)
13107        } else {
13108            1
13109        };
13110    }
13111
13112    width - offset
13113}
13114
13115#[cfg(test)]
13116mod tests {
13117    use super::*;
13118
13119    #[test]
13120    fn test_string_size_with_expanded_tabs() {
13121        let nz = |val| NonZeroU32::new(val).unwrap();
13122        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13123        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13124        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13125        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13126        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13127        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13128        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13129        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13130    }
13131}
13132
13133/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13134struct WordBreakingTokenizer<'a> {
13135    input: &'a str,
13136}
13137
13138impl<'a> WordBreakingTokenizer<'a> {
13139    fn new(input: &'a str) -> Self {
13140        Self { input }
13141    }
13142}
13143
13144fn is_char_ideographic(ch: char) -> bool {
13145    use unicode_script::Script::*;
13146    use unicode_script::UnicodeScript;
13147    matches!(ch.script(), Han | Tangut | Yi)
13148}
13149
13150fn is_grapheme_ideographic(text: &str) -> bool {
13151    text.chars().any(is_char_ideographic)
13152}
13153
13154fn is_grapheme_whitespace(text: &str) -> bool {
13155    text.chars().any(|x| x.is_whitespace())
13156}
13157
13158fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13159    text.chars().next().map_or(false, |ch| {
13160        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13161    })
13162}
13163
13164#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13165struct WordBreakToken<'a> {
13166    token: &'a str,
13167    grapheme_len: usize,
13168    is_whitespace: bool,
13169}
13170
13171impl<'a> Iterator for WordBreakingTokenizer<'a> {
13172    /// Yields a span, the count of graphemes in the token, and whether it was
13173    /// whitespace. Note that it also breaks at word boundaries.
13174    type Item = WordBreakToken<'a>;
13175
13176    fn next(&mut self) -> Option<Self::Item> {
13177        use unicode_segmentation::UnicodeSegmentation;
13178        if self.input.is_empty() {
13179            return None;
13180        }
13181
13182        let mut iter = self.input.graphemes(true).peekable();
13183        let mut offset = 0;
13184        let mut graphemes = 0;
13185        if let Some(first_grapheme) = iter.next() {
13186            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13187            offset += first_grapheme.len();
13188            graphemes += 1;
13189            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13190                if let Some(grapheme) = iter.peek().copied() {
13191                    if should_stay_with_preceding_ideograph(grapheme) {
13192                        offset += grapheme.len();
13193                        graphemes += 1;
13194                    }
13195                }
13196            } else {
13197                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13198                let mut next_word_bound = words.peek().copied();
13199                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13200                    next_word_bound = words.next();
13201                }
13202                while let Some(grapheme) = iter.peek().copied() {
13203                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13204                        break;
13205                    };
13206                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13207                        break;
13208                    };
13209                    offset += grapheme.len();
13210                    graphemes += 1;
13211                    iter.next();
13212                }
13213            }
13214            let token = &self.input[..offset];
13215            self.input = &self.input[offset..];
13216            if is_whitespace {
13217                Some(WordBreakToken {
13218                    token: " ",
13219                    grapheme_len: 1,
13220                    is_whitespace: true,
13221                })
13222            } else {
13223                Some(WordBreakToken {
13224                    token,
13225                    grapheme_len: graphemes,
13226                    is_whitespace: false,
13227                })
13228            }
13229        } else {
13230            None
13231        }
13232    }
13233}
13234
13235#[test]
13236fn test_word_breaking_tokenizer() {
13237    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13238        ("", &[]),
13239        ("  ", &[(" ", 1, true)]),
13240        ("Ʒ", &[("Ʒ", 1, false)]),
13241        ("Ǽ", &[("Ǽ", 1, false)]),
13242        ("", &[("", 1, false)]),
13243        ("⋑⋑", &[("⋑⋑", 2, false)]),
13244        (
13245            "原理,进而",
13246            &[
13247                ("", 1, false),
13248                ("理,", 2, false),
13249                ("", 1, false),
13250                ("", 1, false),
13251            ],
13252        ),
13253        (
13254            "hello world",
13255            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13256        ),
13257        (
13258            "hello, world",
13259            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13260        ),
13261        (
13262            "  hello world",
13263            &[
13264                (" ", 1, true),
13265                ("hello", 5, false),
13266                (" ", 1, true),
13267                ("world", 5, false),
13268            ],
13269        ),
13270        (
13271            "这是什么 \n 钢笔",
13272            &[
13273                ("", 1, false),
13274                ("", 1, false),
13275                ("", 1, false),
13276                ("", 1, false),
13277                (" ", 1, true),
13278                ("", 1, false),
13279                ("", 1, false),
13280            ],
13281        ),
13282        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13283    ];
13284
13285    for (input, result) in tests {
13286        assert_eq!(
13287            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13288            result
13289                .iter()
13290                .copied()
13291                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13292                    token,
13293                    grapheme_len,
13294                    is_whitespace,
13295                })
13296                .collect::<Vec<_>>()
13297        );
13298    }
13299}
13300
13301fn wrap_with_prefix(
13302    line_prefix: String,
13303    unwrapped_text: String,
13304    wrap_column: usize,
13305    tab_size: NonZeroU32,
13306) -> String {
13307    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13308    let mut wrapped_text = String::new();
13309    let mut current_line = line_prefix.clone();
13310
13311    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13312    let mut current_line_len = line_prefix_len;
13313    for WordBreakToken {
13314        token,
13315        grapheme_len,
13316        is_whitespace,
13317    } in tokenizer
13318    {
13319        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13320            wrapped_text.push_str(current_line.trim_end());
13321            wrapped_text.push('\n');
13322            current_line.truncate(line_prefix.len());
13323            current_line_len = line_prefix_len;
13324            if !is_whitespace {
13325                current_line.push_str(token);
13326                current_line_len += grapheme_len;
13327            }
13328        } else if !is_whitespace {
13329            current_line.push_str(token);
13330            current_line_len += grapheme_len;
13331        } else if current_line_len != line_prefix_len {
13332            current_line.push(' ');
13333            current_line_len += 1;
13334        }
13335    }
13336
13337    if !current_line.is_empty() {
13338        wrapped_text.push_str(&current_line);
13339    }
13340    wrapped_text
13341}
13342
13343#[test]
13344fn test_wrap_with_prefix() {
13345    assert_eq!(
13346        wrap_with_prefix(
13347            "# ".to_string(),
13348            "abcdefg".to_string(),
13349            4,
13350            NonZeroU32::new(4).unwrap()
13351        ),
13352        "# abcdefg"
13353    );
13354    assert_eq!(
13355        wrap_with_prefix(
13356            "".to_string(),
13357            "\thello world".to_string(),
13358            8,
13359            NonZeroU32::new(4).unwrap()
13360        ),
13361        "hello\nworld"
13362    );
13363    assert_eq!(
13364        wrap_with_prefix(
13365            "// ".to_string(),
13366            "xx \nyy zz aa bb cc".to_string(),
13367            12,
13368            NonZeroU32::new(4).unwrap()
13369        ),
13370        "// xx yy zz\n// aa bb cc"
13371    );
13372    assert_eq!(
13373        wrap_with_prefix(
13374            String::new(),
13375            "这是什么 \n 钢笔".to_string(),
13376            3,
13377            NonZeroU32::new(4).unwrap()
13378        ),
13379        "这是什\n么 钢\n"
13380    );
13381}
13382
13383fn hunks_for_selections(
13384    snapshot: &EditorSnapshot,
13385    selections: &[Selection<Point>],
13386) -> Vec<MultiBufferDiffHunk> {
13387    hunks_for_ranges(
13388        selections.iter().map(|selection| selection.range()),
13389        snapshot,
13390    )
13391}
13392
13393pub fn hunks_for_ranges(
13394    ranges: impl Iterator<Item = Range<Point>>,
13395    snapshot: &EditorSnapshot,
13396) -> Vec<MultiBufferDiffHunk> {
13397    let mut hunks = Vec::new();
13398    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13399        HashMap::default();
13400    for query_range in ranges {
13401        let query_rows =
13402            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13403        for hunk in snapshot.diff_map.diff_hunks_in_range(
13404            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13405            &snapshot.buffer_snapshot,
13406        ) {
13407            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13408            // when the caret is just above or just below the deleted hunk.
13409            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13410            let related_to_selection = if allow_adjacent {
13411                hunk.row_range.overlaps(&query_rows)
13412                    || hunk.row_range.start == query_rows.end
13413                    || hunk.row_range.end == query_rows.start
13414            } else {
13415                hunk.row_range.overlaps(&query_rows)
13416            };
13417            if related_to_selection {
13418                if !processed_buffer_rows
13419                    .entry(hunk.buffer_id)
13420                    .or_default()
13421                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13422                {
13423                    continue;
13424                }
13425                hunks.push(hunk);
13426            }
13427        }
13428    }
13429
13430    hunks
13431}
13432
13433pub trait CollaborationHub {
13434    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13435    fn user_participant_indices<'a>(
13436        &self,
13437        cx: &'a AppContext,
13438    ) -> &'a HashMap<u64, ParticipantIndex>;
13439    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13440}
13441
13442impl CollaborationHub for Model<Project> {
13443    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13444        self.read(cx).collaborators()
13445    }
13446
13447    fn user_participant_indices<'a>(
13448        &self,
13449        cx: &'a AppContext,
13450    ) -> &'a HashMap<u64, ParticipantIndex> {
13451        self.read(cx).user_store().read(cx).participant_indices()
13452    }
13453
13454    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13455        let this = self.read(cx);
13456        let user_ids = this.collaborators().values().map(|c| c.user_id);
13457        this.user_store().read_with(cx, |user_store, cx| {
13458            user_store.participant_names(user_ids, cx)
13459        })
13460    }
13461}
13462
13463pub trait SemanticsProvider {
13464    fn hover(
13465        &self,
13466        buffer: &Model<Buffer>,
13467        position: text::Anchor,
13468        cx: &mut AppContext,
13469    ) -> Option<Task<Vec<project::Hover>>>;
13470
13471    fn inlay_hints(
13472        &self,
13473        buffer_handle: Model<Buffer>,
13474        range: Range<text::Anchor>,
13475        cx: &mut AppContext,
13476    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13477
13478    fn resolve_inlay_hint(
13479        &self,
13480        hint: InlayHint,
13481        buffer_handle: Model<Buffer>,
13482        server_id: LanguageServerId,
13483        cx: &mut AppContext,
13484    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13485
13486    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13487
13488    fn document_highlights(
13489        &self,
13490        buffer: &Model<Buffer>,
13491        position: text::Anchor,
13492        cx: &mut AppContext,
13493    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13494
13495    fn definitions(
13496        &self,
13497        buffer: &Model<Buffer>,
13498        position: text::Anchor,
13499        kind: GotoDefinitionKind,
13500        cx: &mut AppContext,
13501    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13502
13503    fn range_for_rename(
13504        &self,
13505        buffer: &Model<Buffer>,
13506        position: text::Anchor,
13507        cx: &mut AppContext,
13508    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13509
13510    fn perform_rename(
13511        &self,
13512        buffer: &Model<Buffer>,
13513        position: text::Anchor,
13514        new_name: String,
13515        cx: &mut AppContext,
13516    ) -> Option<Task<Result<ProjectTransaction>>>;
13517}
13518
13519pub trait CompletionProvider {
13520    fn completions(
13521        &self,
13522        buffer: &Model<Buffer>,
13523        buffer_position: text::Anchor,
13524        trigger: CompletionContext,
13525        cx: &mut ViewContext<Editor>,
13526    ) -> Task<Result<Vec<Completion>>>;
13527
13528    fn resolve_completions(
13529        &self,
13530        buffer: Model<Buffer>,
13531        completion_indices: Vec<usize>,
13532        completions: Rc<RefCell<Box<[Completion]>>>,
13533        cx: &mut ViewContext<Editor>,
13534    ) -> Task<Result<bool>>;
13535
13536    fn apply_additional_edits_for_completion(
13537        &self,
13538        _buffer: Model<Buffer>,
13539        _completions: Rc<RefCell<Box<[Completion]>>>,
13540        _completion_index: usize,
13541        _push_to_history: bool,
13542        _cx: &mut ViewContext<Editor>,
13543    ) -> Task<Result<Option<language::Transaction>>> {
13544        Task::ready(Ok(None))
13545    }
13546
13547    fn is_completion_trigger(
13548        &self,
13549        buffer: &Model<Buffer>,
13550        position: language::Anchor,
13551        text: &str,
13552        trigger_in_words: bool,
13553        cx: &mut ViewContext<Editor>,
13554    ) -> bool;
13555
13556    fn sort_completions(&self) -> bool {
13557        true
13558    }
13559}
13560
13561pub trait CodeActionProvider {
13562    fn code_actions(
13563        &self,
13564        buffer: &Model<Buffer>,
13565        range: Range<text::Anchor>,
13566        cx: &mut WindowContext,
13567    ) -> Task<Result<Vec<CodeAction>>>;
13568
13569    fn apply_code_action(
13570        &self,
13571        buffer_handle: Model<Buffer>,
13572        action: CodeAction,
13573        excerpt_id: ExcerptId,
13574        push_to_history: bool,
13575        cx: &mut WindowContext,
13576    ) -> Task<Result<ProjectTransaction>>;
13577}
13578
13579impl CodeActionProvider for Model<Project> {
13580    fn code_actions(
13581        &self,
13582        buffer: &Model<Buffer>,
13583        range: Range<text::Anchor>,
13584        cx: &mut WindowContext,
13585    ) -> Task<Result<Vec<CodeAction>>> {
13586        self.update(cx, |project, cx| {
13587            project.code_actions(buffer, range, None, cx)
13588        })
13589    }
13590
13591    fn apply_code_action(
13592        &self,
13593        buffer_handle: Model<Buffer>,
13594        action: CodeAction,
13595        _excerpt_id: ExcerptId,
13596        push_to_history: bool,
13597        cx: &mut WindowContext,
13598    ) -> Task<Result<ProjectTransaction>> {
13599        self.update(cx, |project, cx| {
13600            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13601        })
13602    }
13603}
13604
13605fn snippet_completions(
13606    project: &Project,
13607    buffer: &Model<Buffer>,
13608    buffer_position: text::Anchor,
13609    cx: &mut AppContext,
13610) -> Task<Result<Vec<Completion>>> {
13611    let language = buffer.read(cx).language_at(buffer_position);
13612    let language_name = language.as_ref().map(|language| language.lsp_id());
13613    let snippet_store = project.snippets().read(cx);
13614    let snippets = snippet_store.snippets_for(language_name, cx);
13615
13616    if snippets.is_empty() {
13617        return Task::ready(Ok(vec![]));
13618    }
13619    let snapshot = buffer.read(cx).text_snapshot();
13620    let chars: String = snapshot
13621        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13622        .collect();
13623
13624    let scope = language.map(|language| language.default_scope());
13625    let executor = cx.background_executor().clone();
13626
13627    cx.background_executor().spawn(async move {
13628        let classifier = CharClassifier::new(scope).for_completion(true);
13629        let mut last_word = chars
13630            .chars()
13631            .take_while(|c| classifier.is_word(*c))
13632            .collect::<String>();
13633        last_word = last_word.chars().rev().collect();
13634
13635        if last_word.is_empty() {
13636            return Ok(vec![]);
13637        }
13638
13639        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13640        let to_lsp = |point: &text::Anchor| {
13641            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13642            point_to_lsp(end)
13643        };
13644        let lsp_end = to_lsp(&buffer_position);
13645
13646        let candidates = snippets
13647            .iter()
13648            .enumerate()
13649            .flat_map(|(ix, snippet)| {
13650                snippet
13651                    .prefix
13652                    .iter()
13653                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13654            })
13655            .collect::<Vec<StringMatchCandidate>>();
13656
13657        let mut matches = fuzzy::match_strings(
13658            &candidates,
13659            &last_word,
13660            last_word.chars().any(|c| c.is_uppercase()),
13661            100,
13662            &Default::default(),
13663            executor,
13664        )
13665        .await;
13666
13667        // Remove all candidates where the query's start does not match the start of any word in the candidate
13668        if let Some(query_start) = last_word.chars().next() {
13669            matches.retain(|string_match| {
13670                split_words(&string_match.string).any(|word| {
13671                    // Check that the first codepoint of the word as lowercase matches the first
13672                    // codepoint of the query as lowercase
13673                    word.chars()
13674                        .flat_map(|codepoint| codepoint.to_lowercase())
13675                        .zip(query_start.to_lowercase())
13676                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13677                })
13678            });
13679        }
13680
13681        let matched_strings = matches
13682            .into_iter()
13683            .map(|m| m.string)
13684            .collect::<HashSet<_>>();
13685
13686        let result: Vec<Completion> = snippets
13687            .into_iter()
13688            .filter_map(|snippet| {
13689                let matching_prefix = snippet
13690                    .prefix
13691                    .iter()
13692                    .find(|prefix| matched_strings.contains(*prefix))?;
13693                let start = as_offset - last_word.len();
13694                let start = snapshot.anchor_before(start);
13695                let range = start..buffer_position;
13696                let lsp_start = to_lsp(&start);
13697                let lsp_range = lsp::Range {
13698                    start: lsp_start,
13699                    end: lsp_end,
13700                };
13701                Some(Completion {
13702                    old_range: range,
13703                    new_text: snippet.body.clone(),
13704                    resolved: false,
13705                    label: CodeLabel {
13706                        text: matching_prefix.clone(),
13707                        runs: vec![],
13708                        filter_range: 0..matching_prefix.len(),
13709                    },
13710                    server_id: LanguageServerId(usize::MAX),
13711                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13712                    lsp_completion: lsp::CompletionItem {
13713                        label: snippet.prefix.first().unwrap().clone(),
13714                        kind: Some(CompletionItemKind::SNIPPET),
13715                        label_details: snippet.description.as_ref().map(|description| {
13716                            lsp::CompletionItemLabelDetails {
13717                                detail: Some(description.clone()),
13718                                description: None,
13719                            }
13720                        }),
13721                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13722                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13723                            lsp::InsertReplaceEdit {
13724                                new_text: snippet.body.clone(),
13725                                insert: lsp_range,
13726                                replace: lsp_range,
13727                            },
13728                        )),
13729                        filter_text: Some(snippet.body.clone()),
13730                        sort_text: Some(char::MAX.to_string()),
13731                        ..Default::default()
13732                    },
13733                    confirm: None,
13734                })
13735            })
13736            .collect();
13737
13738        Ok(result)
13739    })
13740}
13741
13742impl CompletionProvider for Model<Project> {
13743    fn completions(
13744        &self,
13745        buffer: &Model<Buffer>,
13746        buffer_position: text::Anchor,
13747        options: CompletionContext,
13748        cx: &mut ViewContext<Editor>,
13749    ) -> Task<Result<Vec<Completion>>> {
13750        self.update(cx, |project, cx| {
13751            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13752            let project_completions = project.completions(buffer, buffer_position, options, cx);
13753            cx.background_executor().spawn(async move {
13754                let mut completions = project_completions.await?;
13755                let snippets_completions = snippets.await?;
13756                completions.extend(snippets_completions);
13757                Ok(completions)
13758            })
13759        })
13760    }
13761
13762    fn resolve_completions(
13763        &self,
13764        buffer: Model<Buffer>,
13765        completion_indices: Vec<usize>,
13766        completions: Rc<RefCell<Box<[Completion]>>>,
13767        cx: &mut ViewContext<Editor>,
13768    ) -> Task<Result<bool>> {
13769        self.update(cx, |project, cx| {
13770            project.lsp_store().update(cx, |lsp_store, cx| {
13771                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13772            })
13773        })
13774    }
13775
13776    fn apply_additional_edits_for_completion(
13777        &self,
13778        buffer: Model<Buffer>,
13779        completions: Rc<RefCell<Box<[Completion]>>>,
13780        completion_index: usize,
13781        push_to_history: bool,
13782        cx: &mut ViewContext<Editor>,
13783    ) -> Task<Result<Option<language::Transaction>>> {
13784        self.update(cx, |project, cx| {
13785            project.lsp_store().update(cx, |lsp_store, cx| {
13786                lsp_store.apply_additional_edits_for_completion(
13787                    buffer,
13788                    completions,
13789                    completion_index,
13790                    push_to_history,
13791                    cx,
13792                )
13793            })
13794        })
13795    }
13796
13797    fn is_completion_trigger(
13798        &self,
13799        buffer: &Model<Buffer>,
13800        position: language::Anchor,
13801        text: &str,
13802        trigger_in_words: bool,
13803        cx: &mut ViewContext<Editor>,
13804    ) -> bool {
13805        let mut chars = text.chars();
13806        let char = if let Some(char) = chars.next() {
13807            char
13808        } else {
13809            return false;
13810        };
13811        if chars.next().is_some() {
13812            return false;
13813        }
13814
13815        let buffer = buffer.read(cx);
13816        let snapshot = buffer.snapshot();
13817        if !snapshot.settings_at(position, cx).show_completions_on_input {
13818            return false;
13819        }
13820        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13821        if trigger_in_words && classifier.is_word(char) {
13822            return true;
13823        }
13824
13825        buffer.completion_triggers().contains(text)
13826    }
13827}
13828
13829impl SemanticsProvider for Model<Project> {
13830    fn hover(
13831        &self,
13832        buffer: &Model<Buffer>,
13833        position: text::Anchor,
13834        cx: &mut AppContext,
13835    ) -> Option<Task<Vec<project::Hover>>> {
13836        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13837    }
13838
13839    fn document_highlights(
13840        &self,
13841        buffer: &Model<Buffer>,
13842        position: text::Anchor,
13843        cx: &mut AppContext,
13844    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13845        Some(self.update(cx, |project, cx| {
13846            project.document_highlights(buffer, position, cx)
13847        }))
13848    }
13849
13850    fn definitions(
13851        &self,
13852        buffer: &Model<Buffer>,
13853        position: text::Anchor,
13854        kind: GotoDefinitionKind,
13855        cx: &mut AppContext,
13856    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13857        Some(self.update(cx, |project, cx| match kind {
13858            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13859            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13860            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13861            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13862        }))
13863    }
13864
13865    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13866        // TODO: make this work for remote projects
13867        self.read(cx)
13868            .language_servers_for_local_buffer(buffer.read(cx), cx)
13869            .any(
13870                |(_, server)| match server.capabilities().inlay_hint_provider {
13871                    Some(lsp::OneOf::Left(enabled)) => enabled,
13872                    Some(lsp::OneOf::Right(_)) => true,
13873                    None => false,
13874                },
13875            )
13876    }
13877
13878    fn inlay_hints(
13879        &self,
13880        buffer_handle: Model<Buffer>,
13881        range: Range<text::Anchor>,
13882        cx: &mut AppContext,
13883    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13884        Some(self.update(cx, |project, cx| {
13885            project.inlay_hints(buffer_handle, range, cx)
13886        }))
13887    }
13888
13889    fn resolve_inlay_hint(
13890        &self,
13891        hint: InlayHint,
13892        buffer_handle: Model<Buffer>,
13893        server_id: LanguageServerId,
13894        cx: &mut AppContext,
13895    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13896        Some(self.update(cx, |project, cx| {
13897            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13898        }))
13899    }
13900
13901    fn range_for_rename(
13902        &self,
13903        buffer: &Model<Buffer>,
13904        position: text::Anchor,
13905        cx: &mut AppContext,
13906    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13907        Some(self.update(cx, |project, cx| {
13908            project.prepare_rename(buffer.clone(), position, cx)
13909        }))
13910    }
13911
13912    fn perform_rename(
13913        &self,
13914        buffer: &Model<Buffer>,
13915        position: text::Anchor,
13916        new_name: String,
13917        cx: &mut AppContext,
13918    ) -> Option<Task<Result<ProjectTransaction>>> {
13919        Some(self.update(cx, |project, cx| {
13920            project.perform_rename(buffer.clone(), position, new_name, cx)
13921        }))
13922    }
13923}
13924
13925fn inlay_hint_settings(
13926    location: Anchor,
13927    snapshot: &MultiBufferSnapshot,
13928    cx: &mut ViewContext<Editor>,
13929) -> InlayHintSettings {
13930    let file = snapshot.file_at(location);
13931    let language = snapshot.language_at(location).map(|l| l.name());
13932    language_settings(language, file, cx).inlay_hints
13933}
13934
13935fn consume_contiguous_rows(
13936    contiguous_row_selections: &mut Vec<Selection<Point>>,
13937    selection: &Selection<Point>,
13938    display_map: &DisplaySnapshot,
13939    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13940) -> (MultiBufferRow, MultiBufferRow) {
13941    contiguous_row_selections.push(selection.clone());
13942    let start_row = MultiBufferRow(selection.start.row);
13943    let mut end_row = ending_row(selection, display_map);
13944
13945    while let Some(next_selection) = selections.peek() {
13946        if next_selection.start.row <= end_row.0 {
13947            end_row = ending_row(next_selection, display_map);
13948            contiguous_row_selections.push(selections.next().unwrap().clone());
13949        } else {
13950            break;
13951        }
13952    }
13953    (start_row, end_row)
13954}
13955
13956fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13957    if next_selection.end.column > 0 || next_selection.is_empty() {
13958        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13959    } else {
13960        MultiBufferRow(next_selection.end.row)
13961    }
13962}
13963
13964impl EditorSnapshot {
13965    pub fn remote_selections_in_range<'a>(
13966        &'a self,
13967        range: &'a Range<Anchor>,
13968        collaboration_hub: &dyn CollaborationHub,
13969        cx: &'a AppContext,
13970    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13971        let participant_names = collaboration_hub.user_names(cx);
13972        let participant_indices = collaboration_hub.user_participant_indices(cx);
13973        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13974        let collaborators_by_replica_id = collaborators_by_peer_id
13975            .iter()
13976            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13977            .collect::<HashMap<_, _>>();
13978        self.buffer_snapshot
13979            .selections_in_range(range, false)
13980            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13981                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13982                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13983                let user_name = participant_names.get(&collaborator.user_id).cloned();
13984                Some(RemoteSelection {
13985                    replica_id,
13986                    selection,
13987                    cursor_shape,
13988                    line_mode,
13989                    participant_index,
13990                    peer_id: collaborator.peer_id,
13991                    user_name,
13992                })
13993            })
13994    }
13995
13996    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13997        self.display_snapshot.buffer_snapshot.language_at(position)
13998    }
13999
14000    pub fn is_focused(&self) -> bool {
14001        self.is_focused
14002    }
14003
14004    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14005        self.placeholder_text.as_ref()
14006    }
14007
14008    pub fn scroll_position(&self) -> gpui::Point<f32> {
14009        self.scroll_anchor.scroll_position(&self.display_snapshot)
14010    }
14011
14012    fn gutter_dimensions(
14013        &self,
14014        font_id: FontId,
14015        font_size: Pixels,
14016        em_width: Pixels,
14017        em_advance: Pixels,
14018        max_line_number_width: Pixels,
14019        cx: &AppContext,
14020    ) -> GutterDimensions {
14021        if !self.show_gutter {
14022            return GutterDimensions::default();
14023        }
14024        let descent = cx.text_system().descent(font_id, font_size);
14025
14026        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14027            matches!(
14028                ProjectSettings::get_global(cx).git.git_gutter,
14029                Some(GitGutterSetting::TrackedFiles)
14030            )
14031        });
14032        let gutter_settings = EditorSettings::get_global(cx).gutter;
14033        let show_line_numbers = self
14034            .show_line_numbers
14035            .unwrap_or(gutter_settings.line_numbers);
14036        let line_gutter_width = if show_line_numbers {
14037            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14038            let min_width_for_number_on_gutter = em_advance * 4.0;
14039            max_line_number_width.max(min_width_for_number_on_gutter)
14040        } else {
14041            0.0.into()
14042        };
14043
14044        let show_code_actions = self
14045            .show_code_actions
14046            .unwrap_or(gutter_settings.code_actions);
14047
14048        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14049
14050        let git_blame_entries_width =
14051            self.git_blame_gutter_max_author_length
14052                .map(|max_author_length| {
14053                    // Length of the author name, but also space for the commit hash,
14054                    // the spacing and the timestamp.
14055                    let max_char_count = max_author_length
14056                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14057                        + 7 // length of commit sha
14058                        + 14 // length of max relative timestamp ("60 minutes ago")
14059                        + 4; // gaps and margins
14060
14061                    em_advance * max_char_count
14062                });
14063
14064        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14065        left_padding += if show_code_actions || show_runnables {
14066            em_width * 3.0
14067        } else if show_git_gutter && show_line_numbers {
14068            em_width * 2.0
14069        } else if show_git_gutter || show_line_numbers {
14070            em_width
14071        } else {
14072            px(0.)
14073        };
14074
14075        let right_padding = if gutter_settings.folds && show_line_numbers {
14076            em_width * 4.0
14077        } else if gutter_settings.folds {
14078            em_width * 3.0
14079        } else if show_line_numbers {
14080            em_width
14081        } else {
14082            px(0.)
14083        };
14084
14085        GutterDimensions {
14086            left_padding,
14087            right_padding,
14088            width: line_gutter_width + left_padding + right_padding,
14089            margin: -descent,
14090            git_blame_entries_width,
14091        }
14092    }
14093
14094    pub fn render_crease_toggle(
14095        &self,
14096        buffer_row: MultiBufferRow,
14097        row_contains_cursor: bool,
14098        editor: View<Editor>,
14099        cx: &mut WindowContext,
14100    ) -> Option<AnyElement> {
14101        let folded = self.is_line_folded(buffer_row);
14102        let mut is_foldable = false;
14103
14104        if let Some(crease) = self
14105            .crease_snapshot
14106            .query_row(buffer_row, &self.buffer_snapshot)
14107        {
14108            is_foldable = true;
14109            match crease {
14110                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14111                    if let Some(render_toggle) = render_toggle {
14112                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14113                            if folded {
14114                                editor.update(cx, |editor, cx| {
14115                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14116                                });
14117                            } else {
14118                                editor.update(cx, |editor, cx| {
14119                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14120                                });
14121                            }
14122                        });
14123                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14124                    }
14125                }
14126            }
14127        }
14128
14129        is_foldable |= self.starts_indent(buffer_row);
14130
14131        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14132            Some(
14133                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14134                    .toggle_state(folded)
14135                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14136                        if folded {
14137                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14138                        } else {
14139                            this.fold_at(&FoldAt { buffer_row }, cx);
14140                        }
14141                    }))
14142                    .into_any_element(),
14143            )
14144        } else {
14145            None
14146        }
14147    }
14148
14149    pub fn render_crease_trailer(
14150        &self,
14151        buffer_row: MultiBufferRow,
14152        cx: &mut WindowContext,
14153    ) -> Option<AnyElement> {
14154        let folded = self.is_line_folded(buffer_row);
14155        if let Crease::Inline { render_trailer, .. } = self
14156            .crease_snapshot
14157            .query_row(buffer_row, &self.buffer_snapshot)?
14158        {
14159            let render_trailer = render_trailer.as_ref()?;
14160            Some(render_trailer(buffer_row, folded, cx))
14161        } else {
14162            None
14163        }
14164    }
14165}
14166
14167impl Deref for EditorSnapshot {
14168    type Target = DisplaySnapshot;
14169
14170    fn deref(&self) -> &Self::Target {
14171        &self.display_snapshot
14172    }
14173}
14174
14175#[derive(Clone, Debug, PartialEq, Eq)]
14176pub enum EditorEvent {
14177    InputIgnored {
14178        text: Arc<str>,
14179    },
14180    InputHandled {
14181        utf16_range_to_replace: Option<Range<isize>>,
14182        text: Arc<str>,
14183    },
14184    ExcerptsAdded {
14185        buffer: Model<Buffer>,
14186        predecessor: ExcerptId,
14187        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14188    },
14189    ExcerptsRemoved {
14190        ids: Vec<ExcerptId>,
14191    },
14192    BufferFoldToggled {
14193        ids: Vec<ExcerptId>,
14194        folded: bool,
14195    },
14196    ExcerptsEdited {
14197        ids: Vec<ExcerptId>,
14198    },
14199    ExcerptsExpanded {
14200        ids: Vec<ExcerptId>,
14201    },
14202    BufferEdited,
14203    Edited {
14204        transaction_id: clock::Lamport,
14205    },
14206    Reparsed(BufferId),
14207    Focused,
14208    FocusedIn,
14209    Blurred,
14210    DirtyChanged,
14211    Saved,
14212    TitleChanged,
14213    DiffBaseChanged,
14214    SelectionsChanged {
14215        local: bool,
14216    },
14217    ScrollPositionChanged {
14218        local: bool,
14219        autoscroll: bool,
14220    },
14221    Closed,
14222    TransactionUndone {
14223        transaction_id: clock::Lamport,
14224    },
14225    TransactionBegun {
14226        transaction_id: clock::Lamport,
14227    },
14228    Reloaded,
14229    CursorShapeChanged,
14230}
14231
14232impl EventEmitter<EditorEvent> for Editor {}
14233
14234impl FocusableView for Editor {
14235    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14236        self.focus_handle.clone()
14237    }
14238}
14239
14240impl Render for Editor {
14241    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14242        let settings = ThemeSettings::get_global(cx);
14243
14244        let mut text_style = match self.mode {
14245            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14246                color: cx.theme().colors().editor_foreground,
14247                font_family: settings.ui_font.family.clone(),
14248                font_features: settings.ui_font.features.clone(),
14249                font_fallbacks: settings.ui_font.fallbacks.clone(),
14250                font_size: rems(0.875).into(),
14251                font_weight: settings.ui_font.weight,
14252                line_height: relative(settings.buffer_line_height.value()),
14253                ..Default::default()
14254            },
14255            EditorMode::Full => TextStyle {
14256                color: cx.theme().colors().editor_foreground,
14257                font_family: settings.buffer_font.family.clone(),
14258                font_features: settings.buffer_font.features.clone(),
14259                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14260                font_size: settings.buffer_font_size(cx).into(),
14261                font_weight: settings.buffer_font.weight,
14262                line_height: relative(settings.buffer_line_height.value()),
14263                ..Default::default()
14264            },
14265        };
14266        if let Some(text_style_refinement) = &self.text_style_refinement {
14267            text_style.refine(text_style_refinement)
14268        }
14269
14270        let background = match self.mode {
14271            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14272            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14273            EditorMode::Full => cx.theme().colors().editor_background,
14274        };
14275
14276        EditorElement::new(
14277            cx.view(),
14278            EditorStyle {
14279                background,
14280                local_player: cx.theme().players().local(),
14281                text: text_style,
14282                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14283                syntax: cx.theme().syntax().clone(),
14284                status: cx.theme().status().clone(),
14285                inlay_hints_style: make_inlay_hints_style(cx),
14286                inline_completion_styles: make_suggestion_styles(cx),
14287                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14288            },
14289        )
14290    }
14291}
14292
14293impl ViewInputHandler for Editor {
14294    fn text_for_range(
14295        &mut self,
14296        range_utf16: Range<usize>,
14297        adjusted_range: &mut Option<Range<usize>>,
14298        cx: &mut ViewContext<Self>,
14299    ) -> Option<String> {
14300        let snapshot = self.buffer.read(cx).read(cx);
14301        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14302        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14303        if (start.0..end.0) != range_utf16 {
14304            adjusted_range.replace(start.0..end.0);
14305        }
14306        Some(snapshot.text_for_range(start..end).collect())
14307    }
14308
14309    fn selected_text_range(
14310        &mut self,
14311        ignore_disabled_input: bool,
14312        cx: &mut ViewContext<Self>,
14313    ) -> Option<UTF16Selection> {
14314        // Prevent the IME menu from appearing when holding down an alphabetic key
14315        // while input is disabled.
14316        if !ignore_disabled_input && !self.input_enabled {
14317            return None;
14318        }
14319
14320        let selection = self.selections.newest::<OffsetUtf16>(cx);
14321        let range = selection.range();
14322
14323        Some(UTF16Selection {
14324            range: range.start.0..range.end.0,
14325            reversed: selection.reversed,
14326        })
14327    }
14328
14329    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14330        let snapshot = self.buffer.read(cx).read(cx);
14331        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14332        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14333    }
14334
14335    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14336        self.clear_highlights::<InputComposition>(cx);
14337        self.ime_transaction.take();
14338    }
14339
14340    fn replace_text_in_range(
14341        &mut self,
14342        range_utf16: Option<Range<usize>>,
14343        text: &str,
14344        cx: &mut ViewContext<Self>,
14345    ) {
14346        if !self.input_enabled {
14347            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14348            return;
14349        }
14350
14351        self.transact(cx, |this, cx| {
14352            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14353                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14354                Some(this.selection_replacement_ranges(range_utf16, cx))
14355            } else {
14356                this.marked_text_ranges(cx)
14357            };
14358
14359            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14360                let newest_selection_id = this.selections.newest_anchor().id;
14361                this.selections
14362                    .all::<OffsetUtf16>(cx)
14363                    .iter()
14364                    .zip(ranges_to_replace.iter())
14365                    .find_map(|(selection, range)| {
14366                        if selection.id == newest_selection_id {
14367                            Some(
14368                                (range.start.0 as isize - selection.head().0 as isize)
14369                                    ..(range.end.0 as isize - selection.head().0 as isize),
14370                            )
14371                        } else {
14372                            None
14373                        }
14374                    })
14375            });
14376
14377            cx.emit(EditorEvent::InputHandled {
14378                utf16_range_to_replace: range_to_replace,
14379                text: text.into(),
14380            });
14381
14382            if let Some(new_selected_ranges) = new_selected_ranges {
14383                this.change_selections(None, cx, |selections| {
14384                    selections.select_ranges(new_selected_ranges)
14385                });
14386                this.backspace(&Default::default(), cx);
14387            }
14388
14389            this.handle_input(text, cx);
14390        });
14391
14392        if let Some(transaction) = self.ime_transaction {
14393            self.buffer.update(cx, |buffer, cx| {
14394                buffer.group_until_transaction(transaction, cx);
14395            });
14396        }
14397
14398        self.unmark_text(cx);
14399    }
14400
14401    fn replace_and_mark_text_in_range(
14402        &mut self,
14403        range_utf16: Option<Range<usize>>,
14404        text: &str,
14405        new_selected_range_utf16: Option<Range<usize>>,
14406        cx: &mut ViewContext<Self>,
14407    ) {
14408        if !self.input_enabled {
14409            return;
14410        }
14411
14412        let transaction = self.transact(cx, |this, cx| {
14413            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14414                let snapshot = this.buffer.read(cx).read(cx);
14415                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14416                    for marked_range in &mut marked_ranges {
14417                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14418                        marked_range.start.0 += relative_range_utf16.start;
14419                        marked_range.start =
14420                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14421                        marked_range.end =
14422                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14423                    }
14424                }
14425                Some(marked_ranges)
14426            } else if let Some(range_utf16) = range_utf16 {
14427                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14428                Some(this.selection_replacement_ranges(range_utf16, cx))
14429            } else {
14430                None
14431            };
14432
14433            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14434                let newest_selection_id = this.selections.newest_anchor().id;
14435                this.selections
14436                    .all::<OffsetUtf16>(cx)
14437                    .iter()
14438                    .zip(ranges_to_replace.iter())
14439                    .find_map(|(selection, range)| {
14440                        if selection.id == newest_selection_id {
14441                            Some(
14442                                (range.start.0 as isize - selection.head().0 as isize)
14443                                    ..(range.end.0 as isize - selection.head().0 as isize),
14444                            )
14445                        } else {
14446                            None
14447                        }
14448                    })
14449            });
14450
14451            cx.emit(EditorEvent::InputHandled {
14452                utf16_range_to_replace: range_to_replace,
14453                text: text.into(),
14454            });
14455
14456            if let Some(ranges) = ranges_to_replace {
14457                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14458            }
14459
14460            let marked_ranges = {
14461                let snapshot = this.buffer.read(cx).read(cx);
14462                this.selections
14463                    .disjoint_anchors()
14464                    .iter()
14465                    .map(|selection| {
14466                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14467                    })
14468                    .collect::<Vec<_>>()
14469            };
14470
14471            if text.is_empty() {
14472                this.unmark_text(cx);
14473            } else {
14474                this.highlight_text::<InputComposition>(
14475                    marked_ranges.clone(),
14476                    HighlightStyle {
14477                        underline: Some(UnderlineStyle {
14478                            thickness: px(1.),
14479                            color: None,
14480                            wavy: false,
14481                        }),
14482                        ..Default::default()
14483                    },
14484                    cx,
14485                );
14486            }
14487
14488            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14489            let use_autoclose = this.use_autoclose;
14490            let use_auto_surround = this.use_auto_surround;
14491            this.set_use_autoclose(false);
14492            this.set_use_auto_surround(false);
14493            this.handle_input(text, cx);
14494            this.set_use_autoclose(use_autoclose);
14495            this.set_use_auto_surround(use_auto_surround);
14496
14497            if let Some(new_selected_range) = new_selected_range_utf16 {
14498                let snapshot = this.buffer.read(cx).read(cx);
14499                let new_selected_ranges = marked_ranges
14500                    .into_iter()
14501                    .map(|marked_range| {
14502                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14503                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14504                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14505                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14506                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14507                    })
14508                    .collect::<Vec<_>>();
14509
14510                drop(snapshot);
14511                this.change_selections(None, cx, |selections| {
14512                    selections.select_ranges(new_selected_ranges)
14513                });
14514            }
14515        });
14516
14517        self.ime_transaction = self.ime_transaction.or(transaction);
14518        if let Some(transaction) = self.ime_transaction {
14519            self.buffer.update(cx, |buffer, cx| {
14520                buffer.group_until_transaction(transaction, cx);
14521            });
14522        }
14523
14524        if self.text_highlights::<InputComposition>(cx).is_none() {
14525            self.ime_transaction.take();
14526        }
14527    }
14528
14529    fn bounds_for_range(
14530        &mut self,
14531        range_utf16: Range<usize>,
14532        element_bounds: gpui::Bounds<Pixels>,
14533        cx: &mut ViewContext<Self>,
14534    ) -> Option<gpui::Bounds<Pixels>> {
14535        let text_layout_details = self.text_layout_details(cx);
14536        let gpui::Point {
14537            x: em_width,
14538            y: line_height,
14539        } = self.character_size(cx);
14540
14541        let snapshot = self.snapshot(cx);
14542        let scroll_position = snapshot.scroll_position();
14543        let scroll_left = scroll_position.x * em_width;
14544
14545        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14546        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14547            + self.gutter_dimensions.width
14548            + self.gutter_dimensions.margin;
14549        let y = line_height * (start.row().as_f32() - scroll_position.y);
14550
14551        Some(Bounds {
14552            origin: element_bounds.origin + point(x, y),
14553            size: size(em_width, line_height),
14554        })
14555    }
14556}
14557
14558trait SelectionExt {
14559    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14560    fn spanned_rows(
14561        &self,
14562        include_end_if_at_line_start: bool,
14563        map: &DisplaySnapshot,
14564    ) -> Range<MultiBufferRow>;
14565}
14566
14567impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14568    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14569        let start = self
14570            .start
14571            .to_point(&map.buffer_snapshot)
14572            .to_display_point(map);
14573        let end = self
14574            .end
14575            .to_point(&map.buffer_snapshot)
14576            .to_display_point(map);
14577        if self.reversed {
14578            end..start
14579        } else {
14580            start..end
14581        }
14582    }
14583
14584    fn spanned_rows(
14585        &self,
14586        include_end_if_at_line_start: bool,
14587        map: &DisplaySnapshot,
14588    ) -> Range<MultiBufferRow> {
14589        let start = self.start.to_point(&map.buffer_snapshot);
14590        let mut end = self.end.to_point(&map.buffer_snapshot);
14591        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14592            end.row -= 1;
14593        }
14594
14595        let buffer_start = map.prev_line_boundary(start).0;
14596        let buffer_end = map.next_line_boundary(end).0;
14597        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14598    }
14599}
14600
14601impl<T: InvalidationRegion> InvalidationStack<T> {
14602    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14603    where
14604        S: Clone + ToOffset,
14605    {
14606        while let Some(region) = self.last() {
14607            let all_selections_inside_invalidation_ranges =
14608                if selections.len() == region.ranges().len() {
14609                    selections
14610                        .iter()
14611                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14612                        .all(|(selection, invalidation_range)| {
14613                            let head = selection.head().to_offset(buffer);
14614                            invalidation_range.start <= head && invalidation_range.end >= head
14615                        })
14616                } else {
14617                    false
14618                };
14619
14620            if all_selections_inside_invalidation_ranges {
14621                break;
14622            } else {
14623                self.pop();
14624            }
14625        }
14626    }
14627}
14628
14629impl<T> Default for InvalidationStack<T> {
14630    fn default() -> Self {
14631        Self(Default::default())
14632    }
14633}
14634
14635impl<T> Deref for InvalidationStack<T> {
14636    type Target = Vec<T>;
14637
14638    fn deref(&self) -> &Self::Target {
14639        &self.0
14640    }
14641}
14642
14643impl<T> DerefMut for InvalidationStack<T> {
14644    fn deref_mut(&mut self) -> &mut Self::Target {
14645        &mut self.0
14646    }
14647}
14648
14649impl InvalidationRegion for SnippetState {
14650    fn ranges(&self) -> &[Range<Anchor>] {
14651        &self.ranges[self.active_index]
14652    }
14653}
14654
14655pub fn diagnostic_block_renderer(
14656    diagnostic: Diagnostic,
14657    max_message_rows: Option<u8>,
14658    allow_closing: bool,
14659    _is_valid: bool,
14660) -> RenderBlock {
14661    let (text_without_backticks, code_ranges) =
14662        highlight_diagnostic_message(&diagnostic, max_message_rows);
14663
14664    Arc::new(move |cx: &mut BlockContext| {
14665        let group_id: SharedString = cx.block_id.to_string().into();
14666
14667        let mut text_style = cx.text_style().clone();
14668        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14669        let theme_settings = ThemeSettings::get_global(cx);
14670        text_style.font_family = theme_settings.buffer_font.family.clone();
14671        text_style.font_style = theme_settings.buffer_font.style;
14672        text_style.font_features = theme_settings.buffer_font.features.clone();
14673        text_style.font_weight = theme_settings.buffer_font.weight;
14674
14675        let multi_line_diagnostic = diagnostic.message.contains('\n');
14676
14677        let buttons = |diagnostic: &Diagnostic| {
14678            if multi_line_diagnostic {
14679                v_flex()
14680            } else {
14681                h_flex()
14682            }
14683            .when(allow_closing, |div| {
14684                div.children(diagnostic.is_primary.then(|| {
14685                    IconButton::new("close-block", IconName::XCircle)
14686                        .icon_color(Color::Muted)
14687                        .size(ButtonSize::Compact)
14688                        .style(ButtonStyle::Transparent)
14689                        .visible_on_hover(group_id.clone())
14690                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14691                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14692                }))
14693            })
14694            .child(
14695                IconButton::new("copy-block", IconName::Copy)
14696                    .icon_color(Color::Muted)
14697                    .size(ButtonSize::Compact)
14698                    .style(ButtonStyle::Transparent)
14699                    .visible_on_hover(group_id.clone())
14700                    .on_click({
14701                        let message = diagnostic.message.clone();
14702                        move |_click, cx| {
14703                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14704                        }
14705                    })
14706                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14707            )
14708        };
14709
14710        let icon_size = buttons(&diagnostic)
14711            .into_any_element()
14712            .layout_as_root(AvailableSpace::min_size(), cx);
14713
14714        h_flex()
14715            .id(cx.block_id)
14716            .group(group_id.clone())
14717            .relative()
14718            .size_full()
14719            .block_mouse_down()
14720            .pl(cx.gutter_dimensions.width)
14721            .w(cx.max_width - cx.gutter_dimensions.full_width())
14722            .child(
14723                div()
14724                    .flex()
14725                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14726                    .flex_shrink(),
14727            )
14728            .child(buttons(&diagnostic))
14729            .child(div().flex().flex_shrink_0().child(
14730                StyledText::new(text_without_backticks.clone()).with_highlights(
14731                    &text_style,
14732                    code_ranges.iter().map(|range| {
14733                        (
14734                            range.clone(),
14735                            HighlightStyle {
14736                                font_weight: Some(FontWeight::BOLD),
14737                                ..Default::default()
14738                            },
14739                        )
14740                    }),
14741                ),
14742            ))
14743            .into_any_element()
14744    })
14745}
14746
14747fn inline_completion_edit_text(
14748    editor_snapshot: &EditorSnapshot,
14749    edits: &Vec<(Range<Anchor>, String)>,
14750    include_deletions: bool,
14751    cx: &WindowContext,
14752) -> InlineCompletionText {
14753    let edit_start = edits
14754        .first()
14755        .unwrap()
14756        .0
14757        .start
14758        .to_display_point(editor_snapshot);
14759
14760    let mut text = String::new();
14761    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14762    let mut highlights = Vec::new();
14763    for (old_range, new_text) in edits {
14764        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14765        text.extend(
14766            editor_snapshot
14767                .buffer_snapshot
14768                .chunks(offset..old_offset_range.start, false)
14769                .map(|chunk| chunk.text),
14770        );
14771        offset = old_offset_range.end;
14772
14773        let start = text.len();
14774        let color = if include_deletions && new_text.is_empty() {
14775            text.extend(
14776                editor_snapshot
14777                    .buffer_snapshot
14778                    .chunks(old_offset_range.start..offset, false)
14779                    .map(|chunk| chunk.text),
14780            );
14781            cx.theme().status().deleted_background
14782        } else {
14783            text.push_str(new_text);
14784            cx.theme().status().created_background
14785        };
14786        let end = text.len();
14787
14788        highlights.push((
14789            start..end,
14790            HighlightStyle {
14791                background_color: Some(color),
14792                ..Default::default()
14793            },
14794        ));
14795    }
14796
14797    let edit_end = edits
14798        .last()
14799        .unwrap()
14800        .0
14801        .end
14802        .to_display_point(editor_snapshot);
14803    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14804        .to_offset(editor_snapshot, Bias::Right);
14805    text.extend(
14806        editor_snapshot
14807            .buffer_snapshot
14808            .chunks(offset..end_of_line, false)
14809            .map(|chunk| chunk.text),
14810    );
14811
14812    InlineCompletionText::Edit {
14813        text: text.into(),
14814        highlights,
14815    }
14816}
14817
14818pub fn highlight_diagnostic_message(
14819    diagnostic: &Diagnostic,
14820    mut max_message_rows: Option<u8>,
14821) -> (SharedString, Vec<Range<usize>>) {
14822    let mut text_without_backticks = String::new();
14823    let mut code_ranges = Vec::new();
14824
14825    if let Some(source) = &diagnostic.source {
14826        text_without_backticks.push_str(source);
14827        code_ranges.push(0..source.len());
14828        text_without_backticks.push_str(": ");
14829    }
14830
14831    let mut prev_offset = 0;
14832    let mut in_code_block = false;
14833    let has_row_limit = max_message_rows.is_some();
14834    let mut newline_indices = diagnostic
14835        .message
14836        .match_indices('\n')
14837        .filter(|_| has_row_limit)
14838        .map(|(ix, _)| ix)
14839        .fuse()
14840        .peekable();
14841
14842    for (quote_ix, _) in diagnostic
14843        .message
14844        .match_indices('`')
14845        .chain([(diagnostic.message.len(), "")])
14846    {
14847        let mut first_newline_ix = None;
14848        let mut last_newline_ix = None;
14849        while let Some(newline_ix) = newline_indices.peek() {
14850            if *newline_ix < quote_ix {
14851                if first_newline_ix.is_none() {
14852                    first_newline_ix = Some(*newline_ix);
14853                }
14854                last_newline_ix = Some(*newline_ix);
14855
14856                if let Some(rows_left) = &mut max_message_rows {
14857                    if *rows_left == 0 {
14858                        break;
14859                    } else {
14860                        *rows_left -= 1;
14861                    }
14862                }
14863                let _ = newline_indices.next();
14864            } else {
14865                break;
14866            }
14867        }
14868        let prev_len = text_without_backticks.len();
14869        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14870        text_without_backticks.push_str(new_text);
14871        if in_code_block {
14872            code_ranges.push(prev_len..text_without_backticks.len());
14873        }
14874        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14875        in_code_block = !in_code_block;
14876        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14877            text_without_backticks.push_str("...");
14878            break;
14879        }
14880    }
14881
14882    (text_without_backticks.into(), code_ranges)
14883}
14884
14885fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14886    match severity {
14887        DiagnosticSeverity::ERROR => colors.error,
14888        DiagnosticSeverity::WARNING => colors.warning,
14889        DiagnosticSeverity::INFORMATION => colors.info,
14890        DiagnosticSeverity::HINT => colors.info,
14891        _ => colors.ignored,
14892    }
14893}
14894
14895pub fn styled_runs_for_code_label<'a>(
14896    label: &'a CodeLabel,
14897    syntax_theme: &'a theme::SyntaxTheme,
14898) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14899    let fade_out = HighlightStyle {
14900        fade_out: Some(0.35),
14901        ..Default::default()
14902    };
14903
14904    let mut prev_end = label.filter_range.end;
14905    label
14906        .runs
14907        .iter()
14908        .enumerate()
14909        .flat_map(move |(ix, (range, highlight_id))| {
14910            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14911                style
14912            } else {
14913                return Default::default();
14914            };
14915            let mut muted_style = style;
14916            muted_style.highlight(fade_out);
14917
14918            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14919            if range.start >= label.filter_range.end {
14920                if range.start > prev_end {
14921                    runs.push((prev_end..range.start, fade_out));
14922                }
14923                runs.push((range.clone(), muted_style));
14924            } else if range.end <= label.filter_range.end {
14925                runs.push((range.clone(), style));
14926            } else {
14927                runs.push((range.start..label.filter_range.end, style));
14928                runs.push((label.filter_range.end..range.end, muted_style));
14929            }
14930            prev_end = cmp::max(prev_end, range.end);
14931
14932            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14933                runs.push((prev_end..label.text.len(), fade_out));
14934            }
14935
14936            runs
14937        })
14938}
14939
14940pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14941    let mut prev_index = 0;
14942    let mut prev_codepoint: Option<char> = None;
14943    text.char_indices()
14944        .chain([(text.len(), '\0')])
14945        .filter_map(move |(index, codepoint)| {
14946            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14947            let is_boundary = index == text.len()
14948                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14949                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14950            if is_boundary {
14951                let chunk = &text[prev_index..index];
14952                prev_index = index;
14953                Some(chunk)
14954            } else {
14955                None
14956            }
14957        })
14958}
14959
14960pub trait RangeToAnchorExt: Sized {
14961    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14962
14963    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14964        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14965        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14966    }
14967}
14968
14969impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14970    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14971        let start_offset = self.start.to_offset(snapshot);
14972        let end_offset = self.end.to_offset(snapshot);
14973        if start_offset == end_offset {
14974            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14975        } else {
14976            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14977        }
14978    }
14979}
14980
14981pub trait RowExt {
14982    fn as_f32(&self) -> f32;
14983
14984    fn next_row(&self) -> Self;
14985
14986    fn previous_row(&self) -> Self;
14987
14988    fn minus(&self, other: Self) -> u32;
14989}
14990
14991impl RowExt for DisplayRow {
14992    fn as_f32(&self) -> f32 {
14993        self.0 as f32
14994    }
14995
14996    fn next_row(&self) -> Self {
14997        Self(self.0 + 1)
14998    }
14999
15000    fn previous_row(&self) -> Self {
15001        Self(self.0.saturating_sub(1))
15002    }
15003
15004    fn minus(&self, other: Self) -> u32 {
15005        self.0 - other.0
15006    }
15007}
15008
15009impl RowExt for MultiBufferRow {
15010    fn as_f32(&self) -> f32 {
15011        self.0 as f32
15012    }
15013
15014    fn next_row(&self) -> Self {
15015        Self(self.0 + 1)
15016    }
15017
15018    fn previous_row(&self) -> Self {
15019        Self(self.0.saturating_sub(1))
15020    }
15021
15022    fn minus(&self, other: Self) -> u32 {
15023        self.0 - other.0
15024    }
15025}
15026
15027trait RowRangeExt {
15028    type Row;
15029
15030    fn len(&self) -> usize;
15031
15032    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15033}
15034
15035impl RowRangeExt for Range<MultiBufferRow> {
15036    type Row = MultiBufferRow;
15037
15038    fn len(&self) -> usize {
15039        (self.end.0 - self.start.0) as usize
15040    }
15041
15042    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15043        (self.start.0..self.end.0).map(MultiBufferRow)
15044    }
15045}
15046
15047impl RowRangeExt for Range<DisplayRow> {
15048    type Row = DisplayRow;
15049
15050    fn len(&self) -> usize {
15051        (self.end.0 - self.start.0) as usize
15052    }
15053
15054    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15055        (self.start.0..self.end.0).map(DisplayRow)
15056    }
15057}
15058
15059fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15060    if hunk.diff_base_byte_range.is_empty() {
15061        DiffHunkStatus::Added
15062    } else if hunk.row_range.is_empty() {
15063        DiffHunkStatus::Removed
15064    } else {
15065        DiffHunkStatus::Modified
15066    }
15067}
15068
15069/// If select range has more than one line, we
15070/// just point the cursor to range.start.
15071fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15072    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15073        range
15074    } else {
15075        range.start..range.start
15076    }
15077}
15078
15079pub struct KillRing(ClipboardItem);
15080impl Global for KillRing {}
15081
15082const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);