editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod code_context_menus;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51use ::git::diff::DiffHunkStatus;
   52pub(crate) use actions::*;
   53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{anyhow, Context as _, Result};
   56use blink_manager::BlinkManager;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::StringMatchCandidate;
   73
   74use code_context_menus::{
   75    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   76    CompletionEntry, CompletionsMenu, ContextMenuOrigin,
   77};
   78use git::blame::GitBlame;
   79use gpui::{
   80    div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
   81    AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
   82    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
   83    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
   84    MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
   85    Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   87    WeakView, WindowContext,
   88};
   89use highlight_matching_bracket::refresh_matching_bracket_highlights;
   90use hover_popover::{hide_hover, HoverState};
   91pub(crate) use hunk_diff::HoveredHunk;
   92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
  103    Point, Selection, SelectionGoal, TransactionId,
  104};
  105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  106use linked_editing_ranges::refresh_linked_ranges;
  107use mouse_context_menu::MouseContextMenu;
  108pub use proposed_changes_editor::{
  109    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  110};
  111use similar::{ChangeTag, TextDiff};
  112use std::iter::Peekable;
  113use task::{ResolvedTask, TaskTemplate, TaskVariables};
  114
  115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  116pub use lsp::CompletionContext;
  117use lsp::{
  118    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  119    LanguageServerId, LanguageServerName,
  120};
  121
  122use movement::TextLayoutDetails;
  123pub use multi_buffer::{
  124    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  125    ToPoint,
  126};
  127use multi_buffer::{
  128    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  129};
  130use project::{
  131    lsp_store::{FormatTarget, FormatTrigger, OpenLspBufferHandle},
  132    project_settings::{GitGutterSetting, ProjectSettings},
  133    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  134    LspStore, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  135};
  136use rand::prelude::*;
  137use rpc::{proto::*, ErrorExt};
  138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  139use selections_collection::{
  140    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  141};
  142use serde::{Deserialize, Serialize};
  143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  144use smallvec::SmallVec;
  145use snippet::Snippet;
  146use std::{
  147    any::TypeId,
  148    borrow::Cow,
  149    cell::RefCell,
  150    cmp::{self, Ordering, Reverse},
  151    mem,
  152    num::NonZeroU32,
  153    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  154    path::{Path, PathBuf},
  155    rc::Rc,
  156    sync::Arc,
  157    time::{Duration, Instant},
  158};
  159pub use sum_tree::Bias;
  160use sum_tree::TreeMap;
  161use text::{BufferId, OffsetUtf16, Rope};
  162use theme::{
  163    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  164    ThemeColors, ThemeSettings,
  165};
  166use ui::{
  167    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  168    PopoverMenuHandle, Tooltip,
  169};
  170use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  171use workspace::item::{ItemHandle, PreviewTabsSettings};
  172use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  173use workspace::{
  174    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  175};
  176use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  177
  178use crate::hover_links::{find_url, find_url_from_range};
  179use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  180
  181pub const FILE_HEADER_HEIGHT: u32 = 2;
  182pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  183pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  184pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  185const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  186const MAX_LINE_LEN: usize = 1024;
  187const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  188const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  189pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  190#[doc(hidden)]
  191pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  192
  193pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  194pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  195
  196pub fn render_parsed_markdown(
  197    element_id: impl Into<ElementId>,
  198    parsed: &language::ParsedMarkdown,
  199    editor_style: &EditorStyle,
  200    workspace: Option<WeakView<Workspace>>,
  201    cx: &mut WindowContext,
  202) -> InteractiveText {
  203    let code_span_background_color = cx
  204        .theme()
  205        .colors()
  206        .editor_document_highlight_read_background;
  207
  208    let highlights = gpui::combine_highlights(
  209        parsed.highlights.iter().filter_map(|(range, highlight)| {
  210            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  211            Some((range.clone(), highlight))
  212        }),
  213        parsed
  214            .regions
  215            .iter()
  216            .zip(&parsed.region_ranges)
  217            .filter_map(|(region, range)| {
  218                if region.code {
  219                    Some((
  220                        range.clone(),
  221                        HighlightStyle {
  222                            background_color: Some(code_span_background_color),
  223                            ..Default::default()
  224                        },
  225                    ))
  226                } else {
  227                    None
  228                }
  229            }),
  230    );
  231
  232    let mut links = Vec::new();
  233    let mut link_ranges = Vec::new();
  234    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  235        if let Some(link) = region.link.clone() {
  236            links.push(link);
  237            link_ranges.push(range.clone());
  238        }
  239    }
  240
  241    InteractiveText::new(
  242        element_id,
  243        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  244    )
  245    .on_click(link_ranges, move |clicked_range_ix, cx| {
  246        match &links[clicked_range_ix] {
  247            markdown::Link::Web { url } => cx.open_url(url),
  248            markdown::Link::Path { path } => {
  249                if let Some(workspace) = &workspace {
  250                    _ = workspace.update(cx, |workspace, cx| {
  251                        workspace.open_abs_path(path.clone(), false, cx).detach();
  252                    });
  253                }
  254            }
  255        }
  256    })
  257}
  258
  259#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  260pub(crate) enum InlayId {
  261    InlineCompletion(usize),
  262    Hint(usize),
  263}
  264
  265impl InlayId {
  266    fn id(&self) -> usize {
  267        match self {
  268            Self::InlineCompletion(id) => *id,
  269            Self::Hint(id) => *id,
  270        }
  271    }
  272}
  273
  274enum DiffRowHighlight {}
  275enum DocumentHighlightRead {}
  276enum DocumentHighlightWrite {}
  277enum InputComposition {}
  278
  279#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  280pub enum Navigated {
  281    Yes,
  282    No,
  283}
  284
  285impl Navigated {
  286    pub fn from_bool(yes: bool) -> Navigated {
  287        if yes {
  288            Navigated::Yes
  289        } else {
  290            Navigated::No
  291        }
  292    }
  293}
  294
  295pub fn init_settings(cx: &mut AppContext) {
  296    EditorSettings::register(cx);
  297}
  298
  299pub fn init(cx: &mut AppContext) {
  300    init_settings(cx);
  301
  302    workspace::register_project_item::<Editor>(cx);
  303    workspace::FollowableViewRegistry::register::<Editor>(cx);
  304    workspace::register_serializable_item::<Editor>(cx);
  305
  306    cx.observe_new_views(
  307        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  308            workspace.register_action(Editor::new_file);
  309            workspace.register_action(Editor::new_file_vertical);
  310            workspace.register_action(Editor::new_file_horizontal);
  311        },
  312    )
  313    .detach();
  314
  315    cx.on_action(move |_: &workspace::NewFile, cx| {
  316        let app_state = workspace::AppState::global(cx);
  317        if let Some(app_state) = app_state.upgrade() {
  318            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  319                Editor::new_file(workspace, &Default::default(), cx)
  320            })
  321            .detach();
  322        }
  323    });
  324    cx.on_action(move |_: &workspace::NewWindow, cx| {
  325        let app_state = workspace::AppState::global(cx);
  326        if let Some(app_state) = app_state.upgrade() {
  327            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  328                Editor::new_file(workspace, &Default::default(), cx)
  329            })
  330            .detach();
  331        }
  332    });
  333    git::project_diff::init(cx);
  334}
  335
  336pub struct SearchWithinRange;
  337
  338trait InvalidationRegion {
  339    fn ranges(&self) -> &[Range<Anchor>];
  340}
  341
  342#[derive(Clone, Debug, PartialEq)]
  343pub enum SelectPhase {
  344    Begin {
  345        position: DisplayPoint,
  346        add: bool,
  347        click_count: usize,
  348    },
  349    BeginColumnar {
  350        position: DisplayPoint,
  351        reset: bool,
  352        goal_column: u32,
  353    },
  354    Extend {
  355        position: DisplayPoint,
  356        click_count: usize,
  357    },
  358    Update {
  359        position: DisplayPoint,
  360        goal_column: u32,
  361        scroll_delta: gpui::Point<f32>,
  362    },
  363    End,
  364}
  365
  366#[derive(Clone, Debug)]
  367pub enum SelectMode {
  368    Character,
  369    Word(Range<Anchor>),
  370    Line(Range<Anchor>),
  371    All,
  372}
  373
  374#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  375pub enum EditorMode {
  376    SingleLine { auto_width: bool },
  377    AutoHeight { max_lines: usize },
  378    Full,
  379}
  380
  381#[derive(Copy, Clone, Debug)]
  382pub enum SoftWrap {
  383    /// Prefer not to wrap at all.
  384    ///
  385    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  386    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  387    GitDiff,
  388    /// Prefer a single line generally, unless an overly long line is encountered.
  389    None,
  390    /// Soft wrap lines that exceed the editor width.
  391    EditorWidth,
  392    /// Soft wrap lines at the preferred line length.
  393    Column(u32),
  394    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  395    Bounded(u32),
  396}
  397
  398#[derive(Clone)]
  399pub struct EditorStyle {
  400    pub background: Hsla,
  401    pub local_player: PlayerColor,
  402    pub text: TextStyle,
  403    pub scrollbar_width: Pixels,
  404    pub syntax: Arc<SyntaxTheme>,
  405    pub status: StatusColors,
  406    pub inlay_hints_style: HighlightStyle,
  407    pub inline_completion_styles: InlineCompletionStyles,
  408    pub unnecessary_code_fade: f32,
  409}
  410
  411impl Default for EditorStyle {
  412    fn default() -> Self {
  413        Self {
  414            background: Hsla::default(),
  415            local_player: PlayerColor::default(),
  416            text: TextStyle::default(),
  417            scrollbar_width: Pixels::default(),
  418            syntax: Default::default(),
  419            // HACK: Status colors don't have a real default.
  420            // We should look into removing the status colors from the editor
  421            // style and retrieve them directly from the theme.
  422            status: StatusColors::dark(),
  423            inlay_hints_style: HighlightStyle::default(),
  424            inline_completion_styles: InlineCompletionStyles {
  425                insertion: HighlightStyle::default(),
  426                whitespace: HighlightStyle::default(),
  427            },
  428            unnecessary_code_fade: Default::default(),
  429        }
  430    }
  431}
  432
  433pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  434    let show_background = language_settings::language_settings(None, None, cx)
  435        .inlay_hints
  436        .show_background;
  437
  438    HighlightStyle {
  439        color: Some(cx.theme().status().hint),
  440        background_color: show_background.then(|| cx.theme().status().hint_background),
  441        ..HighlightStyle::default()
  442    }
  443}
  444
  445pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
  446    InlineCompletionStyles {
  447        insertion: HighlightStyle {
  448            color: Some(cx.theme().status().predictive),
  449            ..HighlightStyle::default()
  450        },
  451        whitespace: HighlightStyle {
  452            background_color: Some(cx.theme().status().created_background),
  453            ..HighlightStyle::default()
  454        },
  455    }
  456}
  457
  458type CompletionId = usize;
  459
  460#[derive(Debug, Clone)]
  461struct InlineCompletionMenuHint {
  462    provider_name: &'static str,
  463    text: InlineCompletionText,
  464}
  465
  466#[derive(Clone, Debug)]
  467enum InlineCompletionText {
  468    Move(SharedString),
  469    Edit {
  470        text: SharedString,
  471        highlights: Vec<(Range<usize>, HighlightStyle)>,
  472    },
  473}
  474
  475enum InlineCompletion {
  476    Edit(Vec<(Range<Anchor>, String)>),
  477    Move(Anchor),
  478}
  479
  480struct InlineCompletionState {
  481    inlay_ids: Vec<InlayId>,
  482    completion: InlineCompletion,
  483    invalidation_range: Range<Anchor>,
  484}
  485
  486enum InlineCompletionHighlight {}
  487
  488#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  489struct EditorActionId(usize);
  490
  491impl EditorActionId {
  492    pub fn post_inc(&mut self) -> Self {
  493        let answer = self.0;
  494
  495        *self = Self(answer + 1);
  496
  497        Self(answer)
  498    }
  499}
  500
  501// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  502// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  503
  504type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  505type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  506
  507#[derive(Default)]
  508struct ScrollbarMarkerState {
  509    scrollbar_size: Size<Pixels>,
  510    dirty: bool,
  511    markers: Arc<[PaintQuad]>,
  512    pending_refresh: Option<Task<Result<()>>>,
  513}
  514
  515impl ScrollbarMarkerState {
  516    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  517        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  518    }
  519}
  520
  521#[derive(Clone, Debug)]
  522struct RunnableTasks {
  523    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  524    offset: MultiBufferOffset,
  525    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  526    column: u32,
  527    // Values of all named captures, including those starting with '_'
  528    extra_variables: HashMap<String, String>,
  529    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  530    context_range: Range<BufferOffset>,
  531}
  532
  533impl RunnableTasks {
  534    fn resolve<'a>(
  535        &'a self,
  536        cx: &'a task::TaskContext,
  537    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  538        self.templates.iter().filter_map(|(kind, template)| {
  539            template
  540                .resolve_task(&kind.to_id_base(), cx)
  541                .map(|task| (kind.clone(), task))
  542        })
  543    }
  544}
  545
  546#[derive(Clone)]
  547struct ResolvedTasks {
  548    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  549    position: Anchor,
  550}
  551#[derive(Copy, Clone, Debug)]
  552struct MultiBufferOffset(usize);
  553#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  554struct BufferOffset(usize);
  555
  556// Addons allow storing per-editor state in other crates (e.g. Vim)
  557pub trait Addon: 'static {
  558    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  559
  560    fn to_any(&self) -> &dyn std::any::Any;
  561}
  562
  563#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  564pub enum IsVimMode {
  565    Yes,
  566    No,
  567}
  568
  569/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  570///
  571/// See the [module level documentation](self) for more information.
  572pub struct Editor {
  573    focus_handle: FocusHandle,
  574    last_focused_descendant: Option<WeakFocusHandle>,
  575    /// The text buffer being edited
  576    buffer: Model<MultiBuffer>,
  577    /// Map of how text in the buffer should be displayed.
  578    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  579    pub display_map: Model<DisplayMap>,
  580    pub selections: SelectionsCollection,
  581    pub scroll_manager: ScrollManager,
  582    /// When inline assist editors are linked, they all render cursors because
  583    /// typing enters text into each of them, even the ones that aren't focused.
  584    pub(crate) show_cursor_when_unfocused: bool,
  585    columnar_selection_tail: Option<Anchor>,
  586    add_selections_state: Option<AddSelectionsState>,
  587    select_next_state: Option<SelectNextState>,
  588    select_prev_state: Option<SelectNextState>,
  589    selection_history: SelectionHistory,
  590    autoclose_regions: Vec<AutocloseRegion>,
  591    snippet_stack: InvalidationStack<SnippetState>,
  592    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  593    ime_transaction: Option<TransactionId>,
  594    active_diagnostics: Option<ActiveDiagnosticGroup>,
  595    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  596
  597    project: Option<Model<Project>>,
  598    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  599    completion_provider: Option<Box<dyn CompletionProvider>>,
  600    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  601    blink_manager: Model<BlinkManager>,
  602    show_cursor_names: bool,
  603    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  604    pub show_local_selections: bool,
  605    mode: EditorMode,
  606    show_breadcrumbs: bool,
  607    show_gutter: bool,
  608    show_line_numbers: Option<bool>,
  609    use_relative_line_numbers: Option<bool>,
  610    show_git_diff_gutter: Option<bool>,
  611    show_code_actions: Option<bool>,
  612    show_runnables: Option<bool>,
  613    show_wrap_guides: Option<bool>,
  614    show_indent_guides: Option<bool>,
  615    placeholder_text: Option<Arc<str>>,
  616    highlight_order: usize,
  617    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  618    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  619    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  620    scrollbar_marker_state: ScrollbarMarkerState,
  621    active_indent_guides_state: ActiveIndentGuidesState,
  622    nav_history: Option<ItemNavHistory>,
  623    context_menu: RefCell<Option<CodeContextMenu>>,
  624    mouse_context_menu: Option<MouseContextMenu>,
  625    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  626    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  627    signature_help_state: SignatureHelpState,
  628    auto_signature_help: Option<bool>,
  629    find_all_references_task_sources: Vec<Anchor>,
  630    next_completion_id: CompletionId,
  631    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  632    code_actions_task: Option<Task<Result<()>>>,
  633    document_highlights_task: Option<Task<()>>,
  634    linked_editing_range_task: Option<Task<Option<()>>>,
  635    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  636    pending_rename: Option<RenameState>,
  637    searchable: bool,
  638    cursor_shape: CursorShape,
  639    current_line_highlight: Option<CurrentLineHighlight>,
  640    collapse_matches: bool,
  641    autoindent_mode: Option<AutoindentMode>,
  642    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  643    input_enabled: bool,
  644    use_modal_editing: bool,
  645    read_only: bool,
  646    leader_peer_id: Option<PeerId>,
  647    remote_id: Option<ViewId>,
  648    hover_state: HoverState,
  649    gutter_hovered: bool,
  650    hovered_link_state: Option<HoveredLinkState>,
  651    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  652    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  653    active_inline_completion: Option<InlineCompletionState>,
  654    // enable_inline_completions is a switch that Vim can use to disable
  655    // inline completions based on its mode.
  656    enable_inline_completions: bool,
  657    show_inline_completions_override: Option<bool>,
  658    inlay_hint_cache: InlayHintCache,
  659    diff_map: DiffMap,
  660    next_inlay_id: usize,
  661    _subscriptions: Vec<Subscription>,
  662    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  663    gutter_dimensions: GutterDimensions,
  664    style: Option<EditorStyle>,
  665    text_style_refinement: Option<TextStyleRefinement>,
  666    next_editor_action_id: EditorActionId,
  667    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  668    use_autoclose: bool,
  669    use_auto_surround: bool,
  670    auto_replace_emoji_shortcode: bool,
  671    show_git_blame_gutter: bool,
  672    show_git_blame_inline: bool,
  673    show_git_blame_inline_delay_task: Option<Task<()>>,
  674    git_blame_inline_enabled: bool,
  675    serialize_dirty_buffers: bool,
  676    show_selection_menu: Option<bool>,
  677    blame: Option<Model<GitBlame>>,
  678    blame_subscription: Option<Subscription>,
  679    custom_context_menu: Option<
  680        Box<
  681            dyn 'static
  682                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  683        >,
  684    >,
  685    last_bounds: Option<Bounds<Pixels>>,
  686    expect_bounds_change: Option<Bounds<Pixels>>,
  687    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  688    tasks_update_task: Option<Task<()>>,
  689    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  690    breadcrumb_header: Option<String>,
  691    focused_block: Option<FocusedBlock>,
  692    next_scroll_position: NextScrollCursorCenterTopBottom,
  693    addons: HashMap<TypeId, Box<dyn Addon>>,
  694    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  695    toggle_fold_multiple_buffers: Task<()>,
  696    _scroll_cursor_center_top_bottom_task: Task<()>,
  697}
  698
  699#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  700enum NextScrollCursorCenterTopBottom {
  701    #[default]
  702    Center,
  703    Top,
  704    Bottom,
  705}
  706
  707impl NextScrollCursorCenterTopBottom {
  708    fn next(&self) -> Self {
  709        match self {
  710            Self::Center => Self::Top,
  711            Self::Top => Self::Bottom,
  712            Self::Bottom => Self::Center,
  713        }
  714    }
  715}
  716
  717#[derive(Clone)]
  718pub struct EditorSnapshot {
  719    pub mode: EditorMode,
  720    show_gutter: bool,
  721    show_line_numbers: Option<bool>,
  722    show_git_diff_gutter: Option<bool>,
  723    show_code_actions: Option<bool>,
  724    show_runnables: Option<bool>,
  725    git_blame_gutter_max_author_length: Option<usize>,
  726    pub display_snapshot: DisplaySnapshot,
  727    pub placeholder_text: Option<Arc<str>>,
  728    diff_map: DiffMapSnapshot,
  729    is_focused: bool,
  730    scroll_anchor: ScrollAnchor,
  731    ongoing_scroll: OngoingScroll,
  732    current_line_highlight: CurrentLineHighlight,
  733    gutter_hovered: bool,
  734}
  735
  736const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  737
  738#[derive(Default, Debug, Clone, Copy)]
  739pub struct GutterDimensions {
  740    pub left_padding: Pixels,
  741    pub right_padding: Pixels,
  742    pub width: Pixels,
  743    pub margin: Pixels,
  744    pub git_blame_entries_width: Option<Pixels>,
  745}
  746
  747impl GutterDimensions {
  748    /// The full width of the space taken up by the gutter.
  749    pub fn full_width(&self) -> Pixels {
  750        self.margin + self.width
  751    }
  752
  753    /// The width of the space reserved for the fold indicators,
  754    /// use alongside 'justify_end' and `gutter_width` to
  755    /// right align content with the line numbers
  756    pub fn fold_area_width(&self) -> Pixels {
  757        self.margin + self.right_padding
  758    }
  759}
  760
  761#[derive(Debug)]
  762pub struct RemoteSelection {
  763    pub replica_id: ReplicaId,
  764    pub selection: Selection<Anchor>,
  765    pub cursor_shape: CursorShape,
  766    pub peer_id: PeerId,
  767    pub line_mode: bool,
  768    pub participant_index: Option<ParticipantIndex>,
  769    pub user_name: Option<SharedString>,
  770}
  771
  772#[derive(Clone, Debug)]
  773struct SelectionHistoryEntry {
  774    selections: Arc<[Selection<Anchor>]>,
  775    select_next_state: Option<SelectNextState>,
  776    select_prev_state: Option<SelectNextState>,
  777    add_selections_state: Option<AddSelectionsState>,
  778}
  779
  780enum SelectionHistoryMode {
  781    Normal,
  782    Undoing,
  783    Redoing,
  784}
  785
  786#[derive(Clone, PartialEq, Eq, Hash)]
  787struct HoveredCursor {
  788    replica_id: u16,
  789    selection_id: usize,
  790}
  791
  792impl Default for SelectionHistoryMode {
  793    fn default() -> Self {
  794        Self::Normal
  795    }
  796}
  797
  798#[derive(Default)]
  799struct SelectionHistory {
  800    #[allow(clippy::type_complexity)]
  801    selections_by_transaction:
  802        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  803    mode: SelectionHistoryMode,
  804    undo_stack: VecDeque<SelectionHistoryEntry>,
  805    redo_stack: VecDeque<SelectionHistoryEntry>,
  806}
  807
  808impl SelectionHistory {
  809    fn insert_transaction(
  810        &mut self,
  811        transaction_id: TransactionId,
  812        selections: Arc<[Selection<Anchor>]>,
  813    ) {
  814        self.selections_by_transaction
  815            .insert(transaction_id, (selections, None));
  816    }
  817
  818    #[allow(clippy::type_complexity)]
  819    fn transaction(
  820        &self,
  821        transaction_id: TransactionId,
  822    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  823        self.selections_by_transaction.get(&transaction_id)
  824    }
  825
  826    #[allow(clippy::type_complexity)]
  827    fn transaction_mut(
  828        &mut self,
  829        transaction_id: TransactionId,
  830    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  831        self.selections_by_transaction.get_mut(&transaction_id)
  832    }
  833
  834    fn push(&mut self, entry: SelectionHistoryEntry) {
  835        if !entry.selections.is_empty() {
  836            match self.mode {
  837                SelectionHistoryMode::Normal => {
  838                    self.push_undo(entry);
  839                    self.redo_stack.clear();
  840                }
  841                SelectionHistoryMode::Undoing => self.push_redo(entry),
  842                SelectionHistoryMode::Redoing => self.push_undo(entry),
  843            }
  844        }
  845    }
  846
  847    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  848        if self
  849            .undo_stack
  850            .back()
  851            .map_or(true, |e| e.selections != entry.selections)
  852        {
  853            self.undo_stack.push_back(entry);
  854            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  855                self.undo_stack.pop_front();
  856            }
  857        }
  858    }
  859
  860    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  861        if self
  862            .redo_stack
  863            .back()
  864            .map_or(true, |e| e.selections != entry.selections)
  865        {
  866            self.redo_stack.push_back(entry);
  867            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  868                self.redo_stack.pop_front();
  869            }
  870        }
  871    }
  872}
  873
  874struct RowHighlight {
  875    index: usize,
  876    range: Range<Anchor>,
  877    color: Hsla,
  878    should_autoscroll: bool,
  879}
  880
  881#[derive(Clone, Debug)]
  882struct AddSelectionsState {
  883    above: bool,
  884    stack: Vec<usize>,
  885}
  886
  887#[derive(Clone)]
  888struct SelectNextState {
  889    query: AhoCorasick,
  890    wordwise: bool,
  891    done: bool,
  892}
  893
  894impl std::fmt::Debug for SelectNextState {
  895    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  896        f.debug_struct(std::any::type_name::<Self>())
  897            .field("wordwise", &self.wordwise)
  898            .field("done", &self.done)
  899            .finish()
  900    }
  901}
  902
  903#[derive(Debug)]
  904struct AutocloseRegion {
  905    selection_id: usize,
  906    range: Range<Anchor>,
  907    pair: BracketPair,
  908}
  909
  910#[derive(Debug)]
  911struct SnippetState {
  912    ranges: Vec<Vec<Range<Anchor>>>,
  913    active_index: usize,
  914    choices: Vec<Option<Vec<String>>>,
  915}
  916
  917#[doc(hidden)]
  918pub struct RenameState {
  919    pub range: Range<Anchor>,
  920    pub old_name: Arc<str>,
  921    pub editor: View<Editor>,
  922    block_id: CustomBlockId,
  923}
  924
  925struct InvalidationStack<T>(Vec<T>);
  926
  927struct RegisteredInlineCompletionProvider {
  928    provider: Arc<dyn InlineCompletionProviderHandle>,
  929    _subscription: Subscription,
  930}
  931
  932#[derive(Debug)]
  933struct ActiveDiagnosticGroup {
  934    primary_range: Range<Anchor>,
  935    primary_message: String,
  936    group_id: usize,
  937    blocks: HashMap<CustomBlockId, Diagnostic>,
  938    is_valid: bool,
  939}
  940
  941#[derive(Serialize, Deserialize, Clone, Debug)]
  942pub struct ClipboardSelection {
  943    pub len: usize,
  944    pub is_entire_line: bool,
  945    pub first_line_indent: u32,
  946}
  947
  948#[derive(Debug)]
  949pub(crate) struct NavigationData {
  950    cursor_anchor: Anchor,
  951    cursor_position: Point,
  952    scroll_anchor: ScrollAnchor,
  953    scroll_top_row: u32,
  954}
  955
  956#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  957pub enum GotoDefinitionKind {
  958    Symbol,
  959    Declaration,
  960    Type,
  961    Implementation,
  962}
  963
  964#[derive(Debug, Clone)]
  965enum InlayHintRefreshReason {
  966    Toggle(bool),
  967    SettingsChange(InlayHintSettings),
  968    NewLinesShown,
  969    BufferEdited(HashSet<Arc<Language>>),
  970    RefreshRequested,
  971    ExcerptsRemoved(Vec<ExcerptId>),
  972}
  973
  974impl InlayHintRefreshReason {
  975    fn description(&self) -> &'static str {
  976        match self {
  977            Self::Toggle(_) => "toggle",
  978            Self::SettingsChange(_) => "settings change",
  979            Self::NewLinesShown => "new lines shown",
  980            Self::BufferEdited(_) => "buffer edited",
  981            Self::RefreshRequested => "refresh requested",
  982            Self::ExcerptsRemoved(_) => "excerpts removed",
  983        }
  984    }
  985}
  986
  987pub(crate) struct FocusedBlock {
  988    id: BlockId,
  989    focus_handle: WeakFocusHandle,
  990}
  991
  992#[derive(Clone)]
  993struct JumpData {
  994    excerpt_id: ExcerptId,
  995    position: Point,
  996    anchor: text::Anchor,
  997    path: Option<project::ProjectPath>,
  998    line_offset_from_top: u32,
  999}
 1000
 1001impl Editor {
 1002    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1003        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1004        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1005        Self::new(
 1006            EditorMode::SingleLine { auto_width: false },
 1007            buffer,
 1008            None,
 1009            false,
 1010            cx,
 1011        )
 1012    }
 1013
 1014    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1015        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1016        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1017        Self::new(EditorMode::Full, buffer, None, false, cx)
 1018    }
 1019
 1020    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1021        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1022        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1023        Self::new(
 1024            EditorMode::SingleLine { auto_width: true },
 1025            buffer,
 1026            None,
 1027            false,
 1028            cx,
 1029        )
 1030    }
 1031
 1032    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1033        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1034        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1035        Self::new(
 1036            EditorMode::AutoHeight { max_lines },
 1037            buffer,
 1038            None,
 1039            false,
 1040            cx,
 1041        )
 1042    }
 1043
 1044    pub fn for_buffer(
 1045        buffer: Model<Buffer>,
 1046        project: Option<Model<Project>>,
 1047        cx: &mut ViewContext<Self>,
 1048    ) -> Self {
 1049        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1050        Self::new(EditorMode::Full, buffer, project, false, cx)
 1051    }
 1052
 1053    pub fn for_multibuffer(
 1054        buffer: Model<MultiBuffer>,
 1055        project: Option<Model<Project>>,
 1056        show_excerpt_controls: bool,
 1057        cx: &mut ViewContext<Self>,
 1058    ) -> Self {
 1059        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1060    }
 1061
 1062    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1063        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1064        let mut clone = Self::new(
 1065            self.mode,
 1066            self.buffer.clone(),
 1067            self.project.clone(),
 1068            show_excerpt_controls,
 1069            cx,
 1070        );
 1071        self.display_map.update(cx, |display_map, cx| {
 1072            let snapshot = display_map.snapshot(cx);
 1073            clone.display_map.update(cx, |display_map, cx| {
 1074                display_map.set_state(&snapshot, cx);
 1075            });
 1076        });
 1077        clone.selections.clone_state(&self.selections);
 1078        clone.scroll_manager.clone_state(&self.scroll_manager);
 1079        clone.searchable = self.searchable;
 1080        clone
 1081    }
 1082
 1083    pub fn new(
 1084        mode: EditorMode,
 1085        buffer: Model<MultiBuffer>,
 1086        project: Option<Model<Project>>,
 1087        show_excerpt_controls: bool,
 1088        cx: &mut ViewContext<Self>,
 1089    ) -> Self {
 1090        let style = cx.text_style();
 1091        let font_size = style.font_size.to_pixels(cx.rem_size());
 1092        let editor = cx.view().downgrade();
 1093        let fold_placeholder = FoldPlaceholder {
 1094            constrain_width: true,
 1095            render: Arc::new(move |fold_id, fold_range, cx| {
 1096                let editor = editor.clone();
 1097                div()
 1098                    .id(fold_id)
 1099                    .bg(cx.theme().colors().ghost_element_background)
 1100                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1101                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1102                    .rounded_sm()
 1103                    .size_full()
 1104                    .cursor_pointer()
 1105                    .child("")
 1106                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1107                    .on_click(move |_, cx| {
 1108                        editor
 1109                            .update(cx, |editor, cx| {
 1110                                editor.unfold_ranges(
 1111                                    &[fold_range.start..fold_range.end],
 1112                                    true,
 1113                                    false,
 1114                                    cx,
 1115                                );
 1116                                cx.stop_propagation();
 1117                            })
 1118                            .ok();
 1119                    })
 1120                    .into_any()
 1121            }),
 1122            merge_adjacent: true,
 1123            ..Default::default()
 1124        };
 1125        let display_map = cx.new_model(|cx| {
 1126            DisplayMap::new(
 1127                buffer.clone(),
 1128                style.font(),
 1129                font_size,
 1130                None,
 1131                show_excerpt_controls,
 1132                FILE_HEADER_HEIGHT,
 1133                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1134                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1135                fold_placeholder,
 1136                cx,
 1137            )
 1138        });
 1139
 1140        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1141
 1142        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1143
 1144        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1145            .then(|| language_settings::SoftWrap::None);
 1146
 1147        let mut project_subscriptions = Vec::new();
 1148        if mode == EditorMode::Full {
 1149            if let Some(project) = project.as_ref() {
 1150                if buffer.read(cx).is_singleton() {
 1151                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1152                        cx.emit(EditorEvent::TitleChanged);
 1153                    }));
 1154                }
 1155                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1156                    if let project::Event::RefreshInlayHints = event {
 1157                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1158                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1159                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1160                            let focus_handle = editor.focus_handle(cx);
 1161                            if focus_handle.is_focused(cx) {
 1162                                let snapshot = buffer.read(cx).snapshot();
 1163                                for (range, snippet) in snippet_edits {
 1164                                    let editor_range =
 1165                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1166                                    editor
 1167                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1168                                        .ok();
 1169                                }
 1170                            }
 1171                        }
 1172                    }
 1173                }));
 1174                if let Some(task_inventory) = project
 1175                    .read(cx)
 1176                    .task_store()
 1177                    .read(cx)
 1178                    .task_inventory()
 1179                    .cloned()
 1180                {
 1181                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1182                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1183                    }));
 1184                }
 1185            }
 1186        }
 1187
 1188        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1189
 1190        let inlay_hint_settings =
 1191            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1192        let focus_handle = cx.focus_handle();
 1193        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1194        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1195            .detach();
 1196        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1197            .detach();
 1198        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1199
 1200        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1201            Some(false)
 1202        } else {
 1203            None
 1204        };
 1205
 1206        let mut code_action_providers = Vec::new();
 1207        if let Some(project) = project.clone() {
 1208            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1209            code_action_providers.push(Rc::new(project) as Rc<_>);
 1210        }
 1211
 1212        let mut this = Self {
 1213            focus_handle,
 1214            show_cursor_when_unfocused: false,
 1215            last_focused_descendant: None,
 1216            buffer: buffer.clone(),
 1217            display_map: display_map.clone(),
 1218            selections,
 1219            scroll_manager: ScrollManager::new(cx),
 1220            columnar_selection_tail: None,
 1221            add_selections_state: None,
 1222            select_next_state: None,
 1223            select_prev_state: None,
 1224            selection_history: Default::default(),
 1225            autoclose_regions: Default::default(),
 1226            snippet_stack: Default::default(),
 1227            select_larger_syntax_node_stack: Vec::new(),
 1228            ime_transaction: Default::default(),
 1229            active_diagnostics: None,
 1230            soft_wrap_mode_override,
 1231            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1232            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1233            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1234            project,
 1235            blink_manager: blink_manager.clone(),
 1236            show_local_selections: true,
 1237            mode,
 1238            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1239            show_gutter: mode == EditorMode::Full,
 1240            show_line_numbers: None,
 1241            use_relative_line_numbers: None,
 1242            show_git_diff_gutter: None,
 1243            show_code_actions: None,
 1244            show_runnables: None,
 1245            show_wrap_guides: None,
 1246            show_indent_guides,
 1247            placeholder_text: None,
 1248            highlight_order: 0,
 1249            highlighted_rows: HashMap::default(),
 1250            background_highlights: Default::default(),
 1251            gutter_highlights: TreeMap::default(),
 1252            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1253            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1254            nav_history: None,
 1255            context_menu: RefCell::new(None),
 1256            mouse_context_menu: None,
 1257            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1258            completion_tasks: Default::default(),
 1259            signature_help_state: SignatureHelpState::default(),
 1260            auto_signature_help: None,
 1261            find_all_references_task_sources: Vec::new(),
 1262            next_completion_id: 0,
 1263            next_inlay_id: 0,
 1264            code_action_providers,
 1265            available_code_actions: Default::default(),
 1266            code_actions_task: Default::default(),
 1267            document_highlights_task: Default::default(),
 1268            linked_editing_range_task: Default::default(),
 1269            pending_rename: Default::default(),
 1270            searchable: true,
 1271            cursor_shape: EditorSettings::get_global(cx)
 1272                .cursor_shape
 1273                .unwrap_or_default(),
 1274            current_line_highlight: None,
 1275            autoindent_mode: Some(AutoindentMode::EachLine),
 1276            collapse_matches: false,
 1277            workspace: None,
 1278            input_enabled: true,
 1279            use_modal_editing: mode == EditorMode::Full,
 1280            read_only: false,
 1281            use_autoclose: true,
 1282            use_auto_surround: true,
 1283            auto_replace_emoji_shortcode: false,
 1284            leader_peer_id: None,
 1285            remote_id: None,
 1286            hover_state: Default::default(),
 1287            hovered_link_state: Default::default(),
 1288            inline_completion_provider: None,
 1289            active_inline_completion: None,
 1290            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1291            diff_map: DiffMap::default(),
 1292            gutter_hovered: false,
 1293            pixel_position_of_newest_cursor: None,
 1294            last_bounds: None,
 1295            expect_bounds_change: None,
 1296            gutter_dimensions: GutterDimensions::default(),
 1297            style: None,
 1298            show_cursor_names: false,
 1299            hovered_cursors: Default::default(),
 1300            next_editor_action_id: EditorActionId::default(),
 1301            editor_actions: Rc::default(),
 1302            show_inline_completions_override: None,
 1303            enable_inline_completions: true,
 1304            custom_context_menu: None,
 1305            show_git_blame_gutter: false,
 1306            show_git_blame_inline: false,
 1307            show_selection_menu: None,
 1308            show_git_blame_inline_delay_task: None,
 1309            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1310            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1311                .session
 1312                .restore_unsaved_buffers,
 1313            blame: None,
 1314            blame_subscription: None,
 1315            tasks: Default::default(),
 1316            _subscriptions: vec![
 1317                cx.observe(&buffer, Self::on_buffer_changed),
 1318                cx.subscribe(&buffer, Self::on_buffer_event),
 1319                cx.observe(&display_map, Self::on_display_map_changed),
 1320                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1321                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1322                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1323                cx.observe_window_activation(|editor, cx| {
 1324                    let active = cx.is_window_active();
 1325                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1326                        if active {
 1327                            blink_manager.enable(cx);
 1328                        } else {
 1329                            blink_manager.disable(cx);
 1330                        }
 1331                    });
 1332                }),
 1333            ],
 1334            tasks_update_task: None,
 1335            linked_edit_ranges: Default::default(),
 1336            previous_search_ranges: None,
 1337            breadcrumb_header: None,
 1338            focused_block: None,
 1339            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1340            addons: HashMap::default(),
 1341            registered_buffers: HashMap::default(),
 1342            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1343            toggle_fold_multiple_buffers: Task::ready(()),
 1344            text_style_refinement: None,
 1345        };
 1346        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1347        this._subscriptions.extend(project_subscriptions);
 1348
 1349        this.end_selection(cx);
 1350        this.scroll_manager.show_scrollbar(cx);
 1351
 1352        if mode == EditorMode::Full {
 1353            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1354            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1355
 1356            if this.git_blame_inline_enabled {
 1357                this.git_blame_inline_enabled = true;
 1358                this.start_git_blame_inline(false, cx);
 1359            }
 1360
 1361            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1362                if let Some(project) = this.project.as_ref() {
 1363                    let lsp_store = project.read(cx).lsp_store();
 1364                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1365                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1366                    });
 1367                    this.registered_buffers
 1368                        .insert(buffer.read(cx).remote_id(), handle);
 1369                }
 1370            }
 1371        }
 1372
 1373        this.report_editor_event("Editor Opened", None, cx);
 1374        this
 1375    }
 1376
 1377    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1378        self.mouse_context_menu
 1379            .as_ref()
 1380            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1381    }
 1382
 1383    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1384        let mut key_context = KeyContext::new_with_defaults();
 1385        key_context.add("Editor");
 1386        let mode = match self.mode {
 1387            EditorMode::SingleLine { .. } => "single_line",
 1388            EditorMode::AutoHeight { .. } => "auto_height",
 1389            EditorMode::Full => "full",
 1390        };
 1391
 1392        if EditorSettings::jupyter_enabled(cx) {
 1393            key_context.add("jupyter");
 1394        }
 1395
 1396        key_context.set("mode", mode);
 1397        if self.pending_rename.is_some() {
 1398            key_context.add("renaming");
 1399        }
 1400        match self.context_menu.borrow().as_ref() {
 1401            Some(CodeContextMenu::Completions(_)) => {
 1402                key_context.add("menu");
 1403                key_context.add("showing_completions")
 1404            }
 1405            Some(CodeContextMenu::CodeActions(_)) => {
 1406                key_context.add("menu");
 1407                key_context.add("showing_code_actions")
 1408            }
 1409            None => {}
 1410        }
 1411
 1412        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1413        if !self.focus_handle(cx).contains_focused(cx)
 1414            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1415        {
 1416            for addon in self.addons.values() {
 1417                addon.extend_key_context(&mut key_context, cx)
 1418            }
 1419        }
 1420
 1421        if let Some(extension) = self
 1422            .buffer
 1423            .read(cx)
 1424            .as_singleton()
 1425            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1426        {
 1427            key_context.set("extension", extension.to_string());
 1428        }
 1429
 1430        if self.has_active_inline_completion() {
 1431            key_context.add("copilot_suggestion");
 1432            key_context.add("inline_completion");
 1433        }
 1434
 1435        if !self
 1436            .selections
 1437            .disjoint
 1438            .iter()
 1439            .all(|selection| selection.start == selection.end)
 1440        {
 1441            key_context.add("selection");
 1442        }
 1443
 1444        key_context
 1445    }
 1446
 1447    pub fn new_file(
 1448        workspace: &mut Workspace,
 1449        _: &workspace::NewFile,
 1450        cx: &mut ViewContext<Workspace>,
 1451    ) {
 1452        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1453            "Failed to create buffer",
 1454            cx,
 1455            |e, _| match e.error_code() {
 1456                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1457                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1458                e.error_tag("required").unwrap_or("the latest version")
 1459            )),
 1460                _ => None,
 1461            },
 1462        );
 1463    }
 1464
 1465    pub fn new_in_workspace(
 1466        workspace: &mut Workspace,
 1467        cx: &mut ViewContext<Workspace>,
 1468    ) -> Task<Result<View<Editor>>> {
 1469        let project = workspace.project().clone();
 1470        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1471
 1472        cx.spawn(|workspace, mut cx| async move {
 1473            let buffer = create.await?;
 1474            workspace.update(&mut cx, |workspace, cx| {
 1475                let editor =
 1476                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1477                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1478                editor
 1479            })
 1480        })
 1481    }
 1482
 1483    fn new_file_vertical(
 1484        workspace: &mut Workspace,
 1485        _: &workspace::NewFileSplitVertical,
 1486        cx: &mut ViewContext<Workspace>,
 1487    ) {
 1488        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1489    }
 1490
 1491    fn new_file_horizontal(
 1492        workspace: &mut Workspace,
 1493        _: &workspace::NewFileSplitHorizontal,
 1494        cx: &mut ViewContext<Workspace>,
 1495    ) {
 1496        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1497    }
 1498
 1499    fn new_file_in_direction(
 1500        workspace: &mut Workspace,
 1501        direction: SplitDirection,
 1502        cx: &mut ViewContext<Workspace>,
 1503    ) {
 1504        let project = workspace.project().clone();
 1505        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1506
 1507        cx.spawn(|workspace, mut cx| async move {
 1508            let buffer = create.await?;
 1509            workspace.update(&mut cx, move |workspace, cx| {
 1510                workspace.split_item(
 1511                    direction,
 1512                    Box::new(
 1513                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1514                    ),
 1515                    cx,
 1516                )
 1517            })?;
 1518            anyhow::Ok(())
 1519        })
 1520        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1521            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1522                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1523                e.error_tag("required").unwrap_or("the latest version")
 1524            )),
 1525            _ => None,
 1526        });
 1527    }
 1528
 1529    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1530        self.leader_peer_id
 1531    }
 1532
 1533    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1534        &self.buffer
 1535    }
 1536
 1537    pub fn workspace(&self) -> Option<View<Workspace>> {
 1538        self.workspace.as_ref()?.0.upgrade()
 1539    }
 1540
 1541    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1542        self.buffer().read(cx).title(cx)
 1543    }
 1544
 1545    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1546        let git_blame_gutter_max_author_length = self
 1547            .render_git_blame_gutter(cx)
 1548            .then(|| {
 1549                if let Some(blame) = self.blame.as_ref() {
 1550                    let max_author_length =
 1551                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1552                    Some(max_author_length)
 1553                } else {
 1554                    None
 1555                }
 1556            })
 1557            .flatten();
 1558
 1559        EditorSnapshot {
 1560            mode: self.mode,
 1561            show_gutter: self.show_gutter,
 1562            show_line_numbers: self.show_line_numbers,
 1563            show_git_diff_gutter: self.show_git_diff_gutter,
 1564            show_code_actions: self.show_code_actions,
 1565            show_runnables: self.show_runnables,
 1566            git_blame_gutter_max_author_length,
 1567            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1568            scroll_anchor: self.scroll_manager.anchor(),
 1569            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1570            placeholder_text: self.placeholder_text.clone(),
 1571            diff_map: self.diff_map.snapshot(),
 1572            is_focused: self.focus_handle.is_focused(cx),
 1573            current_line_highlight: self
 1574                .current_line_highlight
 1575                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1576            gutter_hovered: self.gutter_hovered,
 1577        }
 1578    }
 1579
 1580    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1581        self.buffer.read(cx).language_at(point, cx)
 1582    }
 1583
 1584    pub fn file_at<T: ToOffset>(
 1585        &self,
 1586        point: T,
 1587        cx: &AppContext,
 1588    ) -> Option<Arc<dyn language::File>> {
 1589        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1590    }
 1591
 1592    pub fn active_excerpt(
 1593        &self,
 1594        cx: &AppContext,
 1595    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1596        self.buffer
 1597            .read(cx)
 1598            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1599    }
 1600
 1601    pub fn mode(&self) -> EditorMode {
 1602        self.mode
 1603    }
 1604
 1605    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1606        self.collaboration_hub.as_deref()
 1607    }
 1608
 1609    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1610        self.collaboration_hub = Some(hub);
 1611    }
 1612
 1613    pub fn set_custom_context_menu(
 1614        &mut self,
 1615        f: impl 'static
 1616            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1617    ) {
 1618        self.custom_context_menu = Some(Box::new(f))
 1619    }
 1620
 1621    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1622        self.completion_provider = provider;
 1623    }
 1624
 1625    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1626        self.semantics_provider.clone()
 1627    }
 1628
 1629    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1630        self.semantics_provider = provider;
 1631    }
 1632
 1633    pub fn set_inline_completion_provider<T>(
 1634        &mut self,
 1635        provider: Option<Model<T>>,
 1636        cx: &mut ViewContext<Self>,
 1637    ) where
 1638        T: InlineCompletionProvider,
 1639    {
 1640        self.inline_completion_provider =
 1641            provider.map(|provider| RegisteredInlineCompletionProvider {
 1642                _subscription: cx.observe(&provider, |this, _, cx| {
 1643                    if this.focus_handle.is_focused(cx) {
 1644                        this.update_visible_inline_completion(cx);
 1645                    }
 1646                }),
 1647                provider: Arc::new(provider),
 1648            });
 1649        self.refresh_inline_completion(false, false, cx);
 1650    }
 1651
 1652    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1653        self.placeholder_text.as_deref()
 1654    }
 1655
 1656    pub fn set_placeholder_text(
 1657        &mut self,
 1658        placeholder_text: impl Into<Arc<str>>,
 1659        cx: &mut ViewContext<Self>,
 1660    ) {
 1661        let placeholder_text = Some(placeholder_text.into());
 1662        if self.placeholder_text != placeholder_text {
 1663            self.placeholder_text = placeholder_text;
 1664            cx.notify();
 1665        }
 1666    }
 1667
 1668    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1669        self.cursor_shape = cursor_shape;
 1670
 1671        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1672        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1673
 1674        cx.notify();
 1675    }
 1676
 1677    pub fn set_current_line_highlight(
 1678        &mut self,
 1679        current_line_highlight: Option<CurrentLineHighlight>,
 1680    ) {
 1681        self.current_line_highlight = current_line_highlight;
 1682    }
 1683
 1684    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1685        self.collapse_matches = collapse_matches;
 1686    }
 1687
 1688    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1689        let buffers = self.buffer.read(cx).all_buffers();
 1690        let Some(lsp_store) = self.lsp_store(cx) else {
 1691            return;
 1692        };
 1693        lsp_store.update(cx, |lsp_store, cx| {
 1694            for buffer in buffers {
 1695                self.registered_buffers
 1696                    .entry(buffer.read(cx).remote_id())
 1697                    .or_insert_with(|| {
 1698                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1699                    });
 1700            }
 1701        })
 1702    }
 1703
 1704    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1705        if self.collapse_matches {
 1706            return range.start..range.start;
 1707        }
 1708        range.clone()
 1709    }
 1710
 1711    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1712        if self.display_map.read(cx).clip_at_line_ends != clip {
 1713            self.display_map
 1714                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1715        }
 1716    }
 1717
 1718    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1719        self.input_enabled = input_enabled;
 1720    }
 1721
 1722    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 1723        self.enable_inline_completions = enabled;
 1724    }
 1725
 1726    pub fn set_autoindent(&mut self, autoindent: bool) {
 1727        if autoindent {
 1728            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1729        } else {
 1730            self.autoindent_mode = None;
 1731        }
 1732    }
 1733
 1734    pub fn read_only(&self, cx: &AppContext) -> bool {
 1735        self.read_only || self.buffer.read(cx).read_only()
 1736    }
 1737
 1738    pub fn set_read_only(&mut self, read_only: bool) {
 1739        self.read_only = read_only;
 1740    }
 1741
 1742    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1743        self.use_autoclose = autoclose;
 1744    }
 1745
 1746    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1747        self.use_auto_surround = auto_surround;
 1748    }
 1749
 1750    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1751        self.auto_replace_emoji_shortcode = auto_replace;
 1752    }
 1753
 1754    pub fn toggle_inline_completions(
 1755        &mut self,
 1756        _: &ToggleInlineCompletions,
 1757        cx: &mut ViewContext<Self>,
 1758    ) {
 1759        if self.show_inline_completions_override.is_some() {
 1760            self.set_show_inline_completions(None, cx);
 1761        } else {
 1762            let cursor = self.selections.newest_anchor().head();
 1763            if let Some((buffer, cursor_buffer_position)) =
 1764                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1765            {
 1766                let show_inline_completions =
 1767                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1768                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1769            }
 1770        }
 1771    }
 1772
 1773    pub fn set_show_inline_completions(
 1774        &mut self,
 1775        show_inline_completions: Option<bool>,
 1776        cx: &mut ViewContext<Self>,
 1777    ) {
 1778        self.show_inline_completions_override = show_inline_completions;
 1779        self.refresh_inline_completion(false, true, cx);
 1780    }
 1781
 1782    fn should_show_inline_completions(
 1783        &self,
 1784        buffer: &Model<Buffer>,
 1785        buffer_position: language::Anchor,
 1786        cx: &AppContext,
 1787    ) -> bool {
 1788        if !self.snippet_stack.is_empty() {
 1789            return false;
 1790        }
 1791
 1792        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1793            return false;
 1794        }
 1795
 1796        if let Some(provider) = self.inline_completion_provider() {
 1797            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1798                show_inline_completions
 1799            } else {
 1800                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1801            }
 1802        } else {
 1803            false
 1804        }
 1805    }
 1806
 1807    fn inline_completions_disabled_in_scope(
 1808        &self,
 1809        buffer: &Model<Buffer>,
 1810        buffer_position: language::Anchor,
 1811        cx: &AppContext,
 1812    ) -> bool {
 1813        let snapshot = buffer.read(cx).snapshot();
 1814        let settings = snapshot.settings_at(buffer_position, cx);
 1815
 1816        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1817            return false;
 1818        };
 1819
 1820        scope.override_name().map_or(false, |scope_name| {
 1821            settings
 1822                .inline_completions_disabled_in
 1823                .iter()
 1824                .any(|s| s == scope_name)
 1825        })
 1826    }
 1827
 1828    pub fn set_use_modal_editing(&mut self, to: bool) {
 1829        self.use_modal_editing = to;
 1830    }
 1831
 1832    pub fn use_modal_editing(&self) -> bool {
 1833        self.use_modal_editing
 1834    }
 1835
 1836    fn selections_did_change(
 1837        &mut self,
 1838        local: bool,
 1839        old_cursor_position: &Anchor,
 1840        show_completions: bool,
 1841        cx: &mut ViewContext<Self>,
 1842    ) {
 1843        cx.invalidate_character_coordinates();
 1844
 1845        // Copy selections to primary selection buffer
 1846        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1847        if local {
 1848            let selections = self.selections.all::<usize>(cx);
 1849            let buffer_handle = self.buffer.read(cx).read(cx);
 1850
 1851            let mut text = String::new();
 1852            for (index, selection) in selections.iter().enumerate() {
 1853                let text_for_selection = buffer_handle
 1854                    .text_for_range(selection.start..selection.end)
 1855                    .collect::<String>();
 1856
 1857                text.push_str(&text_for_selection);
 1858                if index != selections.len() - 1 {
 1859                    text.push('\n');
 1860                }
 1861            }
 1862
 1863            if !text.is_empty() {
 1864                cx.write_to_primary(ClipboardItem::new_string(text));
 1865            }
 1866        }
 1867
 1868        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1869            self.buffer.update(cx, |buffer, cx| {
 1870                buffer.set_active_selections(
 1871                    &self.selections.disjoint_anchors(),
 1872                    self.selections.line_mode,
 1873                    self.cursor_shape,
 1874                    cx,
 1875                )
 1876            });
 1877        }
 1878        let display_map = self
 1879            .display_map
 1880            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1881        let buffer = &display_map.buffer_snapshot;
 1882        self.add_selections_state = None;
 1883        self.select_next_state = None;
 1884        self.select_prev_state = None;
 1885        self.select_larger_syntax_node_stack.clear();
 1886        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1887        self.snippet_stack
 1888            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1889        self.take_rename(false, cx);
 1890
 1891        let new_cursor_position = self.selections.newest_anchor().head();
 1892
 1893        self.push_to_nav_history(
 1894            *old_cursor_position,
 1895            Some(new_cursor_position.to_point(buffer)),
 1896            cx,
 1897        );
 1898
 1899        if local {
 1900            let new_cursor_position = self.selections.newest_anchor().head();
 1901            let mut context_menu = self.context_menu.borrow_mut();
 1902            let completion_menu = match context_menu.as_ref() {
 1903                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1904                _ => {
 1905                    *context_menu = None;
 1906                    None
 1907                }
 1908            };
 1909
 1910            if let Some(completion_menu) = completion_menu {
 1911                let cursor_position = new_cursor_position.to_offset(buffer);
 1912                let (word_range, kind) =
 1913                    buffer.surrounding_word(completion_menu.initial_position, true);
 1914                if kind == Some(CharKind::Word)
 1915                    && word_range.to_inclusive().contains(&cursor_position)
 1916                {
 1917                    let mut completion_menu = completion_menu.clone();
 1918                    drop(context_menu);
 1919
 1920                    let query = Self::completion_query(buffer, cursor_position);
 1921                    cx.spawn(move |this, mut cx| async move {
 1922                        completion_menu
 1923                            .filter(query.as_deref(), cx.background_executor().clone())
 1924                            .await;
 1925
 1926                        this.update(&mut cx, |this, cx| {
 1927                            let mut context_menu = this.context_menu.borrow_mut();
 1928                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1929                            else {
 1930                                return;
 1931                            };
 1932
 1933                            if menu.id > completion_menu.id {
 1934                                return;
 1935                            }
 1936
 1937                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1938                            drop(context_menu);
 1939                            cx.notify();
 1940                        })
 1941                    })
 1942                    .detach();
 1943
 1944                    if show_completions {
 1945                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1946                    }
 1947                } else {
 1948                    drop(context_menu);
 1949                    self.hide_context_menu(cx);
 1950                }
 1951            } else {
 1952                drop(context_menu);
 1953            }
 1954
 1955            hide_hover(self, cx);
 1956
 1957            if old_cursor_position.to_display_point(&display_map).row()
 1958                != new_cursor_position.to_display_point(&display_map).row()
 1959            {
 1960                self.available_code_actions.take();
 1961            }
 1962            self.refresh_code_actions(cx);
 1963            self.refresh_document_highlights(cx);
 1964            refresh_matching_bracket_highlights(self, cx);
 1965            self.update_visible_inline_completion(cx);
 1966            linked_editing_ranges::refresh_linked_ranges(self, cx);
 1967            if self.git_blame_inline_enabled {
 1968                self.start_inline_blame_timer(cx);
 1969            }
 1970        }
 1971
 1972        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 1973        cx.emit(EditorEvent::SelectionsChanged { local });
 1974
 1975        if self.selections.disjoint_anchors().len() == 1 {
 1976            cx.emit(SearchEvent::ActiveMatchChanged)
 1977        }
 1978        cx.notify();
 1979    }
 1980
 1981    pub fn change_selections<R>(
 1982        &mut self,
 1983        autoscroll: Option<Autoscroll>,
 1984        cx: &mut ViewContext<Self>,
 1985        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1986    ) -> R {
 1987        self.change_selections_inner(autoscroll, true, cx, change)
 1988    }
 1989
 1990    pub fn change_selections_inner<R>(
 1991        &mut self,
 1992        autoscroll: Option<Autoscroll>,
 1993        request_completions: bool,
 1994        cx: &mut ViewContext<Self>,
 1995        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1996    ) -> R {
 1997        let old_cursor_position = self.selections.newest_anchor().head();
 1998        self.push_to_selection_history();
 1999
 2000        let (changed, result) = self.selections.change_with(cx, change);
 2001
 2002        if changed {
 2003            if let Some(autoscroll) = autoscroll {
 2004                self.request_autoscroll(autoscroll, cx);
 2005            }
 2006            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2007
 2008            if self.should_open_signature_help_automatically(
 2009                &old_cursor_position,
 2010                self.signature_help_state.backspace_pressed(),
 2011                cx,
 2012            ) {
 2013                self.show_signature_help(&ShowSignatureHelp, cx);
 2014            }
 2015            self.signature_help_state.set_backspace_pressed(false);
 2016        }
 2017
 2018        result
 2019    }
 2020
 2021    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2022    where
 2023        I: IntoIterator<Item = (Range<S>, T)>,
 2024        S: ToOffset,
 2025        T: Into<Arc<str>>,
 2026    {
 2027        if self.read_only(cx) {
 2028            return;
 2029        }
 2030
 2031        self.buffer
 2032            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2033    }
 2034
 2035    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2036    where
 2037        I: IntoIterator<Item = (Range<S>, T)>,
 2038        S: ToOffset,
 2039        T: Into<Arc<str>>,
 2040    {
 2041        if self.read_only(cx) {
 2042            return;
 2043        }
 2044
 2045        self.buffer.update(cx, |buffer, cx| {
 2046            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2047        });
 2048    }
 2049
 2050    pub fn edit_with_block_indent<I, S, T>(
 2051        &mut self,
 2052        edits: I,
 2053        original_indent_columns: Vec<u32>,
 2054        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(
 2066                edits,
 2067                Some(AutoindentMode::Block {
 2068                    original_indent_columns,
 2069                }),
 2070                cx,
 2071            )
 2072        });
 2073    }
 2074
 2075    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2076        self.hide_context_menu(cx);
 2077
 2078        match phase {
 2079            SelectPhase::Begin {
 2080                position,
 2081                add,
 2082                click_count,
 2083            } => self.begin_selection(position, add, click_count, cx),
 2084            SelectPhase::BeginColumnar {
 2085                position,
 2086                goal_column,
 2087                reset,
 2088            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2089            SelectPhase::Extend {
 2090                position,
 2091                click_count,
 2092            } => self.extend_selection(position, click_count, cx),
 2093            SelectPhase::Update {
 2094                position,
 2095                goal_column,
 2096                scroll_delta,
 2097            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2098            SelectPhase::End => self.end_selection(cx),
 2099        }
 2100    }
 2101
 2102    fn extend_selection(
 2103        &mut self,
 2104        position: DisplayPoint,
 2105        click_count: usize,
 2106        cx: &mut ViewContext<Self>,
 2107    ) {
 2108        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2109        let tail = self.selections.newest::<usize>(cx).tail();
 2110        self.begin_selection(position, false, click_count, cx);
 2111
 2112        let position = position.to_offset(&display_map, Bias::Left);
 2113        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2114
 2115        let mut pending_selection = self
 2116            .selections
 2117            .pending_anchor()
 2118            .expect("extend_selection not called with pending selection");
 2119        if position >= tail {
 2120            pending_selection.start = tail_anchor;
 2121        } else {
 2122            pending_selection.end = tail_anchor;
 2123            pending_selection.reversed = true;
 2124        }
 2125
 2126        let mut pending_mode = self.selections.pending_mode().unwrap();
 2127        match &mut pending_mode {
 2128            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2129            _ => {}
 2130        }
 2131
 2132        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2133            s.set_pending(pending_selection, pending_mode)
 2134        });
 2135    }
 2136
 2137    fn begin_selection(
 2138        &mut self,
 2139        position: DisplayPoint,
 2140        add: bool,
 2141        click_count: usize,
 2142        cx: &mut ViewContext<Self>,
 2143    ) {
 2144        if !self.focus_handle.is_focused(cx) {
 2145            self.last_focused_descendant = None;
 2146            cx.focus(&self.focus_handle);
 2147        }
 2148
 2149        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2150        let buffer = &display_map.buffer_snapshot;
 2151        let newest_selection = self.selections.newest_anchor().clone();
 2152        let position = display_map.clip_point(position, Bias::Left);
 2153
 2154        let start;
 2155        let end;
 2156        let mode;
 2157        let mut auto_scroll;
 2158        match click_count {
 2159            1 => {
 2160                start = buffer.anchor_before(position.to_point(&display_map));
 2161                end = start;
 2162                mode = SelectMode::Character;
 2163                auto_scroll = true;
 2164            }
 2165            2 => {
 2166                let range = movement::surrounding_word(&display_map, position);
 2167                start = buffer.anchor_before(range.start.to_point(&display_map));
 2168                end = buffer.anchor_before(range.end.to_point(&display_map));
 2169                mode = SelectMode::Word(start..end);
 2170                auto_scroll = true;
 2171            }
 2172            3 => {
 2173                let position = display_map
 2174                    .clip_point(position, Bias::Left)
 2175                    .to_point(&display_map);
 2176                let line_start = display_map.prev_line_boundary(position).0;
 2177                let next_line_start = buffer.clip_point(
 2178                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2179                    Bias::Left,
 2180                );
 2181                start = buffer.anchor_before(line_start);
 2182                end = buffer.anchor_before(next_line_start);
 2183                mode = SelectMode::Line(start..end);
 2184                auto_scroll = true;
 2185            }
 2186            _ => {
 2187                start = buffer.anchor_before(0);
 2188                end = buffer.anchor_before(buffer.len());
 2189                mode = SelectMode::All;
 2190                auto_scroll = false;
 2191            }
 2192        }
 2193        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2194
 2195        let point_to_delete: Option<usize> = {
 2196            let selected_points: Vec<Selection<Point>> =
 2197                self.selections.disjoint_in_range(start..end, cx);
 2198
 2199            if !add || click_count > 1 {
 2200                None
 2201            } else if !selected_points.is_empty() {
 2202                Some(selected_points[0].id)
 2203            } else {
 2204                let clicked_point_already_selected =
 2205                    self.selections.disjoint.iter().find(|selection| {
 2206                        selection.start.to_point(buffer) == start.to_point(buffer)
 2207                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2208                    });
 2209
 2210                clicked_point_already_selected.map(|selection| selection.id)
 2211            }
 2212        };
 2213
 2214        let selections_count = self.selections.count();
 2215
 2216        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2217            if let Some(point_to_delete) = point_to_delete {
 2218                s.delete(point_to_delete);
 2219
 2220                if selections_count == 1 {
 2221                    s.set_pending_anchor_range(start..end, mode);
 2222                }
 2223            } else {
 2224                if !add {
 2225                    s.clear_disjoint();
 2226                } else if click_count > 1 {
 2227                    s.delete(newest_selection.id)
 2228                }
 2229
 2230                s.set_pending_anchor_range(start..end, mode);
 2231            }
 2232        });
 2233    }
 2234
 2235    fn begin_columnar_selection(
 2236        &mut self,
 2237        position: DisplayPoint,
 2238        goal_column: u32,
 2239        reset: bool,
 2240        cx: &mut ViewContext<Self>,
 2241    ) {
 2242        if !self.focus_handle.is_focused(cx) {
 2243            self.last_focused_descendant = None;
 2244            cx.focus(&self.focus_handle);
 2245        }
 2246
 2247        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2248
 2249        if reset {
 2250            let pointer_position = display_map
 2251                .buffer_snapshot
 2252                .anchor_before(position.to_point(&display_map));
 2253
 2254            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2255                s.clear_disjoint();
 2256                s.set_pending_anchor_range(
 2257                    pointer_position..pointer_position,
 2258                    SelectMode::Character,
 2259                );
 2260            });
 2261        }
 2262
 2263        let tail = self.selections.newest::<Point>(cx).tail();
 2264        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2265
 2266        if !reset {
 2267            self.select_columns(
 2268                tail.to_display_point(&display_map),
 2269                position,
 2270                goal_column,
 2271                &display_map,
 2272                cx,
 2273            );
 2274        }
 2275    }
 2276
 2277    fn update_selection(
 2278        &mut self,
 2279        position: DisplayPoint,
 2280        goal_column: u32,
 2281        scroll_delta: gpui::Point<f32>,
 2282        cx: &mut ViewContext<Self>,
 2283    ) {
 2284        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2285
 2286        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2287            let tail = tail.to_display_point(&display_map);
 2288            self.select_columns(tail, position, goal_column, &display_map, cx);
 2289        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2290            let buffer = self.buffer.read(cx).snapshot(cx);
 2291            let head;
 2292            let tail;
 2293            let mode = self.selections.pending_mode().unwrap();
 2294            match &mode {
 2295                SelectMode::Character => {
 2296                    head = position.to_point(&display_map);
 2297                    tail = pending.tail().to_point(&buffer);
 2298                }
 2299                SelectMode::Word(original_range) => {
 2300                    let original_display_range = original_range.start.to_display_point(&display_map)
 2301                        ..original_range.end.to_display_point(&display_map);
 2302                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2303                        ..original_display_range.end.to_point(&display_map);
 2304                    if movement::is_inside_word(&display_map, position)
 2305                        || original_display_range.contains(&position)
 2306                    {
 2307                        let word_range = movement::surrounding_word(&display_map, position);
 2308                        if word_range.start < original_display_range.start {
 2309                            head = word_range.start.to_point(&display_map);
 2310                        } else {
 2311                            head = word_range.end.to_point(&display_map);
 2312                        }
 2313                    } else {
 2314                        head = position.to_point(&display_map);
 2315                    }
 2316
 2317                    if head <= original_buffer_range.start {
 2318                        tail = original_buffer_range.end;
 2319                    } else {
 2320                        tail = original_buffer_range.start;
 2321                    }
 2322                }
 2323                SelectMode::Line(original_range) => {
 2324                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2325
 2326                    let position = display_map
 2327                        .clip_point(position, Bias::Left)
 2328                        .to_point(&display_map);
 2329                    let line_start = display_map.prev_line_boundary(position).0;
 2330                    let next_line_start = buffer.clip_point(
 2331                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2332                        Bias::Left,
 2333                    );
 2334
 2335                    if line_start < original_range.start {
 2336                        head = line_start
 2337                    } else {
 2338                        head = next_line_start
 2339                    }
 2340
 2341                    if head <= original_range.start {
 2342                        tail = original_range.end;
 2343                    } else {
 2344                        tail = original_range.start;
 2345                    }
 2346                }
 2347                SelectMode::All => {
 2348                    return;
 2349                }
 2350            };
 2351
 2352            if head < tail {
 2353                pending.start = buffer.anchor_before(head);
 2354                pending.end = buffer.anchor_before(tail);
 2355                pending.reversed = true;
 2356            } else {
 2357                pending.start = buffer.anchor_before(tail);
 2358                pending.end = buffer.anchor_before(head);
 2359                pending.reversed = false;
 2360            }
 2361
 2362            self.change_selections(None, cx, |s| {
 2363                s.set_pending(pending, mode);
 2364            });
 2365        } else {
 2366            log::error!("update_selection dispatched with no pending selection");
 2367            return;
 2368        }
 2369
 2370        self.apply_scroll_delta(scroll_delta, cx);
 2371        cx.notify();
 2372    }
 2373
 2374    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2375        self.columnar_selection_tail.take();
 2376        if self.selections.pending_anchor().is_some() {
 2377            let selections = self.selections.all::<usize>(cx);
 2378            self.change_selections(None, cx, |s| {
 2379                s.select(selections);
 2380                s.clear_pending();
 2381            });
 2382        }
 2383    }
 2384
 2385    fn select_columns(
 2386        &mut self,
 2387        tail: DisplayPoint,
 2388        head: DisplayPoint,
 2389        goal_column: u32,
 2390        display_map: &DisplaySnapshot,
 2391        cx: &mut ViewContext<Self>,
 2392    ) {
 2393        let start_row = cmp::min(tail.row(), head.row());
 2394        let end_row = cmp::max(tail.row(), head.row());
 2395        let start_column = cmp::min(tail.column(), goal_column);
 2396        let end_column = cmp::max(tail.column(), goal_column);
 2397        let reversed = start_column < tail.column();
 2398
 2399        let selection_ranges = (start_row.0..=end_row.0)
 2400            .map(DisplayRow)
 2401            .filter_map(|row| {
 2402                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2403                    let start = display_map
 2404                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2405                        .to_point(display_map);
 2406                    let end = display_map
 2407                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2408                        .to_point(display_map);
 2409                    if reversed {
 2410                        Some(end..start)
 2411                    } else {
 2412                        Some(start..end)
 2413                    }
 2414                } else {
 2415                    None
 2416                }
 2417            })
 2418            .collect::<Vec<_>>();
 2419
 2420        self.change_selections(None, cx, |s| {
 2421            s.select_ranges(selection_ranges);
 2422        });
 2423        cx.notify();
 2424    }
 2425
 2426    pub fn has_pending_nonempty_selection(&self) -> bool {
 2427        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2428            Some(Selection { start, end, .. }) => start != end,
 2429            None => false,
 2430        };
 2431
 2432        pending_nonempty_selection
 2433            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2434    }
 2435
 2436    pub fn has_pending_selection(&self) -> bool {
 2437        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2438    }
 2439
 2440    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2441        if self.clear_expanded_diff_hunks(cx) {
 2442            cx.notify();
 2443            return;
 2444        }
 2445        if self.dismiss_menus_and_popups(true, cx) {
 2446            return;
 2447        }
 2448
 2449        if self.mode == EditorMode::Full
 2450            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2451        {
 2452            return;
 2453        }
 2454
 2455        cx.propagate();
 2456    }
 2457
 2458    pub fn dismiss_menus_and_popups(
 2459        &mut self,
 2460        should_report_inline_completion_event: bool,
 2461        cx: &mut ViewContext<Self>,
 2462    ) -> bool {
 2463        if self.take_rename(false, cx).is_some() {
 2464            return true;
 2465        }
 2466
 2467        if hide_hover(self, cx) {
 2468            return true;
 2469        }
 2470
 2471        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2472            return true;
 2473        }
 2474
 2475        if self.hide_context_menu(cx).is_some() {
 2476            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2477                self.update_visible_inline_completion(cx);
 2478            }
 2479            return true;
 2480        }
 2481
 2482        if self.mouse_context_menu.take().is_some() {
 2483            return true;
 2484        }
 2485
 2486        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2487            return true;
 2488        }
 2489
 2490        if self.snippet_stack.pop().is_some() {
 2491            return true;
 2492        }
 2493
 2494        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2495            self.dismiss_diagnostics(cx);
 2496            return true;
 2497        }
 2498
 2499        false
 2500    }
 2501
 2502    fn linked_editing_ranges_for(
 2503        &self,
 2504        selection: Range<text::Anchor>,
 2505        cx: &AppContext,
 2506    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2507        if self.linked_edit_ranges.is_empty() {
 2508            return None;
 2509        }
 2510        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2511            selection.end.buffer_id.and_then(|end_buffer_id| {
 2512                if selection.start.buffer_id != Some(end_buffer_id) {
 2513                    return None;
 2514                }
 2515                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2516                let snapshot = buffer.read(cx).snapshot();
 2517                self.linked_edit_ranges
 2518                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2519                    .map(|ranges| (ranges, snapshot, buffer))
 2520            })?;
 2521        use text::ToOffset as TO;
 2522        // find offset from the start of current range to current cursor position
 2523        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2524
 2525        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2526        let start_difference = start_offset - start_byte_offset;
 2527        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2528        let end_difference = end_offset - start_byte_offset;
 2529        // Current range has associated linked ranges.
 2530        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2531        for range in linked_ranges.iter() {
 2532            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2533            let end_offset = start_offset + end_difference;
 2534            let start_offset = start_offset + start_difference;
 2535            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2536                continue;
 2537            }
 2538            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 2539                if s.start.buffer_id != selection.start.buffer_id
 2540                    || s.end.buffer_id != selection.end.buffer_id
 2541                {
 2542                    return false;
 2543                }
 2544                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2545                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2546            }) {
 2547                continue;
 2548            }
 2549            let start = buffer_snapshot.anchor_after(start_offset);
 2550            let end = buffer_snapshot.anchor_after(end_offset);
 2551            linked_edits
 2552                .entry(buffer.clone())
 2553                .or_default()
 2554                .push(start..end);
 2555        }
 2556        Some(linked_edits)
 2557    }
 2558
 2559    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2560        let text: Arc<str> = text.into();
 2561
 2562        if self.read_only(cx) {
 2563            return;
 2564        }
 2565
 2566        let selections = self.selections.all_adjusted(cx);
 2567        let mut bracket_inserted = false;
 2568        let mut edits = Vec::new();
 2569        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2570        let mut new_selections = Vec::with_capacity(selections.len());
 2571        let mut new_autoclose_regions = Vec::new();
 2572        let snapshot = self.buffer.read(cx).read(cx);
 2573
 2574        for (selection, autoclose_region) in
 2575            self.selections_with_autoclose_regions(selections, &snapshot)
 2576        {
 2577            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2578                // Determine if the inserted text matches the opening or closing
 2579                // bracket of any of this language's bracket pairs.
 2580                let mut bracket_pair = None;
 2581                let mut is_bracket_pair_start = false;
 2582                let mut is_bracket_pair_end = false;
 2583                if !text.is_empty() {
 2584                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2585                    //  and they are removing the character that triggered IME popup.
 2586                    for (pair, enabled) in scope.brackets() {
 2587                        if !pair.close && !pair.surround {
 2588                            continue;
 2589                        }
 2590
 2591                        if enabled && pair.start.ends_with(text.as_ref()) {
 2592                            let prefix_len = pair.start.len() - text.len();
 2593                            let preceding_text_matches_prefix = prefix_len == 0
 2594                                || (selection.start.column >= (prefix_len as u32)
 2595                                    && snapshot.contains_str_at(
 2596                                        Point::new(
 2597                                            selection.start.row,
 2598                                            selection.start.column - (prefix_len as u32),
 2599                                        ),
 2600                                        &pair.start[..prefix_len],
 2601                                    ));
 2602                            if preceding_text_matches_prefix {
 2603                                bracket_pair = Some(pair.clone());
 2604                                is_bracket_pair_start = true;
 2605                                break;
 2606                            }
 2607                        }
 2608                        if pair.end.as_str() == text.as_ref() {
 2609                            bracket_pair = Some(pair.clone());
 2610                            is_bracket_pair_end = true;
 2611                            break;
 2612                        }
 2613                    }
 2614                }
 2615
 2616                if let Some(bracket_pair) = bracket_pair {
 2617                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2618                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2619                    let auto_surround =
 2620                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2621                    if selection.is_empty() {
 2622                        if is_bracket_pair_start {
 2623                            // If the inserted text is a suffix of an opening bracket and the
 2624                            // selection is preceded by the rest of the opening bracket, then
 2625                            // insert the closing bracket.
 2626                            let following_text_allows_autoclose = snapshot
 2627                                .chars_at(selection.start)
 2628                                .next()
 2629                                .map_or(true, |c| scope.should_autoclose_before(c));
 2630
 2631                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2632                                && bracket_pair.start.len() == 1
 2633                            {
 2634                                let target = bracket_pair.start.chars().next().unwrap();
 2635                                let current_line_count = snapshot
 2636                                    .reversed_chars_at(selection.start)
 2637                                    .take_while(|&c| c != '\n')
 2638                                    .filter(|&c| c == target)
 2639                                    .count();
 2640                                current_line_count % 2 == 1
 2641                            } else {
 2642                                false
 2643                            };
 2644
 2645                            if autoclose
 2646                                && bracket_pair.close
 2647                                && following_text_allows_autoclose
 2648                                && !is_closing_quote
 2649                            {
 2650                                let anchor = snapshot.anchor_before(selection.end);
 2651                                new_selections.push((selection.map(|_| anchor), text.len()));
 2652                                new_autoclose_regions.push((
 2653                                    anchor,
 2654                                    text.len(),
 2655                                    selection.id,
 2656                                    bracket_pair.clone(),
 2657                                ));
 2658                                edits.push((
 2659                                    selection.range(),
 2660                                    format!("{}{}", text, bracket_pair.end).into(),
 2661                                ));
 2662                                bracket_inserted = true;
 2663                                continue;
 2664                            }
 2665                        }
 2666
 2667                        if let Some(region) = autoclose_region {
 2668                            // If the selection is followed by an auto-inserted closing bracket,
 2669                            // then don't insert that closing bracket again; just move the selection
 2670                            // past the closing bracket.
 2671                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2672                                && text.as_ref() == region.pair.end.as_str();
 2673                            if should_skip {
 2674                                let anchor = snapshot.anchor_after(selection.end);
 2675                                new_selections
 2676                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2677                                continue;
 2678                            }
 2679                        }
 2680
 2681                        let always_treat_brackets_as_autoclosed = snapshot
 2682                            .settings_at(selection.start, cx)
 2683                            .always_treat_brackets_as_autoclosed;
 2684                        if always_treat_brackets_as_autoclosed
 2685                            && is_bracket_pair_end
 2686                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2687                        {
 2688                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2689                            // and the inserted text is a closing bracket and the selection is followed
 2690                            // by the closing bracket then move the selection past the closing bracket.
 2691                            let anchor = snapshot.anchor_after(selection.end);
 2692                            new_selections.push((selection.map(|_| anchor), text.len()));
 2693                            continue;
 2694                        }
 2695                    }
 2696                    // If an opening bracket is 1 character long and is typed while
 2697                    // text is selected, then surround that text with the bracket pair.
 2698                    else if auto_surround
 2699                        && bracket_pair.surround
 2700                        && is_bracket_pair_start
 2701                        && bracket_pair.start.chars().count() == 1
 2702                    {
 2703                        edits.push((selection.start..selection.start, text.clone()));
 2704                        edits.push((
 2705                            selection.end..selection.end,
 2706                            bracket_pair.end.as_str().into(),
 2707                        ));
 2708                        bracket_inserted = true;
 2709                        new_selections.push((
 2710                            Selection {
 2711                                id: selection.id,
 2712                                start: snapshot.anchor_after(selection.start),
 2713                                end: snapshot.anchor_before(selection.end),
 2714                                reversed: selection.reversed,
 2715                                goal: selection.goal,
 2716                            },
 2717                            0,
 2718                        ));
 2719                        continue;
 2720                    }
 2721                }
 2722            }
 2723
 2724            if self.auto_replace_emoji_shortcode
 2725                && selection.is_empty()
 2726                && text.as_ref().ends_with(':')
 2727            {
 2728                if let Some(possible_emoji_short_code) =
 2729                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2730                {
 2731                    if !possible_emoji_short_code.is_empty() {
 2732                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2733                            let emoji_shortcode_start = Point::new(
 2734                                selection.start.row,
 2735                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2736                            );
 2737
 2738                            // Remove shortcode from buffer
 2739                            edits.push((
 2740                                emoji_shortcode_start..selection.start,
 2741                                "".to_string().into(),
 2742                            ));
 2743                            new_selections.push((
 2744                                Selection {
 2745                                    id: selection.id,
 2746                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2747                                    end: snapshot.anchor_before(selection.start),
 2748                                    reversed: selection.reversed,
 2749                                    goal: selection.goal,
 2750                                },
 2751                                0,
 2752                            ));
 2753
 2754                            // Insert emoji
 2755                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2756                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2757                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2758
 2759                            continue;
 2760                        }
 2761                    }
 2762                }
 2763            }
 2764
 2765            // If not handling any auto-close operation, then just replace the selected
 2766            // text with the given input and move the selection to the end of the
 2767            // newly inserted text.
 2768            let anchor = snapshot.anchor_after(selection.end);
 2769            if !self.linked_edit_ranges.is_empty() {
 2770                let start_anchor = snapshot.anchor_before(selection.start);
 2771
 2772                let is_word_char = text.chars().next().map_or(true, |char| {
 2773                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2774                    classifier.is_word(char)
 2775                });
 2776
 2777                if is_word_char {
 2778                    if let Some(ranges) = self
 2779                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2780                    {
 2781                        for (buffer, edits) in ranges {
 2782                            linked_edits
 2783                                .entry(buffer.clone())
 2784                                .or_default()
 2785                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2786                        }
 2787                    }
 2788                }
 2789            }
 2790
 2791            new_selections.push((selection.map(|_| anchor), 0));
 2792            edits.push((selection.start..selection.end, text.clone()));
 2793        }
 2794
 2795        drop(snapshot);
 2796
 2797        self.transact(cx, |this, cx| {
 2798            this.buffer.update(cx, |buffer, cx| {
 2799                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2800            });
 2801            for (buffer, edits) in linked_edits {
 2802                buffer.update(cx, |buffer, cx| {
 2803                    let snapshot = buffer.snapshot();
 2804                    let edits = edits
 2805                        .into_iter()
 2806                        .map(|(range, text)| {
 2807                            use text::ToPoint as TP;
 2808                            let end_point = TP::to_point(&range.end, &snapshot);
 2809                            let start_point = TP::to_point(&range.start, &snapshot);
 2810                            (start_point..end_point, text)
 2811                        })
 2812                        .sorted_by_key(|(range, _)| range.start)
 2813                        .collect::<Vec<_>>();
 2814                    buffer.edit(edits, None, cx);
 2815                })
 2816            }
 2817            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2818            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2819            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2820            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2821                .zip(new_selection_deltas)
 2822                .map(|(selection, delta)| Selection {
 2823                    id: selection.id,
 2824                    start: selection.start + delta,
 2825                    end: selection.end + delta,
 2826                    reversed: selection.reversed,
 2827                    goal: SelectionGoal::None,
 2828                })
 2829                .collect::<Vec<_>>();
 2830
 2831            let mut i = 0;
 2832            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2833                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2834                let start = map.buffer_snapshot.anchor_before(position);
 2835                let end = map.buffer_snapshot.anchor_after(position);
 2836                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2837                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2838                        Ordering::Less => i += 1,
 2839                        Ordering::Greater => break,
 2840                        Ordering::Equal => {
 2841                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2842                                Ordering::Less => i += 1,
 2843                                Ordering::Equal => break,
 2844                                Ordering::Greater => break,
 2845                            }
 2846                        }
 2847                    }
 2848                }
 2849                this.autoclose_regions.insert(
 2850                    i,
 2851                    AutocloseRegion {
 2852                        selection_id,
 2853                        range: start..end,
 2854                        pair,
 2855                    },
 2856                );
 2857            }
 2858
 2859            let had_active_inline_completion = this.has_active_inline_completion();
 2860            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2861                s.select(new_selections)
 2862            });
 2863
 2864            if !bracket_inserted {
 2865                if let Some(on_type_format_task) =
 2866                    this.trigger_on_type_formatting(text.to_string(), cx)
 2867                {
 2868                    on_type_format_task.detach_and_log_err(cx);
 2869                }
 2870            }
 2871
 2872            let editor_settings = EditorSettings::get_global(cx);
 2873            if bracket_inserted
 2874                && (editor_settings.auto_signature_help
 2875                    || editor_settings.show_signature_help_after_edits)
 2876            {
 2877                this.show_signature_help(&ShowSignatureHelp, cx);
 2878            }
 2879
 2880            let trigger_in_words =
 2881                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2882            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2883            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2884            this.refresh_inline_completion(true, false, cx);
 2885        });
 2886    }
 2887
 2888    fn find_possible_emoji_shortcode_at_position(
 2889        snapshot: &MultiBufferSnapshot,
 2890        position: Point,
 2891    ) -> Option<String> {
 2892        let mut chars = Vec::new();
 2893        let mut found_colon = false;
 2894        for char in snapshot.reversed_chars_at(position).take(100) {
 2895            // Found a possible emoji shortcode in the middle of the buffer
 2896            if found_colon {
 2897                if char.is_whitespace() {
 2898                    chars.reverse();
 2899                    return Some(chars.iter().collect());
 2900                }
 2901                // If the previous character is not a whitespace, we are in the middle of a word
 2902                // and we only want to complete the shortcode if the word is made up of other emojis
 2903                let mut containing_word = String::new();
 2904                for ch in snapshot
 2905                    .reversed_chars_at(position)
 2906                    .skip(chars.len() + 1)
 2907                    .take(100)
 2908                {
 2909                    if ch.is_whitespace() {
 2910                        break;
 2911                    }
 2912                    containing_word.push(ch);
 2913                }
 2914                let containing_word = containing_word.chars().rev().collect::<String>();
 2915                if util::word_consists_of_emojis(containing_word.as_str()) {
 2916                    chars.reverse();
 2917                    return Some(chars.iter().collect());
 2918                }
 2919            }
 2920
 2921            if char.is_whitespace() || !char.is_ascii() {
 2922                return None;
 2923            }
 2924            if char == ':' {
 2925                found_colon = true;
 2926            } else {
 2927                chars.push(char);
 2928            }
 2929        }
 2930        // Found a possible emoji shortcode at the beginning of the buffer
 2931        chars.reverse();
 2932        Some(chars.iter().collect())
 2933    }
 2934
 2935    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2936        self.transact(cx, |this, cx| {
 2937            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2938                let selections = this.selections.all::<usize>(cx);
 2939                let multi_buffer = this.buffer.read(cx);
 2940                let buffer = multi_buffer.snapshot(cx);
 2941                selections
 2942                    .iter()
 2943                    .map(|selection| {
 2944                        let start_point = selection.start.to_point(&buffer);
 2945                        let mut indent =
 2946                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2947                        indent.len = cmp::min(indent.len, start_point.column);
 2948                        let start = selection.start;
 2949                        let end = selection.end;
 2950                        let selection_is_empty = start == end;
 2951                        let language_scope = buffer.language_scope_at(start);
 2952                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2953                            &language_scope
 2954                        {
 2955                            let leading_whitespace_len = buffer
 2956                                .reversed_chars_at(start)
 2957                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2958                                .map(|c| c.len_utf8())
 2959                                .sum::<usize>();
 2960
 2961                            let trailing_whitespace_len = buffer
 2962                                .chars_at(end)
 2963                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2964                                .map(|c| c.len_utf8())
 2965                                .sum::<usize>();
 2966
 2967                            let insert_extra_newline =
 2968                                language.brackets().any(|(pair, enabled)| {
 2969                                    let pair_start = pair.start.trim_end();
 2970                                    let pair_end = pair.end.trim_start();
 2971
 2972                                    enabled
 2973                                        && pair.newline
 2974                                        && buffer.contains_str_at(
 2975                                            end + trailing_whitespace_len,
 2976                                            pair_end,
 2977                                        )
 2978                                        && buffer.contains_str_at(
 2979                                            (start - leading_whitespace_len)
 2980                                                .saturating_sub(pair_start.len()),
 2981                                            pair_start,
 2982                                        )
 2983                                });
 2984
 2985                            // Comment extension on newline is allowed only for cursor selections
 2986                            let comment_delimiter = maybe!({
 2987                                if !selection_is_empty {
 2988                                    return None;
 2989                                }
 2990
 2991                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 2992                                    return None;
 2993                                }
 2994
 2995                                let delimiters = language.line_comment_prefixes();
 2996                                let max_len_of_delimiter =
 2997                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 2998                                let (snapshot, range) =
 2999                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3000
 3001                                let mut index_of_first_non_whitespace = 0;
 3002                                let comment_candidate = snapshot
 3003                                    .chars_for_range(range)
 3004                                    .skip_while(|c| {
 3005                                        let should_skip = c.is_whitespace();
 3006                                        if should_skip {
 3007                                            index_of_first_non_whitespace += 1;
 3008                                        }
 3009                                        should_skip
 3010                                    })
 3011                                    .take(max_len_of_delimiter)
 3012                                    .collect::<String>();
 3013                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3014                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3015                                })?;
 3016                                let cursor_is_placed_after_comment_marker =
 3017                                    index_of_first_non_whitespace + comment_prefix.len()
 3018                                        <= start_point.column as usize;
 3019                                if cursor_is_placed_after_comment_marker {
 3020                                    Some(comment_prefix.clone())
 3021                                } else {
 3022                                    None
 3023                                }
 3024                            });
 3025                            (comment_delimiter, insert_extra_newline)
 3026                        } else {
 3027                            (None, false)
 3028                        };
 3029
 3030                        let capacity_for_delimiter = comment_delimiter
 3031                            .as_deref()
 3032                            .map(str::len)
 3033                            .unwrap_or_default();
 3034                        let mut new_text =
 3035                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3036                        new_text.push('\n');
 3037                        new_text.extend(indent.chars());
 3038                        if let Some(delimiter) = &comment_delimiter {
 3039                            new_text.push_str(delimiter);
 3040                        }
 3041                        if insert_extra_newline {
 3042                            new_text = new_text.repeat(2);
 3043                        }
 3044
 3045                        let anchor = buffer.anchor_after(end);
 3046                        let new_selection = selection.map(|_| anchor);
 3047                        (
 3048                            (start..end, new_text),
 3049                            (insert_extra_newline, new_selection),
 3050                        )
 3051                    })
 3052                    .unzip()
 3053            };
 3054
 3055            this.edit_with_autoindent(edits, cx);
 3056            let buffer = this.buffer.read(cx).snapshot(cx);
 3057            let new_selections = selection_fixup_info
 3058                .into_iter()
 3059                .map(|(extra_newline_inserted, new_selection)| {
 3060                    let mut cursor = new_selection.end.to_point(&buffer);
 3061                    if extra_newline_inserted {
 3062                        cursor.row -= 1;
 3063                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3064                    }
 3065                    new_selection.map(|_| cursor)
 3066                })
 3067                .collect();
 3068
 3069            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3070            this.refresh_inline_completion(true, false, cx);
 3071        });
 3072    }
 3073
 3074    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3075        let buffer = self.buffer.read(cx);
 3076        let snapshot = buffer.snapshot(cx);
 3077
 3078        let mut edits = Vec::new();
 3079        let mut rows = Vec::new();
 3080
 3081        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3082            let cursor = selection.head();
 3083            let row = cursor.row;
 3084
 3085            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3086
 3087            let newline = "\n".to_string();
 3088            edits.push((start_of_line..start_of_line, newline));
 3089
 3090            rows.push(row + rows_inserted as u32);
 3091        }
 3092
 3093        self.transact(cx, |editor, cx| {
 3094            editor.edit(edits, cx);
 3095
 3096            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3097                let mut index = 0;
 3098                s.move_cursors_with(|map, _, _| {
 3099                    let row = rows[index];
 3100                    index += 1;
 3101
 3102                    let point = Point::new(row, 0);
 3103                    let boundary = map.next_line_boundary(point).1;
 3104                    let clipped = map.clip_point(boundary, Bias::Left);
 3105
 3106                    (clipped, SelectionGoal::None)
 3107                });
 3108            });
 3109
 3110            let mut indent_edits = Vec::new();
 3111            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3112            for row in rows {
 3113                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3114                for (row, indent) in indents {
 3115                    if indent.len == 0 {
 3116                        continue;
 3117                    }
 3118
 3119                    let text = match indent.kind {
 3120                        IndentKind::Space => " ".repeat(indent.len as usize),
 3121                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3122                    };
 3123                    let point = Point::new(row.0, 0);
 3124                    indent_edits.push((point..point, text));
 3125                }
 3126            }
 3127            editor.edit(indent_edits, cx);
 3128        });
 3129    }
 3130
 3131    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3132        let buffer = self.buffer.read(cx);
 3133        let snapshot = buffer.snapshot(cx);
 3134
 3135        let mut edits = Vec::new();
 3136        let mut rows = Vec::new();
 3137        let mut rows_inserted = 0;
 3138
 3139        for selection in self.selections.all_adjusted(cx) {
 3140            let cursor = selection.head();
 3141            let row = cursor.row;
 3142
 3143            let point = Point::new(row + 1, 0);
 3144            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3145
 3146            let newline = "\n".to_string();
 3147            edits.push((start_of_line..start_of_line, newline));
 3148
 3149            rows_inserted += 1;
 3150            rows.push(row + rows_inserted);
 3151        }
 3152
 3153        self.transact(cx, |editor, cx| {
 3154            editor.edit(edits, cx);
 3155
 3156            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3157                let mut index = 0;
 3158                s.move_cursors_with(|map, _, _| {
 3159                    let row = rows[index];
 3160                    index += 1;
 3161
 3162                    let point = Point::new(row, 0);
 3163                    let boundary = map.next_line_boundary(point).1;
 3164                    let clipped = map.clip_point(boundary, Bias::Left);
 3165
 3166                    (clipped, SelectionGoal::None)
 3167                });
 3168            });
 3169
 3170            let mut indent_edits = Vec::new();
 3171            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3172            for row in rows {
 3173                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3174                for (row, indent) in indents {
 3175                    if indent.len == 0 {
 3176                        continue;
 3177                    }
 3178
 3179                    let text = match indent.kind {
 3180                        IndentKind::Space => " ".repeat(indent.len as usize),
 3181                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3182                    };
 3183                    let point = Point::new(row.0, 0);
 3184                    indent_edits.push((point..point, text));
 3185                }
 3186            }
 3187            editor.edit(indent_edits, cx);
 3188        });
 3189    }
 3190
 3191    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3192        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3193            original_indent_columns: Vec::new(),
 3194        });
 3195        self.insert_with_autoindent_mode(text, autoindent, cx);
 3196    }
 3197
 3198    fn insert_with_autoindent_mode(
 3199        &mut self,
 3200        text: &str,
 3201        autoindent_mode: Option<AutoindentMode>,
 3202        cx: &mut ViewContext<Self>,
 3203    ) {
 3204        if self.read_only(cx) {
 3205            return;
 3206        }
 3207
 3208        let text: Arc<str> = text.into();
 3209        self.transact(cx, |this, cx| {
 3210            let old_selections = this.selections.all_adjusted(cx);
 3211            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3212                let anchors = {
 3213                    let snapshot = buffer.read(cx);
 3214                    old_selections
 3215                        .iter()
 3216                        .map(|s| {
 3217                            let anchor = snapshot.anchor_after(s.head());
 3218                            s.map(|_| anchor)
 3219                        })
 3220                        .collect::<Vec<_>>()
 3221                };
 3222                buffer.edit(
 3223                    old_selections
 3224                        .iter()
 3225                        .map(|s| (s.start..s.end, text.clone())),
 3226                    autoindent_mode,
 3227                    cx,
 3228                );
 3229                anchors
 3230            });
 3231
 3232            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3233                s.select_anchors(selection_anchors);
 3234            })
 3235        });
 3236    }
 3237
 3238    fn trigger_completion_on_input(
 3239        &mut self,
 3240        text: &str,
 3241        trigger_in_words: bool,
 3242        cx: &mut ViewContext<Self>,
 3243    ) {
 3244        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3245            self.show_completions(
 3246                &ShowCompletions {
 3247                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3248                },
 3249                cx,
 3250            );
 3251        } else {
 3252            self.hide_context_menu(cx);
 3253        }
 3254    }
 3255
 3256    fn is_completion_trigger(
 3257        &self,
 3258        text: &str,
 3259        trigger_in_words: bool,
 3260        cx: &mut ViewContext<Self>,
 3261    ) -> bool {
 3262        let position = self.selections.newest_anchor().head();
 3263        let multibuffer = self.buffer.read(cx);
 3264        let Some(buffer) = position
 3265            .buffer_id
 3266            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3267        else {
 3268            return false;
 3269        };
 3270
 3271        if let Some(completion_provider) = &self.completion_provider {
 3272            completion_provider.is_completion_trigger(
 3273                &buffer,
 3274                position.text_anchor,
 3275                text,
 3276                trigger_in_words,
 3277                cx,
 3278            )
 3279        } else {
 3280            false
 3281        }
 3282    }
 3283
 3284    /// If any empty selections is touching the start of its innermost containing autoclose
 3285    /// region, expand it to select the brackets.
 3286    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3287        let selections = self.selections.all::<usize>(cx);
 3288        let buffer = self.buffer.read(cx).read(cx);
 3289        let new_selections = self
 3290            .selections_with_autoclose_regions(selections, &buffer)
 3291            .map(|(mut selection, region)| {
 3292                if !selection.is_empty() {
 3293                    return selection;
 3294                }
 3295
 3296                if let Some(region) = region {
 3297                    let mut range = region.range.to_offset(&buffer);
 3298                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3299                        range.start -= region.pair.start.len();
 3300                        if buffer.contains_str_at(range.start, &region.pair.start)
 3301                            && buffer.contains_str_at(range.end, &region.pair.end)
 3302                        {
 3303                            range.end += region.pair.end.len();
 3304                            selection.start = range.start;
 3305                            selection.end = range.end;
 3306
 3307                            return selection;
 3308                        }
 3309                    }
 3310                }
 3311
 3312                let always_treat_brackets_as_autoclosed = buffer
 3313                    .settings_at(selection.start, cx)
 3314                    .always_treat_brackets_as_autoclosed;
 3315
 3316                if !always_treat_brackets_as_autoclosed {
 3317                    return selection;
 3318                }
 3319
 3320                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3321                    for (pair, enabled) in scope.brackets() {
 3322                        if !enabled || !pair.close {
 3323                            continue;
 3324                        }
 3325
 3326                        if buffer.contains_str_at(selection.start, &pair.end) {
 3327                            let pair_start_len = pair.start.len();
 3328                            if buffer.contains_str_at(
 3329                                selection.start.saturating_sub(pair_start_len),
 3330                                &pair.start,
 3331                            ) {
 3332                                selection.start -= pair_start_len;
 3333                                selection.end += pair.end.len();
 3334
 3335                                return selection;
 3336                            }
 3337                        }
 3338                    }
 3339                }
 3340
 3341                selection
 3342            })
 3343            .collect();
 3344
 3345        drop(buffer);
 3346        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3347    }
 3348
 3349    /// Iterate the given selections, and for each one, find the smallest surrounding
 3350    /// autoclose region. This uses the ordering of the selections and the autoclose
 3351    /// regions to avoid repeated comparisons.
 3352    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3353        &'a self,
 3354        selections: impl IntoIterator<Item = Selection<D>>,
 3355        buffer: &'a MultiBufferSnapshot,
 3356    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3357        let mut i = 0;
 3358        let mut regions = self.autoclose_regions.as_slice();
 3359        selections.into_iter().map(move |selection| {
 3360            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3361
 3362            let mut enclosing = None;
 3363            while let Some(pair_state) = regions.get(i) {
 3364                if pair_state.range.end.to_offset(buffer) < range.start {
 3365                    regions = &regions[i + 1..];
 3366                    i = 0;
 3367                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3368                    break;
 3369                } else {
 3370                    if pair_state.selection_id == selection.id {
 3371                        enclosing = Some(pair_state);
 3372                    }
 3373                    i += 1;
 3374                }
 3375            }
 3376
 3377            (selection, enclosing)
 3378        })
 3379    }
 3380
 3381    /// Remove any autoclose regions that no longer contain their selection.
 3382    fn invalidate_autoclose_regions(
 3383        &mut self,
 3384        mut selections: &[Selection<Anchor>],
 3385        buffer: &MultiBufferSnapshot,
 3386    ) {
 3387        self.autoclose_regions.retain(|state| {
 3388            let mut i = 0;
 3389            while let Some(selection) = selections.get(i) {
 3390                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3391                    selections = &selections[1..];
 3392                    continue;
 3393                }
 3394                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3395                    break;
 3396                }
 3397                if selection.id == state.selection_id {
 3398                    return true;
 3399                } else {
 3400                    i += 1;
 3401                }
 3402            }
 3403            false
 3404        });
 3405    }
 3406
 3407    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3408        let offset = position.to_offset(buffer);
 3409        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3410        if offset > word_range.start && kind == Some(CharKind::Word) {
 3411            Some(
 3412                buffer
 3413                    .text_for_range(word_range.start..offset)
 3414                    .collect::<String>(),
 3415            )
 3416        } else {
 3417            None
 3418        }
 3419    }
 3420
 3421    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3422        self.refresh_inlay_hints(
 3423            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3424            cx,
 3425        );
 3426    }
 3427
 3428    pub fn inlay_hints_enabled(&self) -> bool {
 3429        self.inlay_hint_cache.enabled
 3430    }
 3431
 3432    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3433        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3434            return;
 3435        }
 3436
 3437        let reason_description = reason.description();
 3438        let ignore_debounce = matches!(
 3439            reason,
 3440            InlayHintRefreshReason::SettingsChange(_)
 3441                | InlayHintRefreshReason::Toggle(_)
 3442                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3443        );
 3444        let (invalidate_cache, required_languages) = match reason {
 3445            InlayHintRefreshReason::Toggle(enabled) => {
 3446                self.inlay_hint_cache.enabled = enabled;
 3447                if enabled {
 3448                    (InvalidationStrategy::RefreshRequested, None)
 3449                } else {
 3450                    self.inlay_hint_cache.clear();
 3451                    self.splice_inlays(
 3452                        self.visible_inlay_hints(cx)
 3453                            .iter()
 3454                            .map(|inlay| inlay.id)
 3455                            .collect(),
 3456                        Vec::new(),
 3457                        cx,
 3458                    );
 3459                    return;
 3460                }
 3461            }
 3462            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3463                match self.inlay_hint_cache.update_settings(
 3464                    &self.buffer,
 3465                    new_settings,
 3466                    self.visible_inlay_hints(cx),
 3467                    cx,
 3468                ) {
 3469                    ControlFlow::Break(Some(InlaySplice {
 3470                        to_remove,
 3471                        to_insert,
 3472                    })) => {
 3473                        self.splice_inlays(to_remove, to_insert, cx);
 3474                        return;
 3475                    }
 3476                    ControlFlow::Break(None) => return,
 3477                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3478                }
 3479            }
 3480            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3481                if let Some(InlaySplice {
 3482                    to_remove,
 3483                    to_insert,
 3484                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3485                {
 3486                    self.splice_inlays(to_remove, to_insert, cx);
 3487                }
 3488                return;
 3489            }
 3490            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3491            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3492                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3493            }
 3494            InlayHintRefreshReason::RefreshRequested => {
 3495                (InvalidationStrategy::RefreshRequested, None)
 3496            }
 3497        };
 3498
 3499        if let Some(InlaySplice {
 3500            to_remove,
 3501            to_insert,
 3502        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3503            reason_description,
 3504            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3505            invalidate_cache,
 3506            ignore_debounce,
 3507            cx,
 3508        ) {
 3509            self.splice_inlays(to_remove, to_insert, cx);
 3510        }
 3511    }
 3512
 3513    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3514        self.display_map
 3515            .read(cx)
 3516            .current_inlays()
 3517            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3518            .cloned()
 3519            .collect()
 3520    }
 3521
 3522    pub fn excerpts_for_inlay_hints_query(
 3523        &self,
 3524        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3525        cx: &mut ViewContext<Editor>,
 3526    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3527        let Some(project) = self.project.as_ref() else {
 3528            return HashMap::default();
 3529        };
 3530        let project = project.read(cx);
 3531        let multi_buffer = self.buffer().read(cx);
 3532        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3533        let multi_buffer_visible_start = self
 3534            .scroll_manager
 3535            .anchor()
 3536            .anchor
 3537            .to_point(&multi_buffer_snapshot);
 3538        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3539            multi_buffer_visible_start
 3540                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3541            Bias::Left,
 3542        );
 3543        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3544        multi_buffer
 3545            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3546            .into_iter()
 3547            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3548            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3549                let buffer = buffer_handle.read(cx);
 3550                let buffer_file = project::File::from_dyn(buffer.file())?;
 3551                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3552                let worktree_entry = buffer_worktree
 3553                    .read(cx)
 3554                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3555                if worktree_entry.is_ignored {
 3556                    return None;
 3557                }
 3558
 3559                let language = buffer.language()?;
 3560                if let Some(restrict_to_languages) = restrict_to_languages {
 3561                    if !restrict_to_languages.contains(language) {
 3562                        return None;
 3563                    }
 3564                }
 3565                Some((
 3566                    excerpt_id,
 3567                    (
 3568                        buffer_handle,
 3569                        buffer.version().clone(),
 3570                        excerpt_visible_range,
 3571                    ),
 3572                ))
 3573            })
 3574            .collect()
 3575    }
 3576
 3577    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3578        TextLayoutDetails {
 3579            text_system: cx.text_system().clone(),
 3580            editor_style: self.style.clone().unwrap(),
 3581            rem_size: cx.rem_size(),
 3582            scroll_anchor: self.scroll_manager.anchor(),
 3583            visible_rows: self.visible_line_count(),
 3584            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3585        }
 3586    }
 3587
 3588    fn splice_inlays(
 3589        &self,
 3590        to_remove: Vec<InlayId>,
 3591        to_insert: Vec<Inlay>,
 3592        cx: &mut ViewContext<Self>,
 3593    ) {
 3594        self.display_map.update(cx, |display_map, cx| {
 3595            display_map.splice_inlays(to_remove, to_insert, cx)
 3596        });
 3597        cx.notify();
 3598    }
 3599
 3600    fn trigger_on_type_formatting(
 3601        &self,
 3602        input: String,
 3603        cx: &mut ViewContext<Self>,
 3604    ) -> Option<Task<Result<()>>> {
 3605        if input.len() != 1 {
 3606            return None;
 3607        }
 3608
 3609        let project = self.project.as_ref()?;
 3610        let position = self.selections.newest_anchor().head();
 3611        let (buffer, buffer_position) = self
 3612            .buffer
 3613            .read(cx)
 3614            .text_anchor_for_position(position, cx)?;
 3615
 3616        let settings = language_settings::language_settings(
 3617            buffer
 3618                .read(cx)
 3619                .language_at(buffer_position)
 3620                .map(|l| l.name()),
 3621            buffer.read(cx).file(),
 3622            cx,
 3623        );
 3624        if !settings.use_on_type_format {
 3625            return None;
 3626        }
 3627
 3628        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3629        // hence we do LSP request & edit on host side only — add formats to host's history.
 3630        let push_to_lsp_host_history = true;
 3631        // If this is not the host, append its history with new edits.
 3632        let push_to_client_history = project.read(cx).is_via_collab();
 3633
 3634        let on_type_formatting = project.update(cx, |project, cx| {
 3635            project.on_type_format(
 3636                buffer.clone(),
 3637                buffer_position,
 3638                input,
 3639                push_to_lsp_host_history,
 3640                cx,
 3641            )
 3642        });
 3643        Some(cx.spawn(|editor, mut cx| async move {
 3644            if let Some(transaction) = on_type_formatting.await? {
 3645                if push_to_client_history {
 3646                    buffer
 3647                        .update(&mut cx, |buffer, _| {
 3648                            buffer.push_transaction(transaction, Instant::now());
 3649                        })
 3650                        .ok();
 3651                }
 3652                editor.update(&mut cx, |editor, cx| {
 3653                    editor.refresh_document_highlights(cx);
 3654                })?;
 3655            }
 3656            Ok(())
 3657        }))
 3658    }
 3659
 3660    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3661        if self.pending_rename.is_some() {
 3662            return;
 3663        }
 3664
 3665        let Some(provider) = self.completion_provider.as_ref() else {
 3666            return;
 3667        };
 3668
 3669        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3670            return;
 3671        }
 3672
 3673        let position = self.selections.newest_anchor().head();
 3674        let (buffer, buffer_position) =
 3675            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3676                output
 3677            } else {
 3678                return;
 3679            };
 3680        let show_completion_documentation = buffer
 3681            .read(cx)
 3682            .snapshot()
 3683            .settings_at(buffer_position, cx)
 3684            .show_completion_documentation;
 3685
 3686        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3687
 3688        let trigger_kind = match &options.trigger {
 3689            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3690                CompletionTriggerKind::TRIGGER_CHARACTER
 3691            }
 3692            _ => CompletionTriggerKind::INVOKED,
 3693        };
 3694        let completion_context = CompletionContext {
 3695            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3696                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3697                    Some(String::from(trigger))
 3698                } else {
 3699                    None
 3700                }
 3701            }),
 3702            trigger_kind,
 3703        };
 3704        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3705        let sort_completions = provider.sort_completions();
 3706
 3707        let id = post_inc(&mut self.next_completion_id);
 3708        let task = cx.spawn(|editor, mut cx| {
 3709            async move {
 3710                editor.update(&mut cx, |this, _| {
 3711                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3712                })?;
 3713                let completions = completions.await.log_err();
 3714                let menu = if let Some(completions) = completions {
 3715                    let mut menu = CompletionsMenu::new(
 3716                        id,
 3717                        sort_completions,
 3718                        show_completion_documentation,
 3719                        position,
 3720                        buffer.clone(),
 3721                        completions.into(),
 3722                    );
 3723
 3724                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3725                        .await;
 3726
 3727                    menu.visible().then_some(menu)
 3728                } else {
 3729                    None
 3730                };
 3731
 3732                editor.update(&mut cx, |editor, cx| {
 3733                    match editor.context_menu.borrow().as_ref() {
 3734                        None => {}
 3735                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3736                            if prev_menu.id > id {
 3737                                return;
 3738                            }
 3739                        }
 3740                        _ => return,
 3741                    }
 3742
 3743                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3744                        let mut menu = menu.unwrap();
 3745                        menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
 3746
 3747                        if editor.show_inline_completions_in_menu(cx) {
 3748                            if let Some(hint) = editor.inline_completion_menu_hint(cx) {
 3749                                editor.hide_active_inline_completion(cx);
 3750                                menu.show_inline_completion_hint(hint);
 3751                            }
 3752                        } else {
 3753                            editor.discard_inline_completion(false, cx);
 3754                        }
 3755
 3756                        *editor.context_menu.borrow_mut() =
 3757                            Some(CodeContextMenu::Completions(menu));
 3758
 3759                        cx.notify();
 3760                    } else if editor.completion_tasks.len() <= 1 {
 3761                        // If there are no more completion tasks and the last menu was
 3762                        // empty, we should hide it.
 3763                        let was_hidden = editor.hide_context_menu(cx).is_none();
 3764                        // If it was already hidden and we don't show inline
 3765                        // completions in the menu, we should also show the
 3766                        // inline-completion when available.
 3767                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3768                            editor.update_visible_inline_completion(cx);
 3769                        }
 3770                    }
 3771                })?;
 3772
 3773                Ok::<_, anyhow::Error>(())
 3774            }
 3775            .log_err()
 3776        });
 3777
 3778        self.completion_tasks.push((id, task));
 3779    }
 3780
 3781    pub fn confirm_completion(
 3782        &mut self,
 3783        action: &ConfirmCompletion,
 3784        cx: &mut ViewContext<Self>,
 3785    ) -> Option<Task<Result<()>>> {
 3786        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3787    }
 3788
 3789    pub fn compose_completion(
 3790        &mut self,
 3791        action: &ComposeCompletion,
 3792        cx: &mut ViewContext<Self>,
 3793    ) -> Option<Task<Result<()>>> {
 3794        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3795    }
 3796
 3797    fn do_completion(
 3798        &mut self,
 3799        item_ix: Option<usize>,
 3800        intent: CompletionIntent,
 3801        cx: &mut ViewContext<Editor>,
 3802    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3803        use language::ToOffset as _;
 3804
 3805        let completions_menu =
 3806            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3807                menu
 3808            } else {
 3809                return None;
 3810            };
 3811
 3812        let mat = completions_menu
 3813            .entries
 3814            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3815
 3816        let mat = match mat {
 3817            CompletionEntry::InlineCompletionHint { .. } => {
 3818                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3819                cx.stop_propagation();
 3820                return Some(Task::ready(Ok(())));
 3821            }
 3822            CompletionEntry::Match(mat) => {
 3823                if self.show_inline_completions_in_menu(cx) {
 3824                    self.discard_inline_completion(true, cx);
 3825                }
 3826                mat
 3827            }
 3828        };
 3829
 3830        let buffer_handle = completions_menu.buffer;
 3831        let completions = completions_menu.completions.borrow_mut();
 3832        let completion = completions.get(mat.candidate_id)?;
 3833        cx.stop_propagation();
 3834
 3835        let snippet;
 3836        let text;
 3837
 3838        if completion.is_snippet() {
 3839            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3840            text = snippet.as_ref().unwrap().text.clone();
 3841        } else {
 3842            snippet = None;
 3843            text = completion.new_text.clone();
 3844        };
 3845        let selections = self.selections.all::<usize>(cx);
 3846        let buffer = buffer_handle.read(cx);
 3847        let old_range = completion.old_range.to_offset(buffer);
 3848        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3849
 3850        let newest_selection = self.selections.newest_anchor();
 3851        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3852            return None;
 3853        }
 3854
 3855        let lookbehind = newest_selection
 3856            .start
 3857            .text_anchor
 3858            .to_offset(buffer)
 3859            .saturating_sub(old_range.start);
 3860        let lookahead = old_range
 3861            .end
 3862            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3863        let mut common_prefix_len = old_text
 3864            .bytes()
 3865            .zip(text.bytes())
 3866            .take_while(|(a, b)| a == b)
 3867            .count();
 3868
 3869        let snapshot = self.buffer.read(cx).snapshot(cx);
 3870        let mut range_to_replace: Option<Range<isize>> = None;
 3871        let mut ranges = Vec::new();
 3872        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3873        for selection in &selections {
 3874            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3875                let start = selection.start.saturating_sub(lookbehind);
 3876                let end = selection.end + lookahead;
 3877                if selection.id == newest_selection.id {
 3878                    range_to_replace = Some(
 3879                        ((start + common_prefix_len) as isize - selection.start as isize)
 3880                            ..(end as isize - selection.start as isize),
 3881                    );
 3882                }
 3883                ranges.push(start + common_prefix_len..end);
 3884            } else {
 3885                common_prefix_len = 0;
 3886                ranges.clear();
 3887                ranges.extend(selections.iter().map(|s| {
 3888                    if s.id == newest_selection.id {
 3889                        range_to_replace = Some(
 3890                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3891                                - selection.start as isize
 3892                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3893                                    - selection.start as isize,
 3894                        );
 3895                        old_range.clone()
 3896                    } else {
 3897                        s.start..s.end
 3898                    }
 3899                }));
 3900                break;
 3901            }
 3902            if !self.linked_edit_ranges.is_empty() {
 3903                let start_anchor = snapshot.anchor_before(selection.head());
 3904                let end_anchor = snapshot.anchor_after(selection.tail());
 3905                if let Some(ranges) = self
 3906                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3907                {
 3908                    for (buffer, edits) in ranges {
 3909                        linked_edits.entry(buffer.clone()).or_default().extend(
 3910                            edits
 3911                                .into_iter()
 3912                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3913                        );
 3914                    }
 3915                }
 3916            }
 3917        }
 3918        let text = &text[common_prefix_len..];
 3919
 3920        cx.emit(EditorEvent::InputHandled {
 3921            utf16_range_to_replace: range_to_replace,
 3922            text: text.into(),
 3923        });
 3924
 3925        self.transact(cx, |this, cx| {
 3926            if let Some(mut snippet) = snippet {
 3927                snippet.text = text.to_string();
 3928                for tabstop in snippet
 3929                    .tabstops
 3930                    .iter_mut()
 3931                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3932                {
 3933                    tabstop.start -= common_prefix_len as isize;
 3934                    tabstop.end -= common_prefix_len as isize;
 3935                }
 3936
 3937                this.insert_snippet(&ranges, snippet, cx).log_err();
 3938            } else {
 3939                this.buffer.update(cx, |buffer, cx| {
 3940                    buffer.edit(
 3941                        ranges.iter().map(|range| (range.clone(), text)),
 3942                        this.autoindent_mode.clone(),
 3943                        cx,
 3944                    );
 3945                });
 3946            }
 3947            for (buffer, edits) in linked_edits {
 3948                buffer.update(cx, |buffer, cx| {
 3949                    let snapshot = buffer.snapshot();
 3950                    let edits = edits
 3951                        .into_iter()
 3952                        .map(|(range, text)| {
 3953                            use text::ToPoint as TP;
 3954                            let end_point = TP::to_point(&range.end, &snapshot);
 3955                            let start_point = TP::to_point(&range.start, &snapshot);
 3956                            (start_point..end_point, text)
 3957                        })
 3958                        .sorted_by_key(|(range, _)| range.start)
 3959                        .collect::<Vec<_>>();
 3960                    buffer.edit(edits, None, cx);
 3961                })
 3962            }
 3963
 3964            this.refresh_inline_completion(true, false, cx);
 3965        });
 3966
 3967        let show_new_completions_on_confirm = completion
 3968            .confirm
 3969            .as_ref()
 3970            .map_or(false, |confirm| confirm(intent, cx));
 3971        if show_new_completions_on_confirm {
 3972            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3973        }
 3974
 3975        let provider = self.completion_provider.as_ref()?;
 3976        let apply_edits = provider.apply_additional_edits_for_completion(
 3977            buffer_handle,
 3978            completion.clone(),
 3979            true,
 3980            cx,
 3981        );
 3982
 3983        let editor_settings = EditorSettings::get_global(cx);
 3984        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 3985            // After the code completion is finished, users often want to know what signatures are needed.
 3986            // so we should automatically call signature_help
 3987            self.show_signature_help(&ShowSignatureHelp, cx);
 3988        }
 3989
 3990        Some(cx.foreground_executor().spawn(async move {
 3991            apply_edits.await?;
 3992            Ok(())
 3993        }))
 3994    }
 3995
 3996    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 3997        let mut context_menu = self.context_menu.borrow_mut();
 3998        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 3999            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4000                // Toggle if we're selecting the same one
 4001                *context_menu = None;
 4002                cx.notify();
 4003                return;
 4004            } else {
 4005                // Otherwise, clear it and start a new one
 4006                *context_menu = None;
 4007                cx.notify();
 4008            }
 4009        }
 4010        drop(context_menu);
 4011        let snapshot = self.snapshot(cx);
 4012        let deployed_from_indicator = action.deployed_from_indicator;
 4013        let mut task = self.code_actions_task.take();
 4014        let action = action.clone();
 4015        cx.spawn(|editor, mut cx| async move {
 4016            while let Some(prev_task) = task {
 4017                prev_task.await.log_err();
 4018                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4019            }
 4020
 4021            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4022                if editor.focus_handle.is_focused(cx) {
 4023                    let multibuffer_point = action
 4024                        .deployed_from_indicator
 4025                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4026                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4027                    let (buffer, buffer_row) = snapshot
 4028                        .buffer_snapshot
 4029                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4030                        .and_then(|(buffer_snapshot, range)| {
 4031                            editor
 4032                                .buffer
 4033                                .read(cx)
 4034                                .buffer(buffer_snapshot.remote_id())
 4035                                .map(|buffer| (buffer, range.start.row))
 4036                        })?;
 4037                    let (_, code_actions) = editor
 4038                        .available_code_actions
 4039                        .clone()
 4040                        .and_then(|(location, code_actions)| {
 4041                            let snapshot = location.buffer.read(cx).snapshot();
 4042                            let point_range = location.range.to_point(&snapshot);
 4043                            let point_range = point_range.start.row..=point_range.end.row;
 4044                            if point_range.contains(&buffer_row) {
 4045                                Some((location, code_actions))
 4046                            } else {
 4047                                None
 4048                            }
 4049                        })
 4050                        .unzip();
 4051                    let buffer_id = buffer.read(cx).remote_id();
 4052                    let tasks = editor
 4053                        .tasks
 4054                        .get(&(buffer_id, buffer_row))
 4055                        .map(|t| Arc::new(t.to_owned()));
 4056                    if tasks.is_none() && code_actions.is_none() {
 4057                        return None;
 4058                    }
 4059
 4060                    editor.completion_tasks.clear();
 4061                    editor.discard_inline_completion(false, cx);
 4062                    let task_context =
 4063                        tasks
 4064                            .as_ref()
 4065                            .zip(editor.project.clone())
 4066                            .map(|(tasks, project)| {
 4067                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4068                            });
 4069
 4070                    Some(cx.spawn(|editor, mut cx| async move {
 4071                        let task_context = match task_context {
 4072                            Some(task_context) => task_context.await,
 4073                            None => None,
 4074                        };
 4075                        let resolved_tasks =
 4076                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4077                                Rc::new(ResolvedTasks {
 4078                                    templates: tasks.resolve(&task_context).collect(),
 4079                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4080                                        multibuffer_point.row,
 4081                                        tasks.column,
 4082                                    )),
 4083                                })
 4084                            });
 4085                        let spawn_straight_away = resolved_tasks
 4086                            .as_ref()
 4087                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4088                            && code_actions
 4089                                .as_ref()
 4090                                .map_or(true, |actions| actions.is_empty());
 4091                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4092                            *editor.context_menu.borrow_mut() =
 4093                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4094                                    buffer,
 4095                                    actions: CodeActionContents {
 4096                                        tasks: resolved_tasks,
 4097                                        actions: code_actions,
 4098                                    },
 4099                                    selected_item: Default::default(),
 4100                                    scroll_handle: UniformListScrollHandle::default(),
 4101                                    deployed_from_indicator,
 4102                                }));
 4103                            if spawn_straight_away {
 4104                                if let Some(task) = editor.confirm_code_action(
 4105                                    &ConfirmCodeAction { item_ix: Some(0) },
 4106                                    cx,
 4107                                ) {
 4108                                    cx.notify();
 4109                                    return task;
 4110                                }
 4111                            }
 4112                            cx.notify();
 4113                            Task::ready(Ok(()))
 4114                        }) {
 4115                            task.await
 4116                        } else {
 4117                            Ok(())
 4118                        }
 4119                    }))
 4120                } else {
 4121                    Some(Task::ready(Ok(())))
 4122                }
 4123            })?;
 4124            if let Some(task) = spawned_test_task {
 4125                task.await?;
 4126            }
 4127
 4128            Ok::<_, anyhow::Error>(())
 4129        })
 4130        .detach_and_log_err(cx);
 4131    }
 4132
 4133    pub fn confirm_code_action(
 4134        &mut self,
 4135        action: &ConfirmCodeAction,
 4136        cx: &mut ViewContext<Self>,
 4137    ) -> Option<Task<Result<()>>> {
 4138        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4139            menu
 4140        } else {
 4141            return None;
 4142        };
 4143        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4144        let action = actions_menu.actions.get(action_ix)?;
 4145        let title = action.label();
 4146        let buffer = actions_menu.buffer;
 4147        let workspace = self.workspace()?;
 4148
 4149        match action {
 4150            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4151                workspace.update(cx, |workspace, cx| {
 4152                    workspace::tasks::schedule_resolved_task(
 4153                        workspace,
 4154                        task_source_kind,
 4155                        resolved_task,
 4156                        false,
 4157                        cx,
 4158                    );
 4159
 4160                    Some(Task::ready(Ok(())))
 4161                })
 4162            }
 4163            CodeActionsItem::CodeAction {
 4164                excerpt_id,
 4165                action,
 4166                provider,
 4167            } => {
 4168                let apply_code_action =
 4169                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4170                let workspace = workspace.downgrade();
 4171                Some(cx.spawn(|editor, cx| async move {
 4172                    let project_transaction = apply_code_action.await?;
 4173                    Self::open_project_transaction(
 4174                        &editor,
 4175                        workspace,
 4176                        project_transaction,
 4177                        title,
 4178                        cx,
 4179                    )
 4180                    .await
 4181                }))
 4182            }
 4183        }
 4184    }
 4185
 4186    pub async fn open_project_transaction(
 4187        this: &WeakView<Editor>,
 4188        workspace: WeakView<Workspace>,
 4189        transaction: ProjectTransaction,
 4190        title: String,
 4191        mut cx: AsyncWindowContext,
 4192    ) -> Result<()> {
 4193        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4194        cx.update(|cx| {
 4195            entries.sort_unstable_by_key(|(buffer, _)| {
 4196                buffer.read(cx).file().map(|f| f.path().clone())
 4197            });
 4198        })?;
 4199
 4200        // If the project transaction's edits are all contained within this editor, then
 4201        // avoid opening a new editor to display them.
 4202
 4203        if let Some((buffer, transaction)) = entries.first() {
 4204            if entries.len() == 1 {
 4205                let excerpt = this.update(&mut cx, |editor, cx| {
 4206                    editor
 4207                        .buffer()
 4208                        .read(cx)
 4209                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4210                })?;
 4211                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4212                    if excerpted_buffer == *buffer {
 4213                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4214                            let excerpt_range = excerpt_range.to_offset(buffer);
 4215                            buffer
 4216                                .edited_ranges_for_transaction::<usize>(transaction)
 4217                                .all(|range| {
 4218                                    excerpt_range.start <= range.start
 4219                                        && excerpt_range.end >= range.end
 4220                                })
 4221                        })?;
 4222
 4223                        if all_edits_within_excerpt {
 4224                            return Ok(());
 4225                        }
 4226                    }
 4227                }
 4228            }
 4229        } else {
 4230            return Ok(());
 4231        }
 4232
 4233        let mut ranges_to_highlight = Vec::new();
 4234        let excerpt_buffer = cx.new_model(|cx| {
 4235            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4236            for (buffer_handle, transaction) in &entries {
 4237                let buffer = buffer_handle.read(cx);
 4238                ranges_to_highlight.extend(
 4239                    multibuffer.push_excerpts_with_context_lines(
 4240                        buffer_handle.clone(),
 4241                        buffer
 4242                            .edited_ranges_for_transaction::<usize>(transaction)
 4243                            .collect(),
 4244                        DEFAULT_MULTIBUFFER_CONTEXT,
 4245                        cx,
 4246                    ),
 4247                );
 4248            }
 4249            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4250            multibuffer
 4251        })?;
 4252
 4253        workspace.update(&mut cx, |workspace, cx| {
 4254            let project = workspace.project().clone();
 4255            let editor =
 4256                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4257            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4258            editor.update(cx, |editor, cx| {
 4259                editor.highlight_background::<Self>(
 4260                    &ranges_to_highlight,
 4261                    |theme| theme.editor_highlighted_line_background,
 4262                    cx,
 4263                );
 4264            });
 4265        })?;
 4266
 4267        Ok(())
 4268    }
 4269
 4270    pub fn clear_code_action_providers(&mut self) {
 4271        self.code_action_providers.clear();
 4272        self.available_code_actions.take();
 4273    }
 4274
 4275    pub fn push_code_action_provider(
 4276        &mut self,
 4277        provider: Rc<dyn CodeActionProvider>,
 4278        cx: &mut ViewContext<Self>,
 4279    ) {
 4280        self.code_action_providers.push(provider);
 4281        self.refresh_code_actions(cx);
 4282    }
 4283
 4284    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4285        let buffer = self.buffer.read(cx);
 4286        let newest_selection = self.selections.newest_anchor().clone();
 4287        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4288        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4289        if start_buffer != end_buffer {
 4290            return None;
 4291        }
 4292
 4293        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4294            cx.background_executor()
 4295                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4296                .await;
 4297
 4298            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4299                let providers = this.code_action_providers.clone();
 4300                let tasks = this
 4301                    .code_action_providers
 4302                    .iter()
 4303                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4304                    .collect::<Vec<_>>();
 4305                (providers, tasks)
 4306            })?;
 4307
 4308            let mut actions = Vec::new();
 4309            for (provider, provider_actions) in
 4310                providers.into_iter().zip(future::join_all(tasks).await)
 4311            {
 4312                if let Some(provider_actions) = provider_actions.log_err() {
 4313                    actions.extend(provider_actions.into_iter().map(|action| {
 4314                        AvailableCodeAction {
 4315                            excerpt_id: newest_selection.start.excerpt_id,
 4316                            action,
 4317                            provider: provider.clone(),
 4318                        }
 4319                    }));
 4320                }
 4321            }
 4322
 4323            this.update(&mut cx, |this, cx| {
 4324                this.available_code_actions = if actions.is_empty() {
 4325                    None
 4326                } else {
 4327                    Some((
 4328                        Location {
 4329                            buffer: start_buffer,
 4330                            range: start..end,
 4331                        },
 4332                        actions.into(),
 4333                    ))
 4334                };
 4335                cx.notify();
 4336            })
 4337        }));
 4338        None
 4339    }
 4340
 4341    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4342        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4343            self.show_git_blame_inline = false;
 4344
 4345            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4346                cx.background_executor().timer(delay).await;
 4347
 4348                this.update(&mut cx, |this, cx| {
 4349                    this.show_git_blame_inline = true;
 4350                    cx.notify();
 4351                })
 4352                .log_err();
 4353            }));
 4354        }
 4355    }
 4356
 4357    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4358        if self.pending_rename.is_some() {
 4359            return None;
 4360        }
 4361
 4362        let provider = self.semantics_provider.clone()?;
 4363        let buffer = self.buffer.read(cx);
 4364        let newest_selection = self.selections.newest_anchor().clone();
 4365        let cursor_position = newest_selection.head();
 4366        let (cursor_buffer, cursor_buffer_position) =
 4367            buffer.text_anchor_for_position(cursor_position, cx)?;
 4368        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4369        if cursor_buffer != tail_buffer {
 4370            return None;
 4371        }
 4372        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4373        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4374            cx.background_executor()
 4375                .timer(Duration::from_millis(debounce))
 4376                .await;
 4377
 4378            let highlights = if let Some(highlights) = cx
 4379                .update(|cx| {
 4380                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4381                })
 4382                .ok()
 4383                .flatten()
 4384            {
 4385                highlights.await.log_err()
 4386            } else {
 4387                None
 4388            };
 4389
 4390            if let Some(highlights) = highlights {
 4391                this.update(&mut cx, |this, cx| {
 4392                    if this.pending_rename.is_some() {
 4393                        return;
 4394                    }
 4395
 4396                    let buffer_id = cursor_position.buffer_id;
 4397                    let buffer = this.buffer.read(cx);
 4398                    if !buffer
 4399                        .text_anchor_for_position(cursor_position, cx)
 4400                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4401                    {
 4402                        return;
 4403                    }
 4404
 4405                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4406                    let mut write_ranges = Vec::new();
 4407                    let mut read_ranges = Vec::new();
 4408                    for highlight in highlights {
 4409                        for (excerpt_id, excerpt_range) in
 4410                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4411                        {
 4412                            let start = highlight
 4413                                .range
 4414                                .start
 4415                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4416                            let end = highlight
 4417                                .range
 4418                                .end
 4419                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4420                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4421                                continue;
 4422                            }
 4423
 4424                            let range = Anchor {
 4425                                buffer_id,
 4426                                excerpt_id,
 4427                                text_anchor: start,
 4428                            }..Anchor {
 4429                                buffer_id,
 4430                                excerpt_id,
 4431                                text_anchor: end,
 4432                            };
 4433                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4434                                write_ranges.push(range);
 4435                            } else {
 4436                                read_ranges.push(range);
 4437                            }
 4438                        }
 4439                    }
 4440
 4441                    this.highlight_background::<DocumentHighlightRead>(
 4442                        &read_ranges,
 4443                        |theme| theme.editor_document_highlight_read_background,
 4444                        cx,
 4445                    );
 4446                    this.highlight_background::<DocumentHighlightWrite>(
 4447                        &write_ranges,
 4448                        |theme| theme.editor_document_highlight_write_background,
 4449                        cx,
 4450                    );
 4451                    cx.notify();
 4452                })
 4453                .log_err();
 4454            }
 4455        }));
 4456        None
 4457    }
 4458
 4459    pub fn refresh_inline_completion(
 4460        &mut self,
 4461        debounce: bool,
 4462        user_requested: bool,
 4463        cx: &mut ViewContext<Self>,
 4464    ) -> Option<()> {
 4465        let provider = self.inline_completion_provider()?;
 4466        let cursor = self.selections.newest_anchor().head();
 4467        let (buffer, cursor_buffer_position) =
 4468            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4469
 4470        if !user_requested
 4471            && (!self.enable_inline_completions
 4472                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4473                || !self.is_focused(cx))
 4474        {
 4475            self.discard_inline_completion(false, cx);
 4476            return None;
 4477        }
 4478
 4479        self.update_visible_inline_completion(cx);
 4480        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4481        Some(())
 4482    }
 4483
 4484    fn cycle_inline_completion(
 4485        &mut self,
 4486        direction: Direction,
 4487        cx: &mut ViewContext<Self>,
 4488    ) -> Option<()> {
 4489        let provider = self.inline_completion_provider()?;
 4490        let cursor = self.selections.newest_anchor().head();
 4491        let (buffer, cursor_buffer_position) =
 4492            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4493        if !self.enable_inline_completions
 4494            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4495        {
 4496            return None;
 4497        }
 4498
 4499        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4500        self.update_visible_inline_completion(cx);
 4501
 4502        Some(())
 4503    }
 4504
 4505    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4506        if !self.has_active_inline_completion() {
 4507            self.refresh_inline_completion(false, true, cx);
 4508            return;
 4509        }
 4510
 4511        self.update_visible_inline_completion(cx);
 4512    }
 4513
 4514    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4515        self.show_cursor_names(cx);
 4516    }
 4517
 4518    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4519        self.show_cursor_names = true;
 4520        cx.notify();
 4521        cx.spawn(|this, mut cx| async move {
 4522            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4523            this.update(&mut cx, |this, cx| {
 4524                this.show_cursor_names = false;
 4525                cx.notify()
 4526            })
 4527            .ok()
 4528        })
 4529        .detach();
 4530    }
 4531
 4532    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4533        if self.has_active_inline_completion() {
 4534            self.cycle_inline_completion(Direction::Next, cx);
 4535        } else {
 4536            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4537            if is_copilot_disabled {
 4538                cx.propagate();
 4539            }
 4540        }
 4541    }
 4542
 4543    pub fn previous_inline_completion(
 4544        &mut self,
 4545        _: &PreviousInlineCompletion,
 4546        cx: &mut ViewContext<Self>,
 4547    ) {
 4548        if self.has_active_inline_completion() {
 4549            self.cycle_inline_completion(Direction::Prev, cx);
 4550        } else {
 4551            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4552            if is_copilot_disabled {
 4553                cx.propagate();
 4554            }
 4555        }
 4556    }
 4557
 4558    pub fn accept_inline_completion(
 4559        &mut self,
 4560        _: &AcceptInlineCompletion,
 4561        cx: &mut ViewContext<Self>,
 4562    ) {
 4563        if self.show_inline_completions_in_menu(cx) {
 4564            self.hide_context_menu(cx);
 4565        }
 4566
 4567        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4568            return;
 4569        };
 4570
 4571        self.report_inline_completion_event(true, cx);
 4572
 4573        match &active_inline_completion.completion {
 4574            InlineCompletion::Move(position) => {
 4575                let position = *position;
 4576                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4577                    selections.select_anchor_ranges([position..position]);
 4578                });
 4579            }
 4580            InlineCompletion::Edit(edits) => {
 4581                if let Some(provider) = self.inline_completion_provider() {
 4582                    provider.accept(cx);
 4583                }
 4584
 4585                let snapshot = self.buffer.read(cx).snapshot(cx);
 4586                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4587
 4588                self.buffer.update(cx, |buffer, cx| {
 4589                    buffer.edit(edits.iter().cloned(), None, cx)
 4590                });
 4591
 4592                self.change_selections(None, cx, |s| {
 4593                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4594                });
 4595
 4596                self.update_visible_inline_completion(cx);
 4597                if self.active_inline_completion.is_none() {
 4598                    self.refresh_inline_completion(true, true, cx);
 4599                }
 4600
 4601                cx.notify();
 4602            }
 4603        }
 4604    }
 4605
 4606    pub fn accept_partial_inline_completion(
 4607        &mut self,
 4608        _: &AcceptPartialInlineCompletion,
 4609        cx: &mut ViewContext<Self>,
 4610    ) {
 4611        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4612            return;
 4613        };
 4614        if self.selections.count() != 1 {
 4615            return;
 4616        }
 4617
 4618        self.report_inline_completion_event(true, cx);
 4619
 4620        match &active_inline_completion.completion {
 4621            InlineCompletion::Move(position) => {
 4622                let position = *position;
 4623                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4624                    selections.select_anchor_ranges([position..position]);
 4625                });
 4626            }
 4627            InlineCompletion::Edit(edits) => {
 4628                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4629                    let text = edits[0].1.as_str();
 4630                    let mut partial_completion = text
 4631                        .chars()
 4632                        .by_ref()
 4633                        .take_while(|c| c.is_alphabetic())
 4634                        .collect::<String>();
 4635                    if partial_completion.is_empty() {
 4636                        partial_completion = text
 4637                            .chars()
 4638                            .by_ref()
 4639                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4640                            .collect::<String>();
 4641                    }
 4642
 4643                    cx.emit(EditorEvent::InputHandled {
 4644                        utf16_range_to_replace: None,
 4645                        text: partial_completion.clone().into(),
 4646                    });
 4647
 4648                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4649
 4650                    self.refresh_inline_completion(true, true, cx);
 4651                    cx.notify();
 4652                }
 4653            }
 4654        }
 4655    }
 4656
 4657    fn discard_inline_completion(
 4658        &mut self,
 4659        should_report_inline_completion_event: bool,
 4660        cx: &mut ViewContext<Self>,
 4661    ) -> bool {
 4662        if should_report_inline_completion_event {
 4663            self.report_inline_completion_event(false, cx);
 4664        }
 4665
 4666        if let Some(provider) = self.inline_completion_provider() {
 4667            provider.discard(cx);
 4668        }
 4669
 4670        self.take_active_inline_completion(cx).is_some()
 4671    }
 4672
 4673    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4674        let Some(provider) = self.inline_completion_provider() else {
 4675            return;
 4676        };
 4677        let Some(project) = self.project.as_ref() else {
 4678            return;
 4679        };
 4680        let Some((_, buffer, _)) = self
 4681            .buffer
 4682            .read(cx)
 4683            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4684        else {
 4685            return;
 4686        };
 4687
 4688        let project = project.read(cx);
 4689        let extension = buffer
 4690            .read(cx)
 4691            .file()
 4692            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4693        project.client().telemetry().report_inline_completion_event(
 4694            provider.name().into(),
 4695            accepted,
 4696            extension,
 4697        );
 4698    }
 4699
 4700    pub fn has_active_inline_completion(&self) -> bool {
 4701        self.active_inline_completion.is_some()
 4702    }
 4703
 4704    fn take_active_inline_completion(
 4705        &mut self,
 4706        cx: &mut ViewContext<Self>,
 4707    ) -> Option<InlineCompletion> {
 4708        let active_inline_completion = self.active_inline_completion.take()?;
 4709        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4710        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4711        Some(active_inline_completion.completion)
 4712    }
 4713
 4714    fn hide_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 4715        if let Some(active_inline_completion) = self.active_inline_completion.as_ref() {
 4716            self.splice_inlays(
 4717                active_inline_completion.inlay_ids.clone(),
 4718                Default::default(),
 4719                cx,
 4720            );
 4721            self.clear_highlights::<InlineCompletionHighlight>(cx);
 4722        }
 4723    }
 4724
 4725    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4726        let selection = self.selections.newest_anchor();
 4727        let cursor = selection.head();
 4728        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4729        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4730        let excerpt_id = cursor.excerpt_id;
 4731
 4732        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 4733            && (self.context_menu.borrow().is_some()
 4734                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 4735        if completions_menu_has_precedence
 4736            || !offset_selection.is_empty()
 4737            || self
 4738                .active_inline_completion
 4739                .as_ref()
 4740                .map_or(false, |completion| {
 4741                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4742                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4743                    !invalidation_range.contains(&offset_selection.head())
 4744                })
 4745        {
 4746            self.discard_inline_completion(false, cx);
 4747            return None;
 4748        }
 4749
 4750        self.take_active_inline_completion(cx);
 4751        let provider = self.inline_completion_provider()?;
 4752
 4753        let (buffer, cursor_buffer_position) =
 4754            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4755
 4756        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4757        let edits = completion
 4758            .edits
 4759            .into_iter()
 4760            .flat_map(|(range, new_text)| {
 4761                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4762                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4763                Some((start..end, new_text))
 4764            })
 4765            .collect::<Vec<_>>();
 4766        if edits.is_empty() {
 4767            return None;
 4768        }
 4769
 4770        let first_edit_start = edits.first().unwrap().0.start;
 4771        let edit_start_row = first_edit_start
 4772            .to_point(&multibuffer)
 4773            .row
 4774            .saturating_sub(2);
 4775
 4776        let last_edit_end = edits.last().unwrap().0.end;
 4777        let edit_end_row = cmp::min(
 4778            multibuffer.max_point().row,
 4779            last_edit_end.to_point(&multibuffer).row + 2,
 4780        );
 4781
 4782        let cursor_row = cursor.to_point(&multibuffer).row;
 4783
 4784        let mut inlay_ids = Vec::new();
 4785        let invalidation_row_range;
 4786        let completion;
 4787        if cursor_row < edit_start_row {
 4788            invalidation_row_range = cursor_row..edit_end_row;
 4789            completion = InlineCompletion::Move(first_edit_start);
 4790        } else if cursor_row > edit_end_row {
 4791            invalidation_row_range = edit_start_row..cursor_row;
 4792            completion = InlineCompletion::Move(first_edit_start);
 4793        } else {
 4794            if !self.show_inline_completions_in_menu(cx) || !self.has_active_completions_menu() {
 4795                if edits
 4796                    .iter()
 4797                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4798                {
 4799                    let mut inlays = Vec::new();
 4800                    for (range, new_text) in &edits {
 4801                        let inlay = Inlay::inline_completion(
 4802                            post_inc(&mut self.next_inlay_id),
 4803                            range.start,
 4804                            new_text.as_str(),
 4805                        );
 4806                        inlay_ids.push(inlay.id);
 4807                        inlays.push(inlay);
 4808                    }
 4809
 4810                    self.splice_inlays(vec![], inlays, cx);
 4811                } else {
 4812                    let background_color = cx.theme().status().deleted_background;
 4813                    self.highlight_text::<InlineCompletionHighlight>(
 4814                        edits.iter().map(|(range, _)| range.clone()).collect(),
 4815                        HighlightStyle {
 4816                            background_color: Some(background_color),
 4817                            ..Default::default()
 4818                        },
 4819                        cx,
 4820                    );
 4821                }
 4822            }
 4823
 4824            invalidation_row_range = edit_start_row..edit_end_row;
 4825            completion = InlineCompletion::Edit(edits);
 4826        };
 4827
 4828        let invalidation_range = multibuffer
 4829            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4830            ..multibuffer.anchor_after(Point::new(
 4831                invalidation_row_range.end,
 4832                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4833            ));
 4834
 4835        self.active_inline_completion = Some(InlineCompletionState {
 4836            inlay_ids,
 4837            completion,
 4838            invalidation_range,
 4839        });
 4840
 4841        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 4842            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4843                match self.context_menu.borrow_mut().as_mut() {
 4844                    Some(CodeContextMenu::Completions(menu)) => {
 4845                        menu.show_inline_completion_hint(hint);
 4846                    }
 4847                    _ => {}
 4848                }
 4849            }
 4850        }
 4851
 4852        cx.notify();
 4853
 4854        Some(())
 4855    }
 4856
 4857    fn inline_completion_menu_hint(
 4858        &mut self,
 4859        cx: &mut ViewContext<Self>,
 4860    ) -> Option<InlineCompletionMenuHint> {
 4861        if self.has_active_inline_completion() {
 4862            let provider_name = self.inline_completion_provider()?.display_name();
 4863            let editor_snapshot = self.snapshot(cx);
 4864
 4865            let text = match &self.active_inline_completion.as_ref()?.completion {
 4866                InlineCompletion::Edit(edits) => {
 4867                    inline_completion_edit_text(&editor_snapshot, edits, true, cx)
 4868                }
 4869                InlineCompletion::Move(target) => {
 4870                    let target_point =
 4871                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4872                    let target_line = target_point.row + 1;
 4873                    InlineCompletionText::Move(
 4874                        format!("Jump to edit in line {}", target_line).into(),
 4875                    )
 4876                }
 4877            };
 4878
 4879            Some(InlineCompletionMenuHint {
 4880                provider_name,
 4881                text,
 4882            })
 4883        } else {
 4884            None
 4885        }
 4886    }
 4887
 4888    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4889        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4890    }
 4891
 4892    fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
 4893        EditorSettings::get_global(cx).show_inline_completions_in_menu
 4894            && self
 4895                .inline_completion_provider()
 4896                .map_or(false, |provider| provider.show_completions_in_menu())
 4897    }
 4898
 4899    fn render_code_actions_indicator(
 4900        &self,
 4901        _style: &EditorStyle,
 4902        row: DisplayRow,
 4903        is_active: bool,
 4904        cx: &mut ViewContext<Self>,
 4905    ) -> Option<IconButton> {
 4906        if self.available_code_actions.is_some() {
 4907            Some(
 4908                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4909                    .shape(ui::IconButtonShape::Square)
 4910                    .icon_size(IconSize::XSmall)
 4911                    .icon_color(Color::Muted)
 4912                    .toggle_state(is_active)
 4913                    .tooltip({
 4914                        let focus_handle = self.focus_handle.clone();
 4915                        move |cx| {
 4916                            Tooltip::for_action_in(
 4917                                "Toggle Code Actions",
 4918                                &ToggleCodeActions {
 4919                                    deployed_from_indicator: None,
 4920                                },
 4921                                &focus_handle,
 4922                                cx,
 4923                            )
 4924                        }
 4925                    })
 4926                    .on_click(cx.listener(move |editor, _e, cx| {
 4927                        editor.focus(cx);
 4928                        editor.toggle_code_actions(
 4929                            &ToggleCodeActions {
 4930                                deployed_from_indicator: Some(row),
 4931                            },
 4932                            cx,
 4933                        );
 4934                    })),
 4935            )
 4936        } else {
 4937            None
 4938        }
 4939    }
 4940
 4941    fn clear_tasks(&mut self) {
 4942        self.tasks.clear()
 4943    }
 4944
 4945    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4946        if self.tasks.insert(key, value).is_some() {
 4947            // This case should hopefully be rare, but just in case...
 4948            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4949        }
 4950    }
 4951
 4952    fn build_tasks_context(
 4953        project: &Model<Project>,
 4954        buffer: &Model<Buffer>,
 4955        buffer_row: u32,
 4956        tasks: &Arc<RunnableTasks>,
 4957        cx: &mut ViewContext<Self>,
 4958    ) -> Task<Option<task::TaskContext>> {
 4959        let position = Point::new(buffer_row, tasks.column);
 4960        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4961        let location = Location {
 4962            buffer: buffer.clone(),
 4963            range: range_start..range_start,
 4964        };
 4965        // Fill in the environmental variables from the tree-sitter captures
 4966        let mut captured_task_variables = TaskVariables::default();
 4967        for (capture_name, value) in tasks.extra_variables.clone() {
 4968            captured_task_variables.insert(
 4969                task::VariableName::Custom(capture_name.into()),
 4970                value.clone(),
 4971            );
 4972        }
 4973        project.update(cx, |project, cx| {
 4974            project.task_store().update(cx, |task_store, cx| {
 4975                task_store.task_context_for_location(captured_task_variables, location, cx)
 4976            })
 4977        })
 4978    }
 4979
 4980    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 4981        let Some((workspace, _)) = self.workspace.clone() else {
 4982            return;
 4983        };
 4984        let Some(project) = self.project.clone() else {
 4985            return;
 4986        };
 4987
 4988        // Try to find a closest, enclosing node using tree-sitter that has a
 4989        // task
 4990        let Some((buffer, buffer_row, tasks)) = self
 4991            .find_enclosing_node_task(cx)
 4992            // Or find the task that's closest in row-distance.
 4993            .or_else(|| self.find_closest_task(cx))
 4994        else {
 4995            return;
 4996        };
 4997
 4998        let reveal_strategy = action.reveal;
 4999        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5000        cx.spawn(|_, mut cx| async move {
 5001            let context = task_context.await?;
 5002            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5003
 5004            let resolved = resolved_task.resolved.as_mut()?;
 5005            resolved.reveal = reveal_strategy;
 5006
 5007            workspace
 5008                .update(&mut cx, |workspace, cx| {
 5009                    workspace::tasks::schedule_resolved_task(
 5010                        workspace,
 5011                        task_source_kind,
 5012                        resolved_task,
 5013                        false,
 5014                        cx,
 5015                    );
 5016                })
 5017                .ok()
 5018        })
 5019        .detach();
 5020    }
 5021
 5022    fn find_closest_task(
 5023        &mut self,
 5024        cx: &mut ViewContext<Self>,
 5025    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5026        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5027
 5028        let ((buffer_id, row), tasks) = self
 5029            .tasks
 5030            .iter()
 5031            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5032
 5033        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5034        let tasks = Arc::new(tasks.to_owned());
 5035        Some((buffer, *row, tasks))
 5036    }
 5037
 5038    fn find_enclosing_node_task(
 5039        &mut self,
 5040        cx: &mut ViewContext<Self>,
 5041    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5042        let snapshot = self.buffer.read(cx).snapshot(cx);
 5043        let offset = self.selections.newest::<usize>(cx).head();
 5044        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5045        let buffer_id = excerpt.buffer().remote_id();
 5046
 5047        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5048        let mut cursor = layer.node().walk();
 5049
 5050        while cursor.goto_first_child_for_byte(offset).is_some() {
 5051            if cursor.node().end_byte() == offset {
 5052                cursor.goto_next_sibling();
 5053            }
 5054        }
 5055
 5056        // Ascend to the smallest ancestor that contains the range and has a task.
 5057        loop {
 5058            let node = cursor.node();
 5059            let node_range = node.byte_range();
 5060            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5061
 5062            // Check if this node contains our offset
 5063            if node_range.start <= offset && node_range.end >= offset {
 5064                // If it contains offset, check for task
 5065                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5066                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5067                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5068                }
 5069            }
 5070
 5071            if !cursor.goto_parent() {
 5072                break;
 5073            }
 5074        }
 5075        None
 5076    }
 5077
 5078    fn render_run_indicator(
 5079        &self,
 5080        _style: &EditorStyle,
 5081        is_active: bool,
 5082        row: DisplayRow,
 5083        cx: &mut ViewContext<Self>,
 5084    ) -> IconButton {
 5085        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5086            .shape(ui::IconButtonShape::Square)
 5087            .icon_size(IconSize::XSmall)
 5088            .icon_color(Color::Muted)
 5089            .toggle_state(is_active)
 5090            .on_click(cx.listener(move |editor, _e, cx| {
 5091                editor.focus(cx);
 5092                editor.toggle_code_actions(
 5093                    &ToggleCodeActions {
 5094                        deployed_from_indicator: Some(row),
 5095                    },
 5096                    cx,
 5097                );
 5098            }))
 5099    }
 5100
 5101    #[cfg(feature = "test-support")]
 5102    pub fn context_menu_visible(&self) -> bool {
 5103        self.context_menu
 5104            .borrow()
 5105            .as_ref()
 5106            .map_or(false, |menu| menu.visible())
 5107    }
 5108
 5109    #[cfg(feature = "test-support")]
 5110    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5111        self.context_menu
 5112            .borrow()
 5113            .as_ref()
 5114            .map_or(false, |menu| match menu {
 5115                CodeContextMenu::Completions(menu) => menu.entries.first().map_or(false, |entry| {
 5116                    matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5117                }),
 5118                CodeContextMenu::CodeActions(_) => false,
 5119            })
 5120    }
 5121
 5122    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5123        self.context_menu
 5124            .borrow()
 5125            .as_ref()
 5126            .map(|menu| menu.origin(cursor_position))
 5127    }
 5128
 5129    fn render_context_menu(
 5130        &self,
 5131        style: &EditorStyle,
 5132        max_height_in_lines: u32,
 5133        cx: &mut ViewContext<Editor>,
 5134    ) -> Option<AnyElement> {
 5135        self.context_menu.borrow().as_ref().and_then(|menu| {
 5136            if menu.visible() {
 5137                Some(menu.render(style, max_height_in_lines, cx))
 5138            } else {
 5139                None
 5140            }
 5141        })
 5142    }
 5143
 5144    fn render_context_menu_aside(
 5145        &self,
 5146        style: &EditorStyle,
 5147        max_height: Pixels,
 5148        cx: &mut ViewContext<Editor>,
 5149    ) -> Option<AnyElement> {
 5150        self.context_menu.borrow().as_ref().and_then(|menu| {
 5151            if menu.visible() {
 5152                menu.render_aside(
 5153                    style,
 5154                    max_height,
 5155                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5156                    cx,
 5157                )
 5158            } else {
 5159                None
 5160            }
 5161        })
 5162    }
 5163
 5164    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5165        cx.notify();
 5166        self.completion_tasks.clear();
 5167        let context_menu = self.context_menu.borrow_mut().take();
 5168        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5169            self.update_visible_inline_completion(cx);
 5170        }
 5171        context_menu
 5172    }
 5173
 5174    fn show_snippet_choices(
 5175        &mut self,
 5176        choices: &Vec<String>,
 5177        selection: Range<Anchor>,
 5178        cx: &mut ViewContext<Self>,
 5179    ) {
 5180        if selection.start.buffer_id.is_none() {
 5181            return;
 5182        }
 5183        let buffer_id = selection.start.buffer_id.unwrap();
 5184        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5185        let id = post_inc(&mut self.next_completion_id);
 5186
 5187        if let Some(buffer) = buffer {
 5188            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5189                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5190            ));
 5191        }
 5192    }
 5193
 5194    pub fn insert_snippet(
 5195        &mut self,
 5196        insertion_ranges: &[Range<usize>],
 5197        snippet: Snippet,
 5198        cx: &mut ViewContext<Self>,
 5199    ) -> Result<()> {
 5200        struct Tabstop<T> {
 5201            is_end_tabstop: bool,
 5202            ranges: Vec<Range<T>>,
 5203            choices: Option<Vec<String>>,
 5204        }
 5205
 5206        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5207            let snippet_text: Arc<str> = snippet.text.clone().into();
 5208            buffer.edit(
 5209                insertion_ranges
 5210                    .iter()
 5211                    .cloned()
 5212                    .map(|range| (range, snippet_text.clone())),
 5213                Some(AutoindentMode::EachLine),
 5214                cx,
 5215            );
 5216
 5217            let snapshot = &*buffer.read(cx);
 5218            let snippet = &snippet;
 5219            snippet
 5220                .tabstops
 5221                .iter()
 5222                .map(|tabstop| {
 5223                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5224                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5225                    });
 5226                    let mut tabstop_ranges = tabstop
 5227                        .ranges
 5228                        .iter()
 5229                        .flat_map(|tabstop_range| {
 5230                            let mut delta = 0_isize;
 5231                            insertion_ranges.iter().map(move |insertion_range| {
 5232                                let insertion_start = insertion_range.start as isize + delta;
 5233                                delta +=
 5234                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5235
 5236                                let start = ((insertion_start + tabstop_range.start) as usize)
 5237                                    .min(snapshot.len());
 5238                                let end = ((insertion_start + tabstop_range.end) as usize)
 5239                                    .min(snapshot.len());
 5240                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5241                            })
 5242                        })
 5243                        .collect::<Vec<_>>();
 5244                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5245
 5246                    Tabstop {
 5247                        is_end_tabstop,
 5248                        ranges: tabstop_ranges,
 5249                        choices: tabstop.choices.clone(),
 5250                    }
 5251                })
 5252                .collect::<Vec<_>>()
 5253        });
 5254        if let Some(tabstop) = tabstops.first() {
 5255            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5256                s.select_ranges(tabstop.ranges.iter().cloned());
 5257            });
 5258
 5259            if let Some(choices) = &tabstop.choices {
 5260                if let Some(selection) = tabstop.ranges.first() {
 5261                    self.show_snippet_choices(choices, selection.clone(), cx)
 5262                }
 5263            }
 5264
 5265            // If we're already at the last tabstop and it's at the end of the snippet,
 5266            // we're done, we don't need to keep the state around.
 5267            if !tabstop.is_end_tabstop {
 5268                let choices = tabstops
 5269                    .iter()
 5270                    .map(|tabstop| tabstop.choices.clone())
 5271                    .collect();
 5272
 5273                let ranges = tabstops
 5274                    .into_iter()
 5275                    .map(|tabstop| tabstop.ranges)
 5276                    .collect::<Vec<_>>();
 5277
 5278                self.snippet_stack.push(SnippetState {
 5279                    active_index: 0,
 5280                    ranges,
 5281                    choices,
 5282                });
 5283            }
 5284
 5285            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5286            if self.autoclose_regions.is_empty() {
 5287                let snapshot = self.buffer.read(cx).snapshot(cx);
 5288                for selection in &mut self.selections.all::<Point>(cx) {
 5289                    let selection_head = selection.head();
 5290                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5291                        continue;
 5292                    };
 5293
 5294                    let mut bracket_pair = None;
 5295                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5296                    let prev_chars = snapshot
 5297                        .reversed_chars_at(selection_head)
 5298                        .collect::<String>();
 5299                    for (pair, enabled) in scope.brackets() {
 5300                        if enabled
 5301                            && pair.close
 5302                            && prev_chars.starts_with(pair.start.as_str())
 5303                            && next_chars.starts_with(pair.end.as_str())
 5304                        {
 5305                            bracket_pair = Some(pair.clone());
 5306                            break;
 5307                        }
 5308                    }
 5309                    if let Some(pair) = bracket_pair {
 5310                        let start = snapshot.anchor_after(selection_head);
 5311                        let end = snapshot.anchor_after(selection_head);
 5312                        self.autoclose_regions.push(AutocloseRegion {
 5313                            selection_id: selection.id,
 5314                            range: start..end,
 5315                            pair,
 5316                        });
 5317                    }
 5318                }
 5319            }
 5320        }
 5321        Ok(())
 5322    }
 5323
 5324    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5325        self.move_to_snippet_tabstop(Bias::Right, cx)
 5326    }
 5327
 5328    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5329        self.move_to_snippet_tabstop(Bias::Left, cx)
 5330    }
 5331
 5332    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5333        if let Some(mut snippet) = self.snippet_stack.pop() {
 5334            match bias {
 5335                Bias::Left => {
 5336                    if snippet.active_index > 0 {
 5337                        snippet.active_index -= 1;
 5338                    } else {
 5339                        self.snippet_stack.push(snippet);
 5340                        return false;
 5341                    }
 5342                }
 5343                Bias::Right => {
 5344                    if snippet.active_index + 1 < snippet.ranges.len() {
 5345                        snippet.active_index += 1;
 5346                    } else {
 5347                        self.snippet_stack.push(snippet);
 5348                        return false;
 5349                    }
 5350                }
 5351            }
 5352            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5353                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5354                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5355                });
 5356
 5357                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5358                    if let Some(selection) = current_ranges.first() {
 5359                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5360                    }
 5361                }
 5362
 5363                // If snippet state is not at the last tabstop, push it back on the stack
 5364                if snippet.active_index + 1 < snippet.ranges.len() {
 5365                    self.snippet_stack.push(snippet);
 5366                }
 5367                return true;
 5368            }
 5369        }
 5370
 5371        false
 5372    }
 5373
 5374    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5375        self.transact(cx, |this, cx| {
 5376            this.select_all(&SelectAll, cx);
 5377            this.insert("", cx);
 5378        });
 5379    }
 5380
 5381    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5382        self.transact(cx, |this, cx| {
 5383            this.select_autoclose_pair(cx);
 5384            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5385            if !this.linked_edit_ranges.is_empty() {
 5386                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5387                let snapshot = this.buffer.read(cx).snapshot(cx);
 5388
 5389                for selection in selections.iter() {
 5390                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5391                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5392                    if selection_start.buffer_id != selection_end.buffer_id {
 5393                        continue;
 5394                    }
 5395                    if let Some(ranges) =
 5396                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5397                    {
 5398                        for (buffer, entries) in ranges {
 5399                            linked_ranges.entry(buffer).or_default().extend(entries);
 5400                        }
 5401                    }
 5402                }
 5403            }
 5404
 5405            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5406            if !this.selections.line_mode {
 5407                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5408                for selection in &mut selections {
 5409                    if selection.is_empty() {
 5410                        let old_head = selection.head();
 5411                        let mut new_head =
 5412                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5413                                .to_point(&display_map);
 5414                        if let Some((buffer, line_buffer_range)) = display_map
 5415                            .buffer_snapshot
 5416                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5417                        {
 5418                            let indent_size =
 5419                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5420                            let indent_len = match indent_size.kind {
 5421                                IndentKind::Space => {
 5422                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5423                                }
 5424                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5425                            };
 5426                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5427                                let indent_len = indent_len.get();
 5428                                new_head = cmp::min(
 5429                                    new_head,
 5430                                    MultiBufferPoint::new(
 5431                                        old_head.row,
 5432                                        ((old_head.column - 1) / indent_len) * indent_len,
 5433                                    ),
 5434                                );
 5435                            }
 5436                        }
 5437
 5438                        selection.set_head(new_head, SelectionGoal::None);
 5439                    }
 5440                }
 5441            }
 5442
 5443            this.signature_help_state.set_backspace_pressed(true);
 5444            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5445            this.insert("", cx);
 5446            let empty_str: Arc<str> = Arc::from("");
 5447            for (buffer, edits) in linked_ranges {
 5448                let snapshot = buffer.read(cx).snapshot();
 5449                use text::ToPoint as TP;
 5450
 5451                let edits = edits
 5452                    .into_iter()
 5453                    .map(|range| {
 5454                        let end_point = TP::to_point(&range.end, &snapshot);
 5455                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5456
 5457                        if end_point == start_point {
 5458                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5459                                .saturating_sub(1);
 5460                            start_point =
 5461                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5462                        };
 5463
 5464                        (start_point..end_point, empty_str.clone())
 5465                    })
 5466                    .sorted_by_key(|(range, _)| range.start)
 5467                    .collect::<Vec<_>>();
 5468                buffer.update(cx, |this, cx| {
 5469                    this.edit(edits, None, cx);
 5470                })
 5471            }
 5472            this.refresh_inline_completion(true, false, cx);
 5473            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5474        });
 5475    }
 5476
 5477    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5478        self.transact(cx, |this, cx| {
 5479            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5480                let line_mode = s.line_mode;
 5481                s.move_with(|map, selection| {
 5482                    if selection.is_empty() && !line_mode {
 5483                        let cursor = movement::right(map, selection.head());
 5484                        selection.end = cursor;
 5485                        selection.reversed = true;
 5486                        selection.goal = SelectionGoal::None;
 5487                    }
 5488                })
 5489            });
 5490            this.insert("", cx);
 5491            this.refresh_inline_completion(true, false, cx);
 5492        });
 5493    }
 5494
 5495    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5496        if self.move_to_prev_snippet_tabstop(cx) {
 5497            return;
 5498        }
 5499
 5500        self.outdent(&Outdent, cx);
 5501    }
 5502
 5503    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5504        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5505            return;
 5506        }
 5507
 5508        let mut selections = self.selections.all_adjusted(cx);
 5509        let buffer = self.buffer.read(cx);
 5510        let snapshot = buffer.snapshot(cx);
 5511        let rows_iter = selections.iter().map(|s| s.head().row);
 5512        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5513
 5514        let mut edits = Vec::new();
 5515        let mut prev_edited_row = 0;
 5516        let mut row_delta = 0;
 5517        for selection in &mut selections {
 5518            if selection.start.row != prev_edited_row {
 5519                row_delta = 0;
 5520            }
 5521            prev_edited_row = selection.end.row;
 5522
 5523            // If the selection is non-empty, then increase the indentation of the selected lines.
 5524            if !selection.is_empty() {
 5525                row_delta =
 5526                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5527                continue;
 5528            }
 5529
 5530            // If the selection is empty and the cursor is in the leading whitespace before the
 5531            // suggested indentation, then auto-indent the line.
 5532            let cursor = selection.head();
 5533            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5534            if let Some(suggested_indent) =
 5535                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5536            {
 5537                if cursor.column < suggested_indent.len
 5538                    && cursor.column <= current_indent.len
 5539                    && current_indent.len <= suggested_indent.len
 5540                {
 5541                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5542                    selection.end = selection.start;
 5543                    if row_delta == 0 {
 5544                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5545                            cursor.row,
 5546                            current_indent,
 5547                            suggested_indent,
 5548                        ));
 5549                        row_delta = suggested_indent.len - current_indent.len;
 5550                    }
 5551                    continue;
 5552                }
 5553            }
 5554
 5555            // Otherwise, insert a hard or soft tab.
 5556            let settings = buffer.settings_at(cursor, cx);
 5557            let tab_size = if settings.hard_tabs {
 5558                IndentSize::tab()
 5559            } else {
 5560                let tab_size = settings.tab_size.get();
 5561                let char_column = snapshot
 5562                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5563                    .flat_map(str::chars)
 5564                    .count()
 5565                    + row_delta as usize;
 5566                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5567                IndentSize::spaces(chars_to_next_tab_stop)
 5568            };
 5569            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5570            selection.end = selection.start;
 5571            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5572            row_delta += tab_size.len;
 5573        }
 5574
 5575        self.transact(cx, |this, cx| {
 5576            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5577            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5578            this.refresh_inline_completion(true, false, cx);
 5579        });
 5580    }
 5581
 5582    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5583        if self.read_only(cx) {
 5584            return;
 5585        }
 5586        let mut selections = self.selections.all::<Point>(cx);
 5587        let mut prev_edited_row = 0;
 5588        let mut row_delta = 0;
 5589        let mut edits = Vec::new();
 5590        let buffer = self.buffer.read(cx);
 5591        let snapshot = buffer.snapshot(cx);
 5592        for selection in &mut selections {
 5593            if selection.start.row != prev_edited_row {
 5594                row_delta = 0;
 5595            }
 5596            prev_edited_row = selection.end.row;
 5597
 5598            row_delta =
 5599                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5600        }
 5601
 5602        self.transact(cx, |this, cx| {
 5603            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5604            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5605        });
 5606    }
 5607
 5608    fn indent_selection(
 5609        buffer: &MultiBuffer,
 5610        snapshot: &MultiBufferSnapshot,
 5611        selection: &mut Selection<Point>,
 5612        edits: &mut Vec<(Range<Point>, String)>,
 5613        delta_for_start_row: u32,
 5614        cx: &AppContext,
 5615    ) -> u32 {
 5616        let settings = buffer.settings_at(selection.start, cx);
 5617        let tab_size = settings.tab_size.get();
 5618        let indent_kind = if settings.hard_tabs {
 5619            IndentKind::Tab
 5620        } else {
 5621            IndentKind::Space
 5622        };
 5623        let mut start_row = selection.start.row;
 5624        let mut end_row = selection.end.row + 1;
 5625
 5626        // If a selection ends at the beginning of a line, don't indent
 5627        // that last line.
 5628        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5629            end_row -= 1;
 5630        }
 5631
 5632        // Avoid re-indenting a row that has already been indented by a
 5633        // previous selection, but still update this selection's column
 5634        // to reflect that indentation.
 5635        if delta_for_start_row > 0 {
 5636            start_row += 1;
 5637            selection.start.column += delta_for_start_row;
 5638            if selection.end.row == selection.start.row {
 5639                selection.end.column += delta_for_start_row;
 5640            }
 5641        }
 5642
 5643        let mut delta_for_end_row = 0;
 5644        let has_multiple_rows = start_row + 1 != end_row;
 5645        for row in start_row..end_row {
 5646            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5647            let indent_delta = match (current_indent.kind, indent_kind) {
 5648                (IndentKind::Space, IndentKind::Space) => {
 5649                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5650                    IndentSize::spaces(columns_to_next_tab_stop)
 5651                }
 5652                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5653                (_, IndentKind::Tab) => IndentSize::tab(),
 5654            };
 5655
 5656            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5657                0
 5658            } else {
 5659                selection.start.column
 5660            };
 5661            let row_start = Point::new(row, start);
 5662            edits.push((
 5663                row_start..row_start,
 5664                indent_delta.chars().collect::<String>(),
 5665            ));
 5666
 5667            // Update this selection's endpoints to reflect the indentation.
 5668            if row == selection.start.row {
 5669                selection.start.column += indent_delta.len;
 5670            }
 5671            if row == selection.end.row {
 5672                selection.end.column += indent_delta.len;
 5673                delta_for_end_row = indent_delta.len;
 5674            }
 5675        }
 5676
 5677        if selection.start.row == selection.end.row {
 5678            delta_for_start_row + delta_for_end_row
 5679        } else {
 5680            delta_for_end_row
 5681        }
 5682    }
 5683
 5684    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5685        if self.read_only(cx) {
 5686            return;
 5687        }
 5688        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5689        let selections = self.selections.all::<Point>(cx);
 5690        let mut deletion_ranges = Vec::new();
 5691        let mut last_outdent = None;
 5692        {
 5693            let buffer = self.buffer.read(cx);
 5694            let snapshot = buffer.snapshot(cx);
 5695            for selection in &selections {
 5696                let settings = buffer.settings_at(selection.start, cx);
 5697                let tab_size = settings.tab_size.get();
 5698                let mut rows = selection.spanned_rows(false, &display_map);
 5699
 5700                // Avoid re-outdenting a row that has already been outdented by a
 5701                // previous selection.
 5702                if let Some(last_row) = last_outdent {
 5703                    if last_row == rows.start {
 5704                        rows.start = rows.start.next_row();
 5705                    }
 5706                }
 5707                let has_multiple_rows = rows.len() > 1;
 5708                for row in rows.iter_rows() {
 5709                    let indent_size = snapshot.indent_size_for_line(row);
 5710                    if indent_size.len > 0 {
 5711                        let deletion_len = match indent_size.kind {
 5712                            IndentKind::Space => {
 5713                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5714                                if columns_to_prev_tab_stop == 0 {
 5715                                    tab_size
 5716                                } else {
 5717                                    columns_to_prev_tab_stop
 5718                                }
 5719                            }
 5720                            IndentKind::Tab => 1,
 5721                        };
 5722                        let start = if has_multiple_rows
 5723                            || deletion_len > selection.start.column
 5724                            || indent_size.len < selection.start.column
 5725                        {
 5726                            0
 5727                        } else {
 5728                            selection.start.column - deletion_len
 5729                        };
 5730                        deletion_ranges.push(
 5731                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5732                        );
 5733                        last_outdent = Some(row);
 5734                    }
 5735                }
 5736            }
 5737        }
 5738
 5739        self.transact(cx, |this, cx| {
 5740            this.buffer.update(cx, |buffer, cx| {
 5741                let empty_str: Arc<str> = Arc::default();
 5742                buffer.edit(
 5743                    deletion_ranges
 5744                        .into_iter()
 5745                        .map(|range| (range, empty_str.clone())),
 5746                    None,
 5747                    cx,
 5748                );
 5749            });
 5750            let selections = this.selections.all::<usize>(cx);
 5751            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5752        });
 5753    }
 5754
 5755    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5756        if self.read_only(cx) {
 5757            return;
 5758        }
 5759        let selections = self
 5760            .selections
 5761            .all::<usize>(cx)
 5762            .into_iter()
 5763            .map(|s| s.range());
 5764
 5765        self.transact(cx, |this, cx| {
 5766            this.buffer.update(cx, |buffer, cx| {
 5767                buffer.autoindent_ranges(selections, cx);
 5768            });
 5769            let selections = this.selections.all::<usize>(cx);
 5770            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5771        });
 5772    }
 5773
 5774    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5775        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5776        let selections = self.selections.all::<Point>(cx);
 5777
 5778        let mut new_cursors = Vec::new();
 5779        let mut edit_ranges = Vec::new();
 5780        let mut selections = selections.iter().peekable();
 5781        while let Some(selection) = selections.next() {
 5782            let mut rows = selection.spanned_rows(false, &display_map);
 5783            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5784
 5785            // Accumulate contiguous regions of rows that we want to delete.
 5786            while let Some(next_selection) = selections.peek() {
 5787                let next_rows = next_selection.spanned_rows(false, &display_map);
 5788                if next_rows.start <= rows.end {
 5789                    rows.end = next_rows.end;
 5790                    selections.next().unwrap();
 5791                } else {
 5792                    break;
 5793                }
 5794            }
 5795
 5796            let buffer = &display_map.buffer_snapshot;
 5797            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5798            let edit_end;
 5799            let cursor_buffer_row;
 5800            if buffer.max_point().row >= rows.end.0 {
 5801                // If there's a line after the range, delete the \n from the end of the row range
 5802                // and position the cursor on the next line.
 5803                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5804                cursor_buffer_row = rows.end;
 5805            } else {
 5806                // If there isn't a line after the range, delete the \n from the line before the
 5807                // start of the row range and position the cursor there.
 5808                edit_start = edit_start.saturating_sub(1);
 5809                edit_end = buffer.len();
 5810                cursor_buffer_row = rows.start.previous_row();
 5811            }
 5812
 5813            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5814            *cursor.column_mut() =
 5815                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5816
 5817            new_cursors.push((
 5818                selection.id,
 5819                buffer.anchor_after(cursor.to_point(&display_map)),
 5820            ));
 5821            edit_ranges.push(edit_start..edit_end);
 5822        }
 5823
 5824        self.transact(cx, |this, cx| {
 5825            let buffer = this.buffer.update(cx, |buffer, cx| {
 5826                let empty_str: Arc<str> = Arc::default();
 5827                buffer.edit(
 5828                    edit_ranges
 5829                        .into_iter()
 5830                        .map(|range| (range, empty_str.clone())),
 5831                    None,
 5832                    cx,
 5833                );
 5834                buffer.snapshot(cx)
 5835            });
 5836            let new_selections = new_cursors
 5837                .into_iter()
 5838                .map(|(id, cursor)| {
 5839                    let cursor = cursor.to_point(&buffer);
 5840                    Selection {
 5841                        id,
 5842                        start: cursor,
 5843                        end: cursor,
 5844                        reversed: false,
 5845                        goal: SelectionGoal::None,
 5846                    }
 5847                })
 5848                .collect();
 5849
 5850            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5851                s.select(new_selections);
 5852            });
 5853        });
 5854    }
 5855
 5856    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5857        if self.read_only(cx) {
 5858            return;
 5859        }
 5860        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5861        for selection in self.selections.all::<Point>(cx) {
 5862            let start = MultiBufferRow(selection.start.row);
 5863            // Treat single line selections as if they include the next line. Otherwise this action
 5864            // would do nothing for single line selections individual cursors.
 5865            let end = if selection.start.row == selection.end.row {
 5866                MultiBufferRow(selection.start.row + 1)
 5867            } else {
 5868                MultiBufferRow(selection.end.row)
 5869            };
 5870
 5871            if let Some(last_row_range) = row_ranges.last_mut() {
 5872                if start <= last_row_range.end {
 5873                    last_row_range.end = end;
 5874                    continue;
 5875                }
 5876            }
 5877            row_ranges.push(start..end);
 5878        }
 5879
 5880        let snapshot = self.buffer.read(cx).snapshot(cx);
 5881        let mut cursor_positions = Vec::new();
 5882        for row_range in &row_ranges {
 5883            let anchor = snapshot.anchor_before(Point::new(
 5884                row_range.end.previous_row().0,
 5885                snapshot.line_len(row_range.end.previous_row()),
 5886            ));
 5887            cursor_positions.push(anchor..anchor);
 5888        }
 5889
 5890        self.transact(cx, |this, cx| {
 5891            for row_range in row_ranges.into_iter().rev() {
 5892                for row in row_range.iter_rows().rev() {
 5893                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5894                    let next_line_row = row.next_row();
 5895                    let indent = snapshot.indent_size_for_line(next_line_row);
 5896                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5897
 5898                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5899                        " "
 5900                    } else {
 5901                        ""
 5902                    };
 5903
 5904                    this.buffer.update(cx, |buffer, cx| {
 5905                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5906                    });
 5907                }
 5908            }
 5909
 5910            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5911                s.select_anchor_ranges(cursor_positions)
 5912            });
 5913        });
 5914    }
 5915
 5916    pub fn sort_lines_case_sensitive(
 5917        &mut self,
 5918        _: &SortLinesCaseSensitive,
 5919        cx: &mut ViewContext<Self>,
 5920    ) {
 5921        self.manipulate_lines(cx, |lines| lines.sort())
 5922    }
 5923
 5924    pub fn sort_lines_case_insensitive(
 5925        &mut self,
 5926        _: &SortLinesCaseInsensitive,
 5927        cx: &mut ViewContext<Self>,
 5928    ) {
 5929        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5930    }
 5931
 5932    pub fn unique_lines_case_insensitive(
 5933        &mut self,
 5934        _: &UniqueLinesCaseInsensitive,
 5935        cx: &mut ViewContext<Self>,
 5936    ) {
 5937        self.manipulate_lines(cx, |lines| {
 5938            let mut seen = HashSet::default();
 5939            lines.retain(|line| seen.insert(line.to_lowercase()));
 5940        })
 5941    }
 5942
 5943    pub fn unique_lines_case_sensitive(
 5944        &mut self,
 5945        _: &UniqueLinesCaseSensitive,
 5946        cx: &mut ViewContext<Self>,
 5947    ) {
 5948        self.manipulate_lines(cx, |lines| {
 5949            let mut seen = HashSet::default();
 5950            lines.retain(|line| seen.insert(*line));
 5951        })
 5952    }
 5953
 5954    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 5955        let mut revert_changes = HashMap::default();
 5956        let snapshot = self.snapshot(cx);
 5957        for hunk in hunks_for_ranges(
 5958            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 5959            &snapshot,
 5960        ) {
 5961            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5962        }
 5963        if !revert_changes.is_empty() {
 5964            self.transact(cx, |editor, cx| {
 5965                editor.revert(revert_changes, cx);
 5966            });
 5967        }
 5968    }
 5969
 5970    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 5971        let Some(project) = self.project.clone() else {
 5972            return;
 5973        };
 5974        self.reload(project, cx).detach_and_notify_err(cx);
 5975    }
 5976
 5977    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5978        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 5979        if !revert_changes.is_empty() {
 5980            self.transact(cx, |editor, cx| {
 5981                editor.revert(revert_changes, cx);
 5982            });
 5983        }
 5984    }
 5985
 5986    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 5987        let snapshot = self.buffer.read(cx).read(cx);
 5988        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 5989            drop(snapshot);
 5990            let mut revert_changes = HashMap::default();
 5991            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5992            if !revert_changes.is_empty() {
 5993                self.revert(revert_changes, cx)
 5994            }
 5995        }
 5996    }
 5997
 5998    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5999        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6000            let project_path = buffer.read(cx).project_path(cx)?;
 6001            let project = self.project.as_ref()?.read(cx);
 6002            let entry = project.entry_for_path(&project_path, cx)?;
 6003            let parent = match &entry.canonical_path {
 6004                Some(canonical_path) => canonical_path.to_path_buf(),
 6005                None => project.absolute_path(&project_path, cx)?,
 6006            }
 6007            .parent()?
 6008            .to_path_buf();
 6009            Some(parent)
 6010        }) {
 6011            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6012        }
 6013    }
 6014
 6015    fn gather_revert_changes(
 6016        &mut self,
 6017        selections: &[Selection<Point>],
 6018        cx: &mut ViewContext<'_, Editor>,
 6019    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6020        let mut revert_changes = HashMap::default();
 6021        let snapshot = self.snapshot(cx);
 6022        for hunk in hunks_for_selections(&snapshot, selections) {
 6023            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6024        }
 6025        revert_changes
 6026    }
 6027
 6028    pub fn prepare_revert_change(
 6029        &mut self,
 6030        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6031        hunk: &MultiBufferDiffHunk,
 6032        cx: &AppContext,
 6033    ) -> Option<()> {
 6034        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6035        let buffer = buffer.read(cx);
 6036        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6037        let original_text = change_set
 6038            .read(cx)
 6039            .base_text
 6040            .as_ref()?
 6041            .read(cx)
 6042            .as_rope()
 6043            .slice(hunk.diff_base_byte_range.clone());
 6044        let buffer_snapshot = buffer.snapshot();
 6045        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6046        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6047            probe
 6048                .0
 6049                .start
 6050                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6051                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6052        }) {
 6053            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6054            Some(())
 6055        } else {
 6056            None
 6057        }
 6058    }
 6059
 6060    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6061        self.manipulate_lines(cx, |lines| lines.reverse())
 6062    }
 6063
 6064    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6065        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6066    }
 6067
 6068    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6069    where
 6070        Fn: FnMut(&mut Vec<&str>),
 6071    {
 6072        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6073        let buffer = self.buffer.read(cx).snapshot(cx);
 6074
 6075        let mut edits = Vec::new();
 6076
 6077        let selections = self.selections.all::<Point>(cx);
 6078        let mut selections = selections.iter().peekable();
 6079        let mut contiguous_row_selections = Vec::new();
 6080        let mut new_selections = Vec::new();
 6081        let mut added_lines = 0;
 6082        let mut removed_lines = 0;
 6083
 6084        while let Some(selection) = selections.next() {
 6085            let (start_row, end_row) = consume_contiguous_rows(
 6086                &mut contiguous_row_selections,
 6087                selection,
 6088                &display_map,
 6089                &mut selections,
 6090            );
 6091
 6092            let start_point = Point::new(start_row.0, 0);
 6093            let end_point = Point::new(
 6094                end_row.previous_row().0,
 6095                buffer.line_len(end_row.previous_row()),
 6096            );
 6097            let text = buffer
 6098                .text_for_range(start_point..end_point)
 6099                .collect::<String>();
 6100
 6101            let mut lines = text.split('\n').collect_vec();
 6102
 6103            let lines_before = lines.len();
 6104            callback(&mut lines);
 6105            let lines_after = lines.len();
 6106
 6107            edits.push((start_point..end_point, lines.join("\n")));
 6108
 6109            // Selections must change based on added and removed line count
 6110            let start_row =
 6111                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6112            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6113            new_selections.push(Selection {
 6114                id: selection.id,
 6115                start: start_row,
 6116                end: end_row,
 6117                goal: SelectionGoal::None,
 6118                reversed: selection.reversed,
 6119            });
 6120
 6121            if lines_after > lines_before {
 6122                added_lines += lines_after - lines_before;
 6123            } else if lines_before > lines_after {
 6124                removed_lines += lines_before - lines_after;
 6125            }
 6126        }
 6127
 6128        self.transact(cx, |this, cx| {
 6129            let buffer = this.buffer.update(cx, |buffer, cx| {
 6130                buffer.edit(edits, None, cx);
 6131                buffer.snapshot(cx)
 6132            });
 6133
 6134            // Recalculate offsets on newly edited buffer
 6135            let new_selections = new_selections
 6136                .iter()
 6137                .map(|s| {
 6138                    let start_point = Point::new(s.start.0, 0);
 6139                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6140                    Selection {
 6141                        id: s.id,
 6142                        start: buffer.point_to_offset(start_point),
 6143                        end: buffer.point_to_offset(end_point),
 6144                        goal: s.goal,
 6145                        reversed: s.reversed,
 6146                    }
 6147                })
 6148                .collect();
 6149
 6150            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6151                s.select(new_selections);
 6152            });
 6153
 6154            this.request_autoscroll(Autoscroll::fit(), cx);
 6155        });
 6156    }
 6157
 6158    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6159        self.manipulate_text(cx, |text| text.to_uppercase())
 6160    }
 6161
 6162    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6163        self.manipulate_text(cx, |text| text.to_lowercase())
 6164    }
 6165
 6166    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6167        self.manipulate_text(cx, |text| {
 6168            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6169            // https://github.com/rutrum/convert-case/issues/16
 6170            text.split('\n')
 6171                .map(|line| line.to_case(Case::Title))
 6172                .join("\n")
 6173        })
 6174    }
 6175
 6176    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6177        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6178    }
 6179
 6180    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6181        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6182    }
 6183
 6184    pub fn convert_to_upper_camel_case(
 6185        &mut self,
 6186        _: &ConvertToUpperCamelCase,
 6187        cx: &mut ViewContext<Self>,
 6188    ) {
 6189        self.manipulate_text(cx, |text| {
 6190            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6191            // https://github.com/rutrum/convert-case/issues/16
 6192            text.split('\n')
 6193                .map(|line| line.to_case(Case::UpperCamel))
 6194                .join("\n")
 6195        })
 6196    }
 6197
 6198    pub fn convert_to_lower_camel_case(
 6199        &mut self,
 6200        _: &ConvertToLowerCamelCase,
 6201        cx: &mut ViewContext<Self>,
 6202    ) {
 6203        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6204    }
 6205
 6206    pub fn convert_to_opposite_case(
 6207        &mut self,
 6208        _: &ConvertToOppositeCase,
 6209        cx: &mut ViewContext<Self>,
 6210    ) {
 6211        self.manipulate_text(cx, |text| {
 6212            text.chars()
 6213                .fold(String::with_capacity(text.len()), |mut t, c| {
 6214                    if c.is_uppercase() {
 6215                        t.extend(c.to_lowercase());
 6216                    } else {
 6217                        t.extend(c.to_uppercase());
 6218                    }
 6219                    t
 6220                })
 6221        })
 6222    }
 6223
 6224    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6225    where
 6226        Fn: FnMut(&str) -> String,
 6227    {
 6228        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6229        let buffer = self.buffer.read(cx).snapshot(cx);
 6230
 6231        let mut new_selections = Vec::new();
 6232        let mut edits = Vec::new();
 6233        let mut selection_adjustment = 0i32;
 6234
 6235        for selection in self.selections.all::<usize>(cx) {
 6236            let selection_is_empty = selection.is_empty();
 6237
 6238            let (start, end) = if selection_is_empty {
 6239                let word_range = movement::surrounding_word(
 6240                    &display_map,
 6241                    selection.start.to_display_point(&display_map),
 6242                );
 6243                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6244                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6245                (start, end)
 6246            } else {
 6247                (selection.start, selection.end)
 6248            };
 6249
 6250            let text = buffer.text_for_range(start..end).collect::<String>();
 6251            let old_length = text.len() as i32;
 6252            let text = callback(&text);
 6253
 6254            new_selections.push(Selection {
 6255                start: (start as i32 - selection_adjustment) as usize,
 6256                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6257                goal: SelectionGoal::None,
 6258                ..selection
 6259            });
 6260
 6261            selection_adjustment += old_length - text.len() as i32;
 6262
 6263            edits.push((start..end, text));
 6264        }
 6265
 6266        self.transact(cx, |this, cx| {
 6267            this.buffer.update(cx, |buffer, cx| {
 6268                buffer.edit(edits, None, cx);
 6269            });
 6270
 6271            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6272                s.select(new_selections);
 6273            });
 6274
 6275            this.request_autoscroll(Autoscroll::fit(), cx);
 6276        });
 6277    }
 6278
 6279    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6280        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6281        let buffer = &display_map.buffer_snapshot;
 6282        let selections = self.selections.all::<Point>(cx);
 6283
 6284        let mut edits = Vec::new();
 6285        let mut selections_iter = selections.iter().peekable();
 6286        while let Some(selection) = selections_iter.next() {
 6287            let mut rows = selection.spanned_rows(false, &display_map);
 6288            // duplicate line-wise
 6289            if whole_lines || selection.start == selection.end {
 6290                // Avoid duplicating the same lines twice.
 6291                while let Some(next_selection) = selections_iter.peek() {
 6292                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6293                    if next_rows.start < rows.end {
 6294                        rows.end = next_rows.end;
 6295                        selections_iter.next().unwrap();
 6296                    } else {
 6297                        break;
 6298                    }
 6299                }
 6300
 6301                // Copy the text from the selected row region and splice it either at the start
 6302                // or end of the region.
 6303                let start = Point::new(rows.start.0, 0);
 6304                let end = Point::new(
 6305                    rows.end.previous_row().0,
 6306                    buffer.line_len(rows.end.previous_row()),
 6307                );
 6308                let text = buffer
 6309                    .text_for_range(start..end)
 6310                    .chain(Some("\n"))
 6311                    .collect::<String>();
 6312                let insert_location = if upwards {
 6313                    Point::new(rows.end.0, 0)
 6314                } else {
 6315                    start
 6316                };
 6317                edits.push((insert_location..insert_location, text));
 6318            } else {
 6319                // duplicate character-wise
 6320                let start = selection.start;
 6321                let end = selection.end;
 6322                let text = buffer.text_for_range(start..end).collect::<String>();
 6323                edits.push((selection.end..selection.end, text));
 6324            }
 6325        }
 6326
 6327        self.transact(cx, |this, cx| {
 6328            this.buffer.update(cx, |buffer, cx| {
 6329                buffer.edit(edits, None, cx);
 6330            });
 6331
 6332            this.request_autoscroll(Autoscroll::fit(), cx);
 6333        });
 6334    }
 6335
 6336    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6337        self.duplicate(true, true, cx);
 6338    }
 6339
 6340    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6341        self.duplicate(false, true, cx);
 6342    }
 6343
 6344    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6345        self.duplicate(false, false, cx);
 6346    }
 6347
 6348    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6349        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6350        let buffer = self.buffer.read(cx).snapshot(cx);
 6351
 6352        let mut edits = Vec::new();
 6353        let mut unfold_ranges = Vec::new();
 6354        let mut refold_creases = Vec::new();
 6355
 6356        let selections = self.selections.all::<Point>(cx);
 6357        let mut selections = selections.iter().peekable();
 6358        let mut contiguous_row_selections = Vec::new();
 6359        let mut new_selections = Vec::new();
 6360
 6361        while let Some(selection) = selections.next() {
 6362            // Find all the selections that span a contiguous row range
 6363            let (start_row, end_row) = consume_contiguous_rows(
 6364                &mut contiguous_row_selections,
 6365                selection,
 6366                &display_map,
 6367                &mut selections,
 6368            );
 6369
 6370            // Move the text spanned by the row range to be before the line preceding the row range
 6371            if start_row.0 > 0 {
 6372                let range_to_move = Point::new(
 6373                    start_row.previous_row().0,
 6374                    buffer.line_len(start_row.previous_row()),
 6375                )
 6376                    ..Point::new(
 6377                        end_row.previous_row().0,
 6378                        buffer.line_len(end_row.previous_row()),
 6379                    );
 6380                let insertion_point = display_map
 6381                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6382                    .0;
 6383
 6384                // Don't move lines across excerpts
 6385                if buffer
 6386                    .excerpt_boundaries_in_range((
 6387                        Bound::Excluded(insertion_point),
 6388                        Bound::Included(range_to_move.end),
 6389                    ))
 6390                    .next()
 6391                    .is_none()
 6392                {
 6393                    let text = buffer
 6394                        .text_for_range(range_to_move.clone())
 6395                        .flat_map(|s| s.chars())
 6396                        .skip(1)
 6397                        .chain(['\n'])
 6398                        .collect::<String>();
 6399
 6400                    edits.push((
 6401                        buffer.anchor_after(range_to_move.start)
 6402                            ..buffer.anchor_before(range_to_move.end),
 6403                        String::new(),
 6404                    ));
 6405                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6406                    edits.push((insertion_anchor..insertion_anchor, text));
 6407
 6408                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6409
 6410                    // Move selections up
 6411                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6412                        |mut selection| {
 6413                            selection.start.row -= row_delta;
 6414                            selection.end.row -= row_delta;
 6415                            selection
 6416                        },
 6417                    ));
 6418
 6419                    // Move folds up
 6420                    unfold_ranges.push(range_to_move.clone());
 6421                    for fold in display_map.folds_in_range(
 6422                        buffer.anchor_before(range_to_move.start)
 6423                            ..buffer.anchor_after(range_to_move.end),
 6424                    ) {
 6425                        let mut start = fold.range.start.to_point(&buffer);
 6426                        let mut end = fold.range.end.to_point(&buffer);
 6427                        start.row -= row_delta;
 6428                        end.row -= row_delta;
 6429                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6430                    }
 6431                }
 6432            }
 6433
 6434            // If we didn't move line(s), preserve the existing selections
 6435            new_selections.append(&mut contiguous_row_selections);
 6436        }
 6437
 6438        self.transact(cx, |this, cx| {
 6439            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6440            this.buffer.update(cx, |buffer, cx| {
 6441                for (range, text) in edits {
 6442                    buffer.edit([(range, text)], None, cx);
 6443                }
 6444            });
 6445            this.fold_creases(refold_creases, true, cx);
 6446            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6447                s.select(new_selections);
 6448            })
 6449        });
 6450    }
 6451
 6452    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6453        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6454        let buffer = self.buffer.read(cx).snapshot(cx);
 6455
 6456        let mut edits = Vec::new();
 6457        let mut unfold_ranges = Vec::new();
 6458        let mut refold_creases = Vec::new();
 6459
 6460        let selections = self.selections.all::<Point>(cx);
 6461        let mut selections = selections.iter().peekable();
 6462        let mut contiguous_row_selections = Vec::new();
 6463        let mut new_selections = Vec::new();
 6464
 6465        while let Some(selection) = selections.next() {
 6466            // Find all the selections that span a contiguous row range
 6467            let (start_row, end_row) = consume_contiguous_rows(
 6468                &mut contiguous_row_selections,
 6469                selection,
 6470                &display_map,
 6471                &mut selections,
 6472            );
 6473
 6474            // Move the text spanned by the row range to be after the last line of the row range
 6475            if end_row.0 <= buffer.max_point().row {
 6476                let range_to_move =
 6477                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6478                let insertion_point = display_map
 6479                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6480                    .0;
 6481
 6482                // Don't move lines across excerpt boundaries
 6483                if buffer
 6484                    .excerpt_boundaries_in_range((
 6485                        Bound::Excluded(range_to_move.start),
 6486                        Bound::Included(insertion_point),
 6487                    ))
 6488                    .next()
 6489                    .is_none()
 6490                {
 6491                    let mut text = String::from("\n");
 6492                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6493                    text.pop(); // Drop trailing newline
 6494                    edits.push((
 6495                        buffer.anchor_after(range_to_move.start)
 6496                            ..buffer.anchor_before(range_to_move.end),
 6497                        String::new(),
 6498                    ));
 6499                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6500                    edits.push((insertion_anchor..insertion_anchor, text));
 6501
 6502                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6503
 6504                    // Move selections down
 6505                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6506                        |mut selection| {
 6507                            selection.start.row += row_delta;
 6508                            selection.end.row += row_delta;
 6509                            selection
 6510                        },
 6511                    ));
 6512
 6513                    // Move folds down
 6514                    unfold_ranges.push(range_to_move.clone());
 6515                    for fold in display_map.folds_in_range(
 6516                        buffer.anchor_before(range_to_move.start)
 6517                            ..buffer.anchor_after(range_to_move.end),
 6518                    ) {
 6519                        let mut start = fold.range.start.to_point(&buffer);
 6520                        let mut end = fold.range.end.to_point(&buffer);
 6521                        start.row += row_delta;
 6522                        end.row += row_delta;
 6523                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6524                    }
 6525                }
 6526            }
 6527
 6528            // If we didn't move line(s), preserve the existing selections
 6529            new_selections.append(&mut contiguous_row_selections);
 6530        }
 6531
 6532        self.transact(cx, |this, cx| {
 6533            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6534            this.buffer.update(cx, |buffer, cx| {
 6535                for (range, text) in edits {
 6536                    buffer.edit([(range, text)], None, cx);
 6537                }
 6538            });
 6539            this.fold_creases(refold_creases, true, cx);
 6540            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6541        });
 6542    }
 6543
 6544    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6545        let text_layout_details = &self.text_layout_details(cx);
 6546        self.transact(cx, |this, cx| {
 6547            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6548                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6549                let line_mode = s.line_mode;
 6550                s.move_with(|display_map, selection| {
 6551                    if !selection.is_empty() || line_mode {
 6552                        return;
 6553                    }
 6554
 6555                    let mut head = selection.head();
 6556                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6557                    if head.column() == display_map.line_len(head.row()) {
 6558                        transpose_offset = display_map
 6559                            .buffer_snapshot
 6560                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6561                    }
 6562
 6563                    if transpose_offset == 0 {
 6564                        return;
 6565                    }
 6566
 6567                    *head.column_mut() += 1;
 6568                    head = display_map.clip_point(head, Bias::Right);
 6569                    let goal = SelectionGoal::HorizontalPosition(
 6570                        display_map
 6571                            .x_for_display_point(head, text_layout_details)
 6572                            .into(),
 6573                    );
 6574                    selection.collapse_to(head, goal);
 6575
 6576                    let transpose_start = display_map
 6577                        .buffer_snapshot
 6578                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6579                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6580                        let transpose_end = display_map
 6581                            .buffer_snapshot
 6582                            .clip_offset(transpose_offset + 1, Bias::Right);
 6583                        if let Some(ch) =
 6584                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6585                        {
 6586                            edits.push((transpose_start..transpose_offset, String::new()));
 6587                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6588                        }
 6589                    }
 6590                });
 6591                edits
 6592            });
 6593            this.buffer
 6594                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6595            let selections = this.selections.all::<usize>(cx);
 6596            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6597                s.select(selections);
 6598            });
 6599        });
 6600    }
 6601
 6602    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6603        self.rewrap_impl(IsVimMode::No, cx)
 6604    }
 6605
 6606    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6607        let buffer = self.buffer.read(cx).snapshot(cx);
 6608        let selections = self.selections.all::<Point>(cx);
 6609        let mut selections = selections.iter().peekable();
 6610
 6611        let mut edits = Vec::new();
 6612        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6613
 6614        while let Some(selection) = selections.next() {
 6615            let mut start_row = selection.start.row;
 6616            let mut end_row = selection.end.row;
 6617
 6618            // Skip selections that overlap with a range that has already been rewrapped.
 6619            let selection_range = start_row..end_row;
 6620            if rewrapped_row_ranges
 6621                .iter()
 6622                .any(|range| range.overlaps(&selection_range))
 6623            {
 6624                continue;
 6625            }
 6626
 6627            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6628
 6629            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6630                match language_scope.language_name().0.as_ref() {
 6631                    "Markdown" | "Plain Text" => {
 6632                        should_rewrap = true;
 6633                    }
 6634                    _ => {}
 6635                }
 6636            }
 6637
 6638            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6639
 6640            // Since not all lines in the selection may be at the same indent
 6641            // level, choose the indent size that is the most common between all
 6642            // of the lines.
 6643            //
 6644            // If there is a tie, we use the deepest indent.
 6645            let (indent_size, indent_end) = {
 6646                let mut indent_size_occurrences = HashMap::default();
 6647                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6648
 6649                for row in start_row..=end_row {
 6650                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6651                    rows_by_indent_size.entry(indent).or_default().push(row);
 6652                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6653                }
 6654
 6655                let indent_size = indent_size_occurrences
 6656                    .into_iter()
 6657                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6658                    .map(|(indent, _)| indent)
 6659                    .unwrap_or_default();
 6660                let row = rows_by_indent_size[&indent_size][0];
 6661                let indent_end = Point::new(row, indent_size.len);
 6662
 6663                (indent_size, indent_end)
 6664            };
 6665
 6666            let mut line_prefix = indent_size.chars().collect::<String>();
 6667
 6668            if let Some(comment_prefix) =
 6669                buffer
 6670                    .language_scope_at(selection.head())
 6671                    .and_then(|language| {
 6672                        language
 6673                            .line_comment_prefixes()
 6674                            .iter()
 6675                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6676                            .cloned()
 6677                    })
 6678            {
 6679                line_prefix.push_str(&comment_prefix);
 6680                should_rewrap = true;
 6681            }
 6682
 6683            if !should_rewrap {
 6684                continue;
 6685            }
 6686
 6687            if selection.is_empty() {
 6688                'expand_upwards: while start_row > 0 {
 6689                    let prev_row = start_row - 1;
 6690                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6691                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6692                    {
 6693                        start_row = prev_row;
 6694                    } else {
 6695                        break 'expand_upwards;
 6696                    }
 6697                }
 6698
 6699                'expand_downwards: while end_row < buffer.max_point().row {
 6700                    let next_row = end_row + 1;
 6701                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6702                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6703                    {
 6704                        end_row = next_row;
 6705                    } else {
 6706                        break 'expand_downwards;
 6707                    }
 6708                }
 6709            }
 6710
 6711            let start = Point::new(start_row, 0);
 6712            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6713            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6714            let Some(lines_without_prefixes) = selection_text
 6715                .lines()
 6716                .map(|line| {
 6717                    line.strip_prefix(&line_prefix)
 6718                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6719                        .ok_or_else(|| {
 6720                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6721                        })
 6722                })
 6723                .collect::<Result<Vec<_>, _>>()
 6724                .log_err()
 6725            else {
 6726                continue;
 6727            };
 6728
 6729            let wrap_column = buffer
 6730                .settings_at(Point::new(start_row, 0), cx)
 6731                .preferred_line_length as usize;
 6732            let wrapped_text = wrap_with_prefix(
 6733                line_prefix,
 6734                lines_without_prefixes.join(" "),
 6735                wrap_column,
 6736                tab_size,
 6737            );
 6738
 6739            // TODO: should always use char-based diff while still supporting cursor behavior that
 6740            // matches vim.
 6741            let diff = match is_vim_mode {
 6742                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6743                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6744            };
 6745            let mut offset = start.to_offset(&buffer);
 6746            let mut moved_since_edit = true;
 6747
 6748            for change in diff.iter_all_changes() {
 6749                let value = change.value();
 6750                match change.tag() {
 6751                    ChangeTag::Equal => {
 6752                        offset += value.len();
 6753                        moved_since_edit = true;
 6754                    }
 6755                    ChangeTag::Delete => {
 6756                        let start = buffer.anchor_after(offset);
 6757                        let end = buffer.anchor_before(offset + value.len());
 6758
 6759                        if moved_since_edit {
 6760                            edits.push((start..end, String::new()));
 6761                        } else {
 6762                            edits.last_mut().unwrap().0.end = end;
 6763                        }
 6764
 6765                        offset += value.len();
 6766                        moved_since_edit = false;
 6767                    }
 6768                    ChangeTag::Insert => {
 6769                        if moved_since_edit {
 6770                            let anchor = buffer.anchor_after(offset);
 6771                            edits.push((anchor..anchor, value.to_string()));
 6772                        } else {
 6773                            edits.last_mut().unwrap().1.push_str(value);
 6774                        }
 6775
 6776                        moved_since_edit = false;
 6777                    }
 6778                }
 6779            }
 6780
 6781            rewrapped_row_ranges.push(start_row..=end_row);
 6782        }
 6783
 6784        self.buffer
 6785            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6786    }
 6787
 6788    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6789        let mut text = String::new();
 6790        let buffer = self.buffer.read(cx).snapshot(cx);
 6791        let mut selections = self.selections.all::<Point>(cx);
 6792        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6793        {
 6794            let max_point = buffer.max_point();
 6795            let mut is_first = true;
 6796            for selection in &mut selections {
 6797                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6798                if is_entire_line {
 6799                    selection.start = Point::new(selection.start.row, 0);
 6800                    if !selection.is_empty() && selection.end.column == 0 {
 6801                        selection.end = cmp::min(max_point, selection.end);
 6802                    } else {
 6803                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6804                    }
 6805                    selection.goal = SelectionGoal::None;
 6806                }
 6807                if is_first {
 6808                    is_first = false;
 6809                } else {
 6810                    text += "\n";
 6811                }
 6812                let mut len = 0;
 6813                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6814                    text.push_str(chunk);
 6815                    len += chunk.len();
 6816                }
 6817                clipboard_selections.push(ClipboardSelection {
 6818                    len,
 6819                    is_entire_line,
 6820                    first_line_indent: buffer
 6821                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6822                        .len,
 6823                });
 6824            }
 6825        }
 6826
 6827        self.transact(cx, |this, cx| {
 6828            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6829                s.select(selections);
 6830            });
 6831            this.insert("", cx);
 6832        });
 6833        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6834    }
 6835
 6836    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6837        let item = self.cut_common(cx);
 6838        cx.write_to_clipboard(item);
 6839    }
 6840
 6841    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6842        self.change_selections(None, cx, |s| {
 6843            s.move_with(|snapshot, sel| {
 6844                if sel.is_empty() {
 6845                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6846                }
 6847            });
 6848        });
 6849        let item = self.cut_common(cx);
 6850        cx.set_global(KillRing(item))
 6851    }
 6852
 6853    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6854        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6855            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6856                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6857            } else {
 6858                return;
 6859            }
 6860        } else {
 6861            return;
 6862        };
 6863        self.do_paste(&text, metadata, false, cx);
 6864    }
 6865
 6866    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6867        let selections = self.selections.all::<Point>(cx);
 6868        let buffer = self.buffer.read(cx).read(cx);
 6869        let mut text = String::new();
 6870
 6871        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6872        {
 6873            let max_point = buffer.max_point();
 6874            let mut is_first = true;
 6875            for selection in selections.iter() {
 6876                let mut start = selection.start;
 6877                let mut end = selection.end;
 6878                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6879                if is_entire_line {
 6880                    start = Point::new(start.row, 0);
 6881                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6882                }
 6883                if is_first {
 6884                    is_first = false;
 6885                } else {
 6886                    text += "\n";
 6887                }
 6888                let mut len = 0;
 6889                for chunk in buffer.text_for_range(start..end) {
 6890                    text.push_str(chunk);
 6891                    len += chunk.len();
 6892                }
 6893                clipboard_selections.push(ClipboardSelection {
 6894                    len,
 6895                    is_entire_line,
 6896                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6897                });
 6898            }
 6899        }
 6900
 6901        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6902            text,
 6903            clipboard_selections,
 6904        ));
 6905    }
 6906
 6907    pub fn do_paste(
 6908        &mut self,
 6909        text: &String,
 6910        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6911        handle_entire_lines: bool,
 6912        cx: &mut ViewContext<Self>,
 6913    ) {
 6914        if self.read_only(cx) {
 6915            return;
 6916        }
 6917
 6918        let clipboard_text = Cow::Borrowed(text);
 6919
 6920        self.transact(cx, |this, cx| {
 6921            if let Some(mut clipboard_selections) = clipboard_selections {
 6922                let old_selections = this.selections.all::<usize>(cx);
 6923                let all_selections_were_entire_line =
 6924                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6925                let first_selection_indent_column =
 6926                    clipboard_selections.first().map(|s| s.first_line_indent);
 6927                if clipboard_selections.len() != old_selections.len() {
 6928                    clipboard_selections.drain(..);
 6929                }
 6930                let cursor_offset = this.selections.last::<usize>(cx).head();
 6931                let mut auto_indent_on_paste = true;
 6932
 6933                this.buffer.update(cx, |buffer, cx| {
 6934                    let snapshot = buffer.read(cx);
 6935                    auto_indent_on_paste =
 6936                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6937
 6938                    let mut start_offset = 0;
 6939                    let mut edits = Vec::new();
 6940                    let mut original_indent_columns = Vec::new();
 6941                    for (ix, selection) in old_selections.iter().enumerate() {
 6942                        let to_insert;
 6943                        let entire_line;
 6944                        let original_indent_column;
 6945                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6946                            let end_offset = start_offset + clipboard_selection.len;
 6947                            to_insert = &clipboard_text[start_offset..end_offset];
 6948                            entire_line = clipboard_selection.is_entire_line;
 6949                            start_offset = end_offset + 1;
 6950                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6951                        } else {
 6952                            to_insert = clipboard_text.as_str();
 6953                            entire_line = all_selections_were_entire_line;
 6954                            original_indent_column = first_selection_indent_column
 6955                        }
 6956
 6957                        // If the corresponding selection was empty when this slice of the
 6958                        // clipboard text was written, then the entire line containing the
 6959                        // selection was copied. If this selection is also currently empty,
 6960                        // then paste the line before the current line of the buffer.
 6961                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6962                            let column = selection.start.to_point(&snapshot).column as usize;
 6963                            let line_start = selection.start - column;
 6964                            line_start..line_start
 6965                        } else {
 6966                            selection.range()
 6967                        };
 6968
 6969                        edits.push((range, to_insert));
 6970                        original_indent_columns.extend(original_indent_column);
 6971                    }
 6972                    drop(snapshot);
 6973
 6974                    buffer.edit(
 6975                        edits,
 6976                        if auto_indent_on_paste {
 6977                            Some(AutoindentMode::Block {
 6978                                original_indent_columns,
 6979                            })
 6980                        } else {
 6981                            None
 6982                        },
 6983                        cx,
 6984                    );
 6985                });
 6986
 6987                let selections = this.selections.all::<usize>(cx);
 6988                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6989            } else {
 6990                this.insert(&clipboard_text, cx);
 6991            }
 6992        });
 6993    }
 6994
 6995    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6996        if let Some(item) = cx.read_from_clipboard() {
 6997            let entries = item.entries();
 6998
 6999            match entries.first() {
 7000                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7001                // of all the pasted entries.
 7002                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7003                    .do_paste(
 7004                        clipboard_string.text(),
 7005                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7006                        true,
 7007                        cx,
 7008                    ),
 7009                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7010            }
 7011        }
 7012    }
 7013
 7014    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7015        if self.read_only(cx) {
 7016            return;
 7017        }
 7018
 7019        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7020            if let Some((selections, _)) =
 7021                self.selection_history.transaction(transaction_id).cloned()
 7022            {
 7023                self.change_selections(None, cx, |s| {
 7024                    s.select_anchors(selections.to_vec());
 7025                });
 7026            }
 7027            self.request_autoscroll(Autoscroll::fit(), cx);
 7028            self.unmark_text(cx);
 7029            self.refresh_inline_completion(true, false, cx);
 7030            cx.emit(EditorEvent::Edited { transaction_id });
 7031            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7032        }
 7033    }
 7034
 7035    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7036        if self.read_only(cx) {
 7037            return;
 7038        }
 7039
 7040        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7041            if let Some((_, Some(selections))) =
 7042                self.selection_history.transaction(transaction_id).cloned()
 7043            {
 7044                self.change_selections(None, cx, |s| {
 7045                    s.select_anchors(selections.to_vec());
 7046                });
 7047            }
 7048            self.request_autoscroll(Autoscroll::fit(), cx);
 7049            self.unmark_text(cx);
 7050            self.refresh_inline_completion(true, false, cx);
 7051            cx.emit(EditorEvent::Edited { transaction_id });
 7052        }
 7053    }
 7054
 7055    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7056        self.buffer
 7057            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7058    }
 7059
 7060    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7061        self.buffer
 7062            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7063    }
 7064
 7065    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7066        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7067            let line_mode = s.line_mode;
 7068            s.move_with(|map, selection| {
 7069                let cursor = if selection.is_empty() && !line_mode {
 7070                    movement::left(map, selection.start)
 7071                } else {
 7072                    selection.start
 7073                };
 7074                selection.collapse_to(cursor, SelectionGoal::None);
 7075            });
 7076        })
 7077    }
 7078
 7079    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7080        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7081            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7082        })
 7083    }
 7084
 7085    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7086        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7087            let line_mode = s.line_mode;
 7088            s.move_with(|map, selection| {
 7089                let cursor = if selection.is_empty() && !line_mode {
 7090                    movement::right(map, selection.end)
 7091                } else {
 7092                    selection.end
 7093                };
 7094                selection.collapse_to(cursor, SelectionGoal::None)
 7095            });
 7096        })
 7097    }
 7098
 7099    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7100        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7101            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7102        })
 7103    }
 7104
 7105    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7106        if self.take_rename(true, cx).is_some() {
 7107            return;
 7108        }
 7109
 7110        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7111            cx.propagate();
 7112            return;
 7113        }
 7114
 7115        let text_layout_details = &self.text_layout_details(cx);
 7116        let selection_count = self.selections.count();
 7117        let first_selection = self.selections.first_anchor();
 7118
 7119        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7120            let line_mode = s.line_mode;
 7121            s.move_with(|map, selection| {
 7122                if !selection.is_empty() && !line_mode {
 7123                    selection.goal = SelectionGoal::None;
 7124                }
 7125                let (cursor, goal) = movement::up(
 7126                    map,
 7127                    selection.start,
 7128                    selection.goal,
 7129                    false,
 7130                    text_layout_details,
 7131                );
 7132                selection.collapse_to(cursor, goal);
 7133            });
 7134        });
 7135
 7136        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7137        {
 7138            cx.propagate();
 7139        }
 7140    }
 7141
 7142    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7143        if self.take_rename(true, cx).is_some() {
 7144            return;
 7145        }
 7146
 7147        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7148            cx.propagate();
 7149            return;
 7150        }
 7151
 7152        let text_layout_details = &self.text_layout_details(cx);
 7153
 7154        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7155            let line_mode = s.line_mode;
 7156            s.move_with(|map, selection| {
 7157                if !selection.is_empty() && !line_mode {
 7158                    selection.goal = SelectionGoal::None;
 7159                }
 7160                let (cursor, goal) = movement::up_by_rows(
 7161                    map,
 7162                    selection.start,
 7163                    action.lines,
 7164                    selection.goal,
 7165                    false,
 7166                    text_layout_details,
 7167                );
 7168                selection.collapse_to(cursor, goal);
 7169            });
 7170        })
 7171    }
 7172
 7173    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7174        if self.take_rename(true, cx).is_some() {
 7175            return;
 7176        }
 7177
 7178        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7179            cx.propagate();
 7180            return;
 7181        }
 7182
 7183        let text_layout_details = &self.text_layout_details(cx);
 7184
 7185        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7186            let line_mode = s.line_mode;
 7187            s.move_with(|map, selection| {
 7188                if !selection.is_empty() && !line_mode {
 7189                    selection.goal = SelectionGoal::None;
 7190                }
 7191                let (cursor, goal) = movement::down_by_rows(
 7192                    map,
 7193                    selection.start,
 7194                    action.lines,
 7195                    selection.goal,
 7196                    false,
 7197                    text_layout_details,
 7198                );
 7199                selection.collapse_to(cursor, goal);
 7200            });
 7201        })
 7202    }
 7203
 7204    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7205        let text_layout_details = &self.text_layout_details(cx);
 7206        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7207            s.move_heads_with(|map, head, goal| {
 7208                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7209            })
 7210        })
 7211    }
 7212
 7213    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7214        let text_layout_details = &self.text_layout_details(cx);
 7215        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7216            s.move_heads_with(|map, head, goal| {
 7217                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7218            })
 7219        })
 7220    }
 7221
 7222    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7223        let Some(row_count) = self.visible_row_count() else {
 7224            return;
 7225        };
 7226
 7227        let text_layout_details = &self.text_layout_details(cx);
 7228
 7229        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7230            s.move_heads_with(|map, head, goal| {
 7231                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7232            })
 7233        })
 7234    }
 7235
 7236    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7237        if self.take_rename(true, cx).is_some() {
 7238            return;
 7239        }
 7240
 7241        if self
 7242            .context_menu
 7243            .borrow_mut()
 7244            .as_mut()
 7245            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7246            .unwrap_or(false)
 7247        {
 7248            return;
 7249        }
 7250
 7251        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7252            cx.propagate();
 7253            return;
 7254        }
 7255
 7256        let Some(row_count) = self.visible_row_count() else {
 7257            return;
 7258        };
 7259
 7260        let autoscroll = if action.center_cursor {
 7261            Autoscroll::center()
 7262        } else {
 7263            Autoscroll::fit()
 7264        };
 7265
 7266        let text_layout_details = &self.text_layout_details(cx);
 7267
 7268        self.change_selections(Some(autoscroll), cx, |s| {
 7269            let line_mode = s.line_mode;
 7270            s.move_with(|map, selection| {
 7271                if !selection.is_empty() && !line_mode {
 7272                    selection.goal = SelectionGoal::None;
 7273                }
 7274                let (cursor, goal) = movement::up_by_rows(
 7275                    map,
 7276                    selection.end,
 7277                    row_count,
 7278                    selection.goal,
 7279                    false,
 7280                    text_layout_details,
 7281                );
 7282                selection.collapse_to(cursor, goal);
 7283            });
 7284        });
 7285    }
 7286
 7287    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7288        let text_layout_details = &self.text_layout_details(cx);
 7289        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7290            s.move_heads_with(|map, head, goal| {
 7291                movement::up(map, head, goal, false, text_layout_details)
 7292            })
 7293        })
 7294    }
 7295
 7296    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7297        self.take_rename(true, cx);
 7298
 7299        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7300            cx.propagate();
 7301            return;
 7302        }
 7303
 7304        let text_layout_details = &self.text_layout_details(cx);
 7305        let selection_count = self.selections.count();
 7306        let first_selection = self.selections.first_anchor();
 7307
 7308        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7309            let line_mode = s.line_mode;
 7310            s.move_with(|map, selection| {
 7311                if !selection.is_empty() && !line_mode {
 7312                    selection.goal = SelectionGoal::None;
 7313                }
 7314                let (cursor, goal) = movement::down(
 7315                    map,
 7316                    selection.end,
 7317                    selection.goal,
 7318                    false,
 7319                    text_layout_details,
 7320                );
 7321                selection.collapse_to(cursor, goal);
 7322            });
 7323        });
 7324
 7325        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7326        {
 7327            cx.propagate();
 7328        }
 7329    }
 7330
 7331    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7332        let Some(row_count) = self.visible_row_count() else {
 7333            return;
 7334        };
 7335
 7336        let text_layout_details = &self.text_layout_details(cx);
 7337
 7338        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7339            s.move_heads_with(|map, head, goal| {
 7340                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7341            })
 7342        })
 7343    }
 7344
 7345    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7346        if self.take_rename(true, cx).is_some() {
 7347            return;
 7348        }
 7349
 7350        if self
 7351            .context_menu
 7352            .borrow_mut()
 7353            .as_mut()
 7354            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7355            .unwrap_or(false)
 7356        {
 7357            return;
 7358        }
 7359
 7360        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7361            cx.propagate();
 7362            return;
 7363        }
 7364
 7365        let Some(row_count) = self.visible_row_count() else {
 7366            return;
 7367        };
 7368
 7369        let autoscroll = if action.center_cursor {
 7370            Autoscroll::center()
 7371        } else {
 7372            Autoscroll::fit()
 7373        };
 7374
 7375        let text_layout_details = &self.text_layout_details(cx);
 7376        self.change_selections(Some(autoscroll), cx, |s| {
 7377            let line_mode = s.line_mode;
 7378            s.move_with(|map, selection| {
 7379                if !selection.is_empty() && !line_mode {
 7380                    selection.goal = SelectionGoal::None;
 7381                }
 7382                let (cursor, goal) = movement::down_by_rows(
 7383                    map,
 7384                    selection.end,
 7385                    row_count,
 7386                    selection.goal,
 7387                    false,
 7388                    text_layout_details,
 7389                );
 7390                selection.collapse_to(cursor, goal);
 7391            });
 7392        });
 7393    }
 7394
 7395    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7396        let text_layout_details = &self.text_layout_details(cx);
 7397        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7398            s.move_heads_with(|map, head, goal| {
 7399                movement::down(map, head, goal, false, text_layout_details)
 7400            })
 7401        });
 7402    }
 7403
 7404    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7405        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7406            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7407        }
 7408    }
 7409
 7410    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7411        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7412            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7413        }
 7414    }
 7415
 7416    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7417        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7418            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7419        }
 7420    }
 7421
 7422    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7423        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7424            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7425        }
 7426    }
 7427
 7428    pub fn move_to_previous_word_start(
 7429        &mut self,
 7430        _: &MoveToPreviousWordStart,
 7431        cx: &mut ViewContext<Self>,
 7432    ) {
 7433        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7434            s.move_cursors_with(|map, head, _| {
 7435                (
 7436                    movement::previous_word_start(map, head),
 7437                    SelectionGoal::None,
 7438                )
 7439            });
 7440        })
 7441    }
 7442
 7443    pub fn move_to_previous_subword_start(
 7444        &mut self,
 7445        _: &MoveToPreviousSubwordStart,
 7446        cx: &mut ViewContext<Self>,
 7447    ) {
 7448        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7449            s.move_cursors_with(|map, head, _| {
 7450                (
 7451                    movement::previous_subword_start(map, head),
 7452                    SelectionGoal::None,
 7453                )
 7454            });
 7455        })
 7456    }
 7457
 7458    pub fn select_to_previous_word_start(
 7459        &mut self,
 7460        _: &SelectToPreviousWordStart,
 7461        cx: &mut ViewContext<Self>,
 7462    ) {
 7463        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7464            s.move_heads_with(|map, head, _| {
 7465                (
 7466                    movement::previous_word_start(map, head),
 7467                    SelectionGoal::None,
 7468                )
 7469            });
 7470        })
 7471    }
 7472
 7473    pub fn select_to_previous_subword_start(
 7474        &mut self,
 7475        _: &SelectToPreviousSubwordStart,
 7476        cx: &mut ViewContext<Self>,
 7477    ) {
 7478        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7479            s.move_heads_with(|map, head, _| {
 7480                (
 7481                    movement::previous_subword_start(map, head),
 7482                    SelectionGoal::None,
 7483                )
 7484            });
 7485        })
 7486    }
 7487
 7488    pub fn delete_to_previous_word_start(
 7489        &mut self,
 7490        action: &DeleteToPreviousWordStart,
 7491        cx: &mut ViewContext<Self>,
 7492    ) {
 7493        self.transact(cx, |this, cx| {
 7494            this.select_autoclose_pair(cx);
 7495            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7496                let line_mode = s.line_mode;
 7497                s.move_with(|map, selection| {
 7498                    if selection.is_empty() && !line_mode {
 7499                        let cursor = if action.ignore_newlines {
 7500                            movement::previous_word_start(map, selection.head())
 7501                        } else {
 7502                            movement::previous_word_start_or_newline(map, selection.head())
 7503                        };
 7504                        selection.set_head(cursor, SelectionGoal::None);
 7505                    }
 7506                });
 7507            });
 7508            this.insert("", cx);
 7509        });
 7510    }
 7511
 7512    pub fn delete_to_previous_subword_start(
 7513        &mut self,
 7514        _: &DeleteToPreviousSubwordStart,
 7515        cx: &mut ViewContext<Self>,
 7516    ) {
 7517        self.transact(cx, |this, cx| {
 7518            this.select_autoclose_pair(cx);
 7519            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7520                let line_mode = s.line_mode;
 7521                s.move_with(|map, selection| {
 7522                    if selection.is_empty() && !line_mode {
 7523                        let cursor = movement::previous_subword_start(map, selection.head());
 7524                        selection.set_head(cursor, SelectionGoal::None);
 7525                    }
 7526                });
 7527            });
 7528            this.insert("", cx);
 7529        });
 7530    }
 7531
 7532    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7533        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7534            s.move_cursors_with(|map, head, _| {
 7535                (movement::next_word_end(map, head), SelectionGoal::None)
 7536            });
 7537        })
 7538    }
 7539
 7540    pub fn move_to_next_subword_end(
 7541        &mut self,
 7542        _: &MoveToNextSubwordEnd,
 7543        cx: &mut ViewContext<Self>,
 7544    ) {
 7545        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7546            s.move_cursors_with(|map, head, _| {
 7547                (movement::next_subword_end(map, head), SelectionGoal::None)
 7548            });
 7549        })
 7550    }
 7551
 7552    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7553        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7554            s.move_heads_with(|map, head, _| {
 7555                (movement::next_word_end(map, head), SelectionGoal::None)
 7556            });
 7557        })
 7558    }
 7559
 7560    pub fn select_to_next_subword_end(
 7561        &mut self,
 7562        _: &SelectToNextSubwordEnd,
 7563        cx: &mut ViewContext<Self>,
 7564    ) {
 7565        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7566            s.move_heads_with(|map, head, _| {
 7567                (movement::next_subword_end(map, head), SelectionGoal::None)
 7568            });
 7569        })
 7570    }
 7571
 7572    pub fn delete_to_next_word_end(
 7573        &mut self,
 7574        action: &DeleteToNextWordEnd,
 7575        cx: &mut ViewContext<Self>,
 7576    ) {
 7577        self.transact(cx, |this, cx| {
 7578            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7579                let line_mode = s.line_mode;
 7580                s.move_with(|map, selection| {
 7581                    if selection.is_empty() && !line_mode {
 7582                        let cursor = if action.ignore_newlines {
 7583                            movement::next_word_end(map, selection.head())
 7584                        } else {
 7585                            movement::next_word_end_or_newline(map, selection.head())
 7586                        };
 7587                        selection.set_head(cursor, SelectionGoal::None);
 7588                    }
 7589                });
 7590            });
 7591            this.insert("", cx);
 7592        });
 7593    }
 7594
 7595    pub fn delete_to_next_subword_end(
 7596        &mut self,
 7597        _: &DeleteToNextSubwordEnd,
 7598        cx: &mut ViewContext<Self>,
 7599    ) {
 7600        self.transact(cx, |this, cx| {
 7601            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7602                s.move_with(|map, selection| {
 7603                    if selection.is_empty() {
 7604                        let cursor = movement::next_subword_end(map, selection.head());
 7605                        selection.set_head(cursor, SelectionGoal::None);
 7606                    }
 7607                });
 7608            });
 7609            this.insert("", cx);
 7610        });
 7611    }
 7612
 7613    pub fn move_to_beginning_of_line(
 7614        &mut self,
 7615        action: &MoveToBeginningOfLine,
 7616        cx: &mut ViewContext<Self>,
 7617    ) {
 7618        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7619            s.move_cursors_with(|map, head, _| {
 7620                (
 7621                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7622                    SelectionGoal::None,
 7623                )
 7624            });
 7625        })
 7626    }
 7627
 7628    pub fn select_to_beginning_of_line(
 7629        &mut self,
 7630        action: &SelectToBeginningOfLine,
 7631        cx: &mut ViewContext<Self>,
 7632    ) {
 7633        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7634            s.move_heads_with(|map, head, _| {
 7635                (
 7636                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7637                    SelectionGoal::None,
 7638                )
 7639            });
 7640        });
 7641    }
 7642
 7643    pub fn delete_to_beginning_of_line(
 7644        &mut self,
 7645        _: &DeleteToBeginningOfLine,
 7646        cx: &mut ViewContext<Self>,
 7647    ) {
 7648        self.transact(cx, |this, cx| {
 7649            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7650                s.move_with(|_, selection| {
 7651                    selection.reversed = true;
 7652                });
 7653            });
 7654
 7655            this.select_to_beginning_of_line(
 7656                &SelectToBeginningOfLine {
 7657                    stop_at_soft_wraps: false,
 7658                },
 7659                cx,
 7660            );
 7661            this.backspace(&Backspace, cx);
 7662        });
 7663    }
 7664
 7665    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7666        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7667            s.move_cursors_with(|map, head, _| {
 7668                (
 7669                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7670                    SelectionGoal::None,
 7671                )
 7672            });
 7673        })
 7674    }
 7675
 7676    pub fn select_to_end_of_line(
 7677        &mut self,
 7678        action: &SelectToEndOfLine,
 7679        cx: &mut ViewContext<Self>,
 7680    ) {
 7681        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7682            s.move_heads_with(|map, head, _| {
 7683                (
 7684                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7685                    SelectionGoal::None,
 7686                )
 7687            });
 7688        })
 7689    }
 7690
 7691    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7692        self.transact(cx, |this, cx| {
 7693            this.select_to_end_of_line(
 7694                &SelectToEndOfLine {
 7695                    stop_at_soft_wraps: false,
 7696                },
 7697                cx,
 7698            );
 7699            this.delete(&Delete, cx);
 7700        });
 7701    }
 7702
 7703    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7704        self.transact(cx, |this, cx| {
 7705            this.select_to_end_of_line(
 7706                &SelectToEndOfLine {
 7707                    stop_at_soft_wraps: false,
 7708                },
 7709                cx,
 7710            );
 7711            this.cut(&Cut, cx);
 7712        });
 7713    }
 7714
 7715    pub fn move_to_start_of_paragraph(
 7716        &mut self,
 7717        _: &MoveToStartOfParagraph,
 7718        cx: &mut ViewContext<Self>,
 7719    ) {
 7720        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7721            cx.propagate();
 7722            return;
 7723        }
 7724
 7725        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7726            s.move_with(|map, selection| {
 7727                selection.collapse_to(
 7728                    movement::start_of_paragraph(map, selection.head(), 1),
 7729                    SelectionGoal::None,
 7730                )
 7731            });
 7732        })
 7733    }
 7734
 7735    pub fn move_to_end_of_paragraph(
 7736        &mut self,
 7737        _: &MoveToEndOfParagraph,
 7738        cx: &mut ViewContext<Self>,
 7739    ) {
 7740        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7741            cx.propagate();
 7742            return;
 7743        }
 7744
 7745        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7746            s.move_with(|map, selection| {
 7747                selection.collapse_to(
 7748                    movement::end_of_paragraph(map, selection.head(), 1),
 7749                    SelectionGoal::None,
 7750                )
 7751            });
 7752        })
 7753    }
 7754
 7755    pub fn select_to_start_of_paragraph(
 7756        &mut self,
 7757        _: &SelectToStartOfParagraph,
 7758        cx: &mut ViewContext<Self>,
 7759    ) {
 7760        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7761            cx.propagate();
 7762            return;
 7763        }
 7764
 7765        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7766            s.move_heads_with(|map, head, _| {
 7767                (
 7768                    movement::start_of_paragraph(map, head, 1),
 7769                    SelectionGoal::None,
 7770                )
 7771            });
 7772        })
 7773    }
 7774
 7775    pub fn select_to_end_of_paragraph(
 7776        &mut self,
 7777        _: &SelectToEndOfParagraph,
 7778        cx: &mut ViewContext<Self>,
 7779    ) {
 7780        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7781            cx.propagate();
 7782            return;
 7783        }
 7784
 7785        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7786            s.move_heads_with(|map, head, _| {
 7787                (
 7788                    movement::end_of_paragraph(map, head, 1),
 7789                    SelectionGoal::None,
 7790                )
 7791            });
 7792        })
 7793    }
 7794
 7795    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7796        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7797            cx.propagate();
 7798            return;
 7799        }
 7800
 7801        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7802            s.select_ranges(vec![0..0]);
 7803        });
 7804    }
 7805
 7806    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7807        let mut selection = self.selections.last::<Point>(cx);
 7808        selection.set_head(Point::zero(), SelectionGoal::None);
 7809
 7810        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7811            s.select(vec![selection]);
 7812        });
 7813    }
 7814
 7815    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7816        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7817            cx.propagate();
 7818            return;
 7819        }
 7820
 7821        let cursor = self.buffer.read(cx).read(cx).len();
 7822        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7823            s.select_ranges(vec![cursor..cursor])
 7824        });
 7825    }
 7826
 7827    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7828        self.nav_history = nav_history;
 7829    }
 7830
 7831    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7832        self.nav_history.as_ref()
 7833    }
 7834
 7835    fn push_to_nav_history(
 7836        &mut self,
 7837        cursor_anchor: Anchor,
 7838        new_position: Option<Point>,
 7839        cx: &mut ViewContext<Self>,
 7840    ) {
 7841        if let Some(nav_history) = self.nav_history.as_mut() {
 7842            let buffer = self.buffer.read(cx).read(cx);
 7843            let cursor_position = cursor_anchor.to_point(&buffer);
 7844            let scroll_state = self.scroll_manager.anchor();
 7845            let scroll_top_row = scroll_state.top_row(&buffer);
 7846            drop(buffer);
 7847
 7848            if let Some(new_position) = new_position {
 7849                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7850                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7851                    return;
 7852                }
 7853            }
 7854
 7855            nav_history.push(
 7856                Some(NavigationData {
 7857                    cursor_anchor,
 7858                    cursor_position,
 7859                    scroll_anchor: scroll_state,
 7860                    scroll_top_row,
 7861                }),
 7862                cx,
 7863            );
 7864        }
 7865    }
 7866
 7867    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7868        let buffer = self.buffer.read(cx).snapshot(cx);
 7869        let mut selection = self.selections.first::<usize>(cx);
 7870        selection.set_head(buffer.len(), SelectionGoal::None);
 7871        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7872            s.select(vec![selection]);
 7873        });
 7874    }
 7875
 7876    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7877        let end = self.buffer.read(cx).read(cx).len();
 7878        self.change_selections(None, cx, |s| {
 7879            s.select_ranges(vec![0..end]);
 7880        });
 7881    }
 7882
 7883    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7884        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7885        let mut selections = self.selections.all::<Point>(cx);
 7886        let max_point = display_map.buffer_snapshot.max_point();
 7887        for selection in &mut selections {
 7888            let rows = selection.spanned_rows(true, &display_map);
 7889            selection.start = Point::new(rows.start.0, 0);
 7890            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7891            selection.reversed = false;
 7892        }
 7893        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7894            s.select(selections);
 7895        });
 7896    }
 7897
 7898    pub fn split_selection_into_lines(
 7899        &mut self,
 7900        _: &SplitSelectionIntoLines,
 7901        cx: &mut ViewContext<Self>,
 7902    ) {
 7903        let mut to_unfold = Vec::new();
 7904        let mut new_selection_ranges = Vec::new();
 7905        {
 7906            let selections = self.selections.all::<Point>(cx);
 7907            let buffer = self.buffer.read(cx).read(cx);
 7908            for selection in selections {
 7909                for row in selection.start.row..selection.end.row {
 7910                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7911                    new_selection_ranges.push(cursor..cursor);
 7912                }
 7913                new_selection_ranges.push(selection.end..selection.end);
 7914                to_unfold.push(selection.start..selection.end);
 7915            }
 7916        }
 7917        self.unfold_ranges(&to_unfold, true, true, cx);
 7918        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7919            s.select_ranges(new_selection_ranges);
 7920        });
 7921    }
 7922
 7923    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7924        self.add_selection(true, cx);
 7925    }
 7926
 7927    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7928        self.add_selection(false, cx);
 7929    }
 7930
 7931    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7932        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7933        let mut selections = self.selections.all::<Point>(cx);
 7934        let text_layout_details = self.text_layout_details(cx);
 7935        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7936            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7937            let range = oldest_selection.display_range(&display_map).sorted();
 7938
 7939            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7940            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7941            let positions = start_x.min(end_x)..start_x.max(end_x);
 7942
 7943            selections.clear();
 7944            let mut stack = Vec::new();
 7945            for row in range.start.row().0..=range.end.row().0 {
 7946                if let Some(selection) = self.selections.build_columnar_selection(
 7947                    &display_map,
 7948                    DisplayRow(row),
 7949                    &positions,
 7950                    oldest_selection.reversed,
 7951                    &text_layout_details,
 7952                ) {
 7953                    stack.push(selection.id);
 7954                    selections.push(selection);
 7955                }
 7956            }
 7957
 7958            if above {
 7959                stack.reverse();
 7960            }
 7961
 7962            AddSelectionsState { above, stack }
 7963        });
 7964
 7965        let last_added_selection = *state.stack.last().unwrap();
 7966        let mut new_selections = Vec::new();
 7967        if above == state.above {
 7968            let end_row = if above {
 7969                DisplayRow(0)
 7970            } else {
 7971                display_map.max_point().row()
 7972            };
 7973
 7974            'outer: for selection in selections {
 7975                if selection.id == last_added_selection {
 7976                    let range = selection.display_range(&display_map).sorted();
 7977                    debug_assert_eq!(range.start.row(), range.end.row());
 7978                    let mut row = range.start.row();
 7979                    let positions =
 7980                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7981                            px(start)..px(end)
 7982                        } else {
 7983                            let start_x =
 7984                                display_map.x_for_display_point(range.start, &text_layout_details);
 7985                            let end_x =
 7986                                display_map.x_for_display_point(range.end, &text_layout_details);
 7987                            start_x.min(end_x)..start_x.max(end_x)
 7988                        };
 7989
 7990                    while row != end_row {
 7991                        if above {
 7992                            row.0 -= 1;
 7993                        } else {
 7994                            row.0 += 1;
 7995                        }
 7996
 7997                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7998                            &display_map,
 7999                            row,
 8000                            &positions,
 8001                            selection.reversed,
 8002                            &text_layout_details,
 8003                        ) {
 8004                            state.stack.push(new_selection.id);
 8005                            if above {
 8006                                new_selections.push(new_selection);
 8007                                new_selections.push(selection);
 8008                            } else {
 8009                                new_selections.push(selection);
 8010                                new_selections.push(new_selection);
 8011                            }
 8012
 8013                            continue 'outer;
 8014                        }
 8015                    }
 8016                }
 8017
 8018                new_selections.push(selection);
 8019            }
 8020        } else {
 8021            new_selections = selections;
 8022            new_selections.retain(|s| s.id != last_added_selection);
 8023            state.stack.pop();
 8024        }
 8025
 8026        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8027            s.select(new_selections);
 8028        });
 8029        if state.stack.len() > 1 {
 8030            self.add_selections_state = Some(state);
 8031        }
 8032    }
 8033
 8034    pub fn select_next_match_internal(
 8035        &mut self,
 8036        display_map: &DisplaySnapshot,
 8037        replace_newest: bool,
 8038        autoscroll: Option<Autoscroll>,
 8039        cx: &mut ViewContext<Self>,
 8040    ) -> Result<()> {
 8041        fn select_next_match_ranges(
 8042            this: &mut Editor,
 8043            range: Range<usize>,
 8044            replace_newest: bool,
 8045            auto_scroll: Option<Autoscroll>,
 8046            cx: &mut ViewContext<Editor>,
 8047        ) {
 8048            this.unfold_ranges(&[range.clone()], false, true, cx);
 8049            this.change_selections(auto_scroll, cx, |s| {
 8050                if replace_newest {
 8051                    s.delete(s.newest_anchor().id);
 8052                }
 8053                s.insert_range(range.clone());
 8054            });
 8055        }
 8056
 8057        let buffer = &display_map.buffer_snapshot;
 8058        let mut selections = self.selections.all::<usize>(cx);
 8059        if let Some(mut select_next_state) = self.select_next_state.take() {
 8060            let query = &select_next_state.query;
 8061            if !select_next_state.done {
 8062                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8063                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8064                let mut next_selected_range = None;
 8065
 8066                let bytes_after_last_selection =
 8067                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8068                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8069                let query_matches = query
 8070                    .stream_find_iter(bytes_after_last_selection)
 8071                    .map(|result| (last_selection.end, result))
 8072                    .chain(
 8073                        query
 8074                            .stream_find_iter(bytes_before_first_selection)
 8075                            .map(|result| (0, result)),
 8076                    );
 8077
 8078                for (start_offset, query_match) in query_matches {
 8079                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8080                    let offset_range =
 8081                        start_offset + query_match.start()..start_offset + query_match.end();
 8082                    let display_range = offset_range.start.to_display_point(display_map)
 8083                        ..offset_range.end.to_display_point(display_map);
 8084
 8085                    if !select_next_state.wordwise
 8086                        || (!movement::is_inside_word(display_map, display_range.start)
 8087                            && !movement::is_inside_word(display_map, display_range.end))
 8088                    {
 8089                        // TODO: This is n^2, because we might check all the selections
 8090                        if !selections
 8091                            .iter()
 8092                            .any(|selection| selection.range().overlaps(&offset_range))
 8093                        {
 8094                            next_selected_range = Some(offset_range);
 8095                            break;
 8096                        }
 8097                    }
 8098                }
 8099
 8100                if let Some(next_selected_range) = next_selected_range {
 8101                    select_next_match_ranges(
 8102                        self,
 8103                        next_selected_range,
 8104                        replace_newest,
 8105                        autoscroll,
 8106                        cx,
 8107                    );
 8108                } else {
 8109                    select_next_state.done = true;
 8110                }
 8111            }
 8112
 8113            self.select_next_state = Some(select_next_state);
 8114        } else {
 8115            let mut only_carets = true;
 8116            let mut same_text_selected = true;
 8117            let mut selected_text = None;
 8118
 8119            let mut selections_iter = selections.iter().peekable();
 8120            while let Some(selection) = selections_iter.next() {
 8121                if selection.start != selection.end {
 8122                    only_carets = false;
 8123                }
 8124
 8125                if same_text_selected {
 8126                    if selected_text.is_none() {
 8127                        selected_text =
 8128                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8129                    }
 8130
 8131                    if let Some(next_selection) = selections_iter.peek() {
 8132                        if next_selection.range().len() == selection.range().len() {
 8133                            let next_selected_text = buffer
 8134                                .text_for_range(next_selection.range())
 8135                                .collect::<String>();
 8136                            if Some(next_selected_text) != selected_text {
 8137                                same_text_selected = false;
 8138                                selected_text = None;
 8139                            }
 8140                        } else {
 8141                            same_text_selected = false;
 8142                            selected_text = None;
 8143                        }
 8144                    }
 8145                }
 8146            }
 8147
 8148            if only_carets {
 8149                for selection in &mut selections {
 8150                    let word_range = movement::surrounding_word(
 8151                        display_map,
 8152                        selection.start.to_display_point(display_map),
 8153                    );
 8154                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8155                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8156                    selection.goal = SelectionGoal::None;
 8157                    selection.reversed = false;
 8158                    select_next_match_ranges(
 8159                        self,
 8160                        selection.start..selection.end,
 8161                        replace_newest,
 8162                        autoscroll,
 8163                        cx,
 8164                    );
 8165                }
 8166
 8167                if selections.len() == 1 {
 8168                    let selection = selections
 8169                        .last()
 8170                        .expect("ensured that there's only one selection");
 8171                    let query = buffer
 8172                        .text_for_range(selection.start..selection.end)
 8173                        .collect::<String>();
 8174                    let is_empty = query.is_empty();
 8175                    let select_state = SelectNextState {
 8176                        query: AhoCorasick::new(&[query])?,
 8177                        wordwise: true,
 8178                        done: is_empty,
 8179                    };
 8180                    self.select_next_state = Some(select_state);
 8181                } else {
 8182                    self.select_next_state = None;
 8183                }
 8184            } else if let Some(selected_text) = selected_text {
 8185                self.select_next_state = Some(SelectNextState {
 8186                    query: AhoCorasick::new(&[selected_text])?,
 8187                    wordwise: false,
 8188                    done: false,
 8189                });
 8190                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8191            }
 8192        }
 8193        Ok(())
 8194    }
 8195
 8196    pub fn select_all_matches(
 8197        &mut self,
 8198        _action: &SelectAllMatches,
 8199        cx: &mut ViewContext<Self>,
 8200    ) -> Result<()> {
 8201        self.push_to_selection_history();
 8202        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8203
 8204        self.select_next_match_internal(&display_map, false, None, cx)?;
 8205        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8206            return Ok(());
 8207        };
 8208        if select_next_state.done {
 8209            return Ok(());
 8210        }
 8211
 8212        let mut new_selections = self.selections.all::<usize>(cx);
 8213
 8214        let buffer = &display_map.buffer_snapshot;
 8215        let query_matches = select_next_state
 8216            .query
 8217            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8218
 8219        for query_match in query_matches {
 8220            let query_match = query_match.unwrap(); // can only fail due to I/O
 8221            let offset_range = query_match.start()..query_match.end();
 8222            let display_range = offset_range.start.to_display_point(&display_map)
 8223                ..offset_range.end.to_display_point(&display_map);
 8224
 8225            if !select_next_state.wordwise
 8226                || (!movement::is_inside_word(&display_map, display_range.start)
 8227                    && !movement::is_inside_word(&display_map, display_range.end))
 8228            {
 8229                self.selections.change_with(cx, |selections| {
 8230                    new_selections.push(Selection {
 8231                        id: selections.new_selection_id(),
 8232                        start: offset_range.start,
 8233                        end: offset_range.end,
 8234                        reversed: false,
 8235                        goal: SelectionGoal::None,
 8236                    });
 8237                });
 8238            }
 8239        }
 8240
 8241        new_selections.sort_by_key(|selection| selection.start);
 8242        let mut ix = 0;
 8243        while ix + 1 < new_selections.len() {
 8244            let current_selection = &new_selections[ix];
 8245            let next_selection = &new_selections[ix + 1];
 8246            if current_selection.range().overlaps(&next_selection.range()) {
 8247                if current_selection.id < next_selection.id {
 8248                    new_selections.remove(ix + 1);
 8249                } else {
 8250                    new_selections.remove(ix);
 8251                }
 8252            } else {
 8253                ix += 1;
 8254            }
 8255        }
 8256
 8257        select_next_state.done = true;
 8258        self.unfold_ranges(
 8259            &new_selections
 8260                .iter()
 8261                .map(|selection| selection.range())
 8262                .collect::<Vec<_>>(),
 8263            false,
 8264            false,
 8265            cx,
 8266        );
 8267        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8268            selections.select(new_selections)
 8269        });
 8270
 8271        Ok(())
 8272    }
 8273
 8274    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8275        self.push_to_selection_history();
 8276        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8277        self.select_next_match_internal(
 8278            &display_map,
 8279            action.replace_newest,
 8280            Some(Autoscroll::newest()),
 8281            cx,
 8282        )?;
 8283        Ok(())
 8284    }
 8285
 8286    pub fn select_previous(
 8287        &mut self,
 8288        action: &SelectPrevious,
 8289        cx: &mut ViewContext<Self>,
 8290    ) -> Result<()> {
 8291        self.push_to_selection_history();
 8292        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8293        let buffer = &display_map.buffer_snapshot;
 8294        let mut selections = self.selections.all::<usize>(cx);
 8295        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8296            let query = &select_prev_state.query;
 8297            if !select_prev_state.done {
 8298                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8299                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8300                let mut next_selected_range = None;
 8301                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8302                let bytes_before_last_selection =
 8303                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8304                let bytes_after_first_selection =
 8305                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8306                let query_matches = query
 8307                    .stream_find_iter(bytes_before_last_selection)
 8308                    .map(|result| (last_selection.start, result))
 8309                    .chain(
 8310                        query
 8311                            .stream_find_iter(bytes_after_first_selection)
 8312                            .map(|result| (buffer.len(), result)),
 8313                    );
 8314                for (end_offset, query_match) in query_matches {
 8315                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8316                    let offset_range =
 8317                        end_offset - query_match.end()..end_offset - query_match.start();
 8318                    let display_range = offset_range.start.to_display_point(&display_map)
 8319                        ..offset_range.end.to_display_point(&display_map);
 8320
 8321                    if !select_prev_state.wordwise
 8322                        || (!movement::is_inside_word(&display_map, display_range.start)
 8323                            && !movement::is_inside_word(&display_map, display_range.end))
 8324                    {
 8325                        next_selected_range = Some(offset_range);
 8326                        break;
 8327                    }
 8328                }
 8329
 8330                if let Some(next_selected_range) = next_selected_range {
 8331                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8332                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8333                        if action.replace_newest {
 8334                            s.delete(s.newest_anchor().id);
 8335                        }
 8336                        s.insert_range(next_selected_range);
 8337                    });
 8338                } else {
 8339                    select_prev_state.done = true;
 8340                }
 8341            }
 8342
 8343            self.select_prev_state = Some(select_prev_state);
 8344        } else {
 8345            let mut only_carets = true;
 8346            let mut same_text_selected = true;
 8347            let mut selected_text = None;
 8348
 8349            let mut selections_iter = selections.iter().peekable();
 8350            while let Some(selection) = selections_iter.next() {
 8351                if selection.start != selection.end {
 8352                    only_carets = false;
 8353                }
 8354
 8355                if same_text_selected {
 8356                    if selected_text.is_none() {
 8357                        selected_text =
 8358                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8359                    }
 8360
 8361                    if let Some(next_selection) = selections_iter.peek() {
 8362                        if next_selection.range().len() == selection.range().len() {
 8363                            let next_selected_text = buffer
 8364                                .text_for_range(next_selection.range())
 8365                                .collect::<String>();
 8366                            if Some(next_selected_text) != selected_text {
 8367                                same_text_selected = false;
 8368                                selected_text = None;
 8369                            }
 8370                        } else {
 8371                            same_text_selected = false;
 8372                            selected_text = None;
 8373                        }
 8374                    }
 8375                }
 8376            }
 8377
 8378            if only_carets {
 8379                for selection in &mut selections {
 8380                    let word_range = movement::surrounding_word(
 8381                        &display_map,
 8382                        selection.start.to_display_point(&display_map),
 8383                    );
 8384                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8385                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8386                    selection.goal = SelectionGoal::None;
 8387                    selection.reversed = false;
 8388                }
 8389                if selections.len() == 1 {
 8390                    let selection = selections
 8391                        .last()
 8392                        .expect("ensured that there's only one selection");
 8393                    let query = buffer
 8394                        .text_for_range(selection.start..selection.end)
 8395                        .collect::<String>();
 8396                    let is_empty = query.is_empty();
 8397                    let select_state = SelectNextState {
 8398                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8399                        wordwise: true,
 8400                        done: is_empty,
 8401                    };
 8402                    self.select_prev_state = Some(select_state);
 8403                } else {
 8404                    self.select_prev_state = None;
 8405                }
 8406
 8407                self.unfold_ranges(
 8408                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8409                    false,
 8410                    true,
 8411                    cx,
 8412                );
 8413                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8414                    s.select(selections);
 8415                });
 8416            } else if let Some(selected_text) = selected_text {
 8417                self.select_prev_state = Some(SelectNextState {
 8418                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8419                    wordwise: false,
 8420                    done: false,
 8421                });
 8422                self.select_previous(action, cx)?;
 8423            }
 8424        }
 8425        Ok(())
 8426    }
 8427
 8428    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8429        if self.read_only(cx) {
 8430            return;
 8431        }
 8432        let text_layout_details = &self.text_layout_details(cx);
 8433        self.transact(cx, |this, cx| {
 8434            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8435            let mut edits = Vec::new();
 8436            let mut selection_edit_ranges = Vec::new();
 8437            let mut last_toggled_row = None;
 8438            let snapshot = this.buffer.read(cx).read(cx);
 8439            let empty_str: Arc<str> = Arc::default();
 8440            let mut suffixes_inserted = Vec::new();
 8441            let ignore_indent = action.ignore_indent;
 8442
 8443            fn comment_prefix_range(
 8444                snapshot: &MultiBufferSnapshot,
 8445                row: MultiBufferRow,
 8446                comment_prefix: &str,
 8447                comment_prefix_whitespace: &str,
 8448                ignore_indent: bool,
 8449            ) -> Range<Point> {
 8450                let indent_size = if ignore_indent {
 8451                    0
 8452                } else {
 8453                    snapshot.indent_size_for_line(row).len
 8454                };
 8455
 8456                let start = Point::new(row.0, indent_size);
 8457
 8458                let mut line_bytes = snapshot
 8459                    .bytes_in_range(start..snapshot.max_point())
 8460                    .flatten()
 8461                    .copied();
 8462
 8463                // If this line currently begins with the line comment prefix, then record
 8464                // the range containing the prefix.
 8465                if line_bytes
 8466                    .by_ref()
 8467                    .take(comment_prefix.len())
 8468                    .eq(comment_prefix.bytes())
 8469                {
 8470                    // Include any whitespace that matches the comment prefix.
 8471                    let matching_whitespace_len = line_bytes
 8472                        .zip(comment_prefix_whitespace.bytes())
 8473                        .take_while(|(a, b)| a == b)
 8474                        .count() as u32;
 8475                    let end = Point::new(
 8476                        start.row,
 8477                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8478                    );
 8479                    start..end
 8480                } else {
 8481                    start..start
 8482                }
 8483            }
 8484
 8485            fn comment_suffix_range(
 8486                snapshot: &MultiBufferSnapshot,
 8487                row: MultiBufferRow,
 8488                comment_suffix: &str,
 8489                comment_suffix_has_leading_space: bool,
 8490            ) -> Range<Point> {
 8491                let end = Point::new(row.0, snapshot.line_len(row));
 8492                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8493
 8494                let mut line_end_bytes = snapshot
 8495                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8496                    .flatten()
 8497                    .copied();
 8498
 8499                let leading_space_len = if suffix_start_column > 0
 8500                    && line_end_bytes.next() == Some(b' ')
 8501                    && comment_suffix_has_leading_space
 8502                {
 8503                    1
 8504                } else {
 8505                    0
 8506                };
 8507
 8508                // If this line currently begins with the line comment prefix, then record
 8509                // the range containing the prefix.
 8510                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8511                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8512                    start..end
 8513                } else {
 8514                    end..end
 8515                }
 8516            }
 8517
 8518            // TODO: Handle selections that cross excerpts
 8519            for selection in &mut selections {
 8520                let start_column = snapshot
 8521                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8522                    .len;
 8523                let language = if let Some(language) =
 8524                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8525                {
 8526                    language
 8527                } else {
 8528                    continue;
 8529                };
 8530
 8531                selection_edit_ranges.clear();
 8532
 8533                // If multiple selections contain a given row, avoid processing that
 8534                // row more than once.
 8535                let mut start_row = MultiBufferRow(selection.start.row);
 8536                if last_toggled_row == Some(start_row) {
 8537                    start_row = start_row.next_row();
 8538                }
 8539                let end_row =
 8540                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8541                        MultiBufferRow(selection.end.row - 1)
 8542                    } else {
 8543                        MultiBufferRow(selection.end.row)
 8544                    };
 8545                last_toggled_row = Some(end_row);
 8546
 8547                if start_row > end_row {
 8548                    continue;
 8549                }
 8550
 8551                // If the language has line comments, toggle those.
 8552                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8553
 8554                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8555                if ignore_indent {
 8556                    full_comment_prefixes = full_comment_prefixes
 8557                        .into_iter()
 8558                        .map(|s| Arc::from(s.trim_end()))
 8559                        .collect();
 8560                }
 8561
 8562                if !full_comment_prefixes.is_empty() {
 8563                    let first_prefix = full_comment_prefixes
 8564                        .first()
 8565                        .expect("prefixes is non-empty");
 8566                    let prefix_trimmed_lengths = full_comment_prefixes
 8567                        .iter()
 8568                        .map(|p| p.trim_end_matches(' ').len())
 8569                        .collect::<SmallVec<[usize; 4]>>();
 8570
 8571                    let mut all_selection_lines_are_comments = true;
 8572
 8573                    for row in start_row.0..=end_row.0 {
 8574                        let row = MultiBufferRow(row);
 8575                        if start_row < end_row && snapshot.is_line_blank(row) {
 8576                            continue;
 8577                        }
 8578
 8579                        let prefix_range = full_comment_prefixes
 8580                            .iter()
 8581                            .zip(prefix_trimmed_lengths.iter().copied())
 8582                            .map(|(prefix, trimmed_prefix_len)| {
 8583                                comment_prefix_range(
 8584                                    snapshot.deref(),
 8585                                    row,
 8586                                    &prefix[..trimmed_prefix_len],
 8587                                    &prefix[trimmed_prefix_len..],
 8588                                    ignore_indent,
 8589                                )
 8590                            })
 8591                            .max_by_key(|range| range.end.column - range.start.column)
 8592                            .expect("prefixes is non-empty");
 8593
 8594                        if prefix_range.is_empty() {
 8595                            all_selection_lines_are_comments = false;
 8596                        }
 8597
 8598                        selection_edit_ranges.push(prefix_range);
 8599                    }
 8600
 8601                    if all_selection_lines_are_comments {
 8602                        edits.extend(
 8603                            selection_edit_ranges
 8604                                .iter()
 8605                                .cloned()
 8606                                .map(|range| (range, empty_str.clone())),
 8607                        );
 8608                    } else {
 8609                        let min_column = selection_edit_ranges
 8610                            .iter()
 8611                            .map(|range| range.start.column)
 8612                            .min()
 8613                            .unwrap_or(0);
 8614                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8615                            let position = Point::new(range.start.row, min_column);
 8616                            (position..position, first_prefix.clone())
 8617                        }));
 8618                    }
 8619                } else if let Some((full_comment_prefix, comment_suffix)) =
 8620                    language.block_comment_delimiters()
 8621                {
 8622                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8623                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8624                    let prefix_range = comment_prefix_range(
 8625                        snapshot.deref(),
 8626                        start_row,
 8627                        comment_prefix,
 8628                        comment_prefix_whitespace,
 8629                        ignore_indent,
 8630                    );
 8631                    let suffix_range = comment_suffix_range(
 8632                        snapshot.deref(),
 8633                        end_row,
 8634                        comment_suffix.trim_start_matches(' '),
 8635                        comment_suffix.starts_with(' '),
 8636                    );
 8637
 8638                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8639                        edits.push((
 8640                            prefix_range.start..prefix_range.start,
 8641                            full_comment_prefix.clone(),
 8642                        ));
 8643                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8644                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8645                    } else {
 8646                        edits.push((prefix_range, empty_str.clone()));
 8647                        edits.push((suffix_range, empty_str.clone()));
 8648                    }
 8649                } else {
 8650                    continue;
 8651                }
 8652            }
 8653
 8654            drop(snapshot);
 8655            this.buffer.update(cx, |buffer, cx| {
 8656                buffer.edit(edits, None, cx);
 8657            });
 8658
 8659            // Adjust selections so that they end before any comment suffixes that
 8660            // were inserted.
 8661            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8662            let mut selections = this.selections.all::<Point>(cx);
 8663            let snapshot = this.buffer.read(cx).read(cx);
 8664            for selection in &mut selections {
 8665                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8666                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8667                        Ordering::Less => {
 8668                            suffixes_inserted.next();
 8669                            continue;
 8670                        }
 8671                        Ordering::Greater => break,
 8672                        Ordering::Equal => {
 8673                            if selection.end.column == snapshot.line_len(row) {
 8674                                if selection.is_empty() {
 8675                                    selection.start.column -= suffix_len as u32;
 8676                                }
 8677                                selection.end.column -= suffix_len as u32;
 8678                            }
 8679                            break;
 8680                        }
 8681                    }
 8682                }
 8683            }
 8684
 8685            drop(snapshot);
 8686            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8687
 8688            let selections = this.selections.all::<Point>(cx);
 8689            let selections_on_single_row = selections.windows(2).all(|selections| {
 8690                selections[0].start.row == selections[1].start.row
 8691                    && selections[0].end.row == selections[1].end.row
 8692                    && selections[0].start.row == selections[0].end.row
 8693            });
 8694            let selections_selecting = selections
 8695                .iter()
 8696                .any(|selection| selection.start != selection.end);
 8697            let advance_downwards = action.advance_downwards
 8698                && selections_on_single_row
 8699                && !selections_selecting
 8700                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8701
 8702            if advance_downwards {
 8703                let snapshot = this.buffer.read(cx).snapshot(cx);
 8704
 8705                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8706                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8707                        let mut point = display_point.to_point(display_snapshot);
 8708                        point.row += 1;
 8709                        point = snapshot.clip_point(point, Bias::Left);
 8710                        let display_point = point.to_display_point(display_snapshot);
 8711                        let goal = SelectionGoal::HorizontalPosition(
 8712                            display_snapshot
 8713                                .x_for_display_point(display_point, text_layout_details)
 8714                                .into(),
 8715                        );
 8716                        (display_point, goal)
 8717                    })
 8718                });
 8719            }
 8720        });
 8721    }
 8722
 8723    pub fn select_enclosing_symbol(
 8724        &mut self,
 8725        _: &SelectEnclosingSymbol,
 8726        cx: &mut ViewContext<Self>,
 8727    ) {
 8728        let buffer = self.buffer.read(cx).snapshot(cx);
 8729        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8730
 8731        fn update_selection(
 8732            selection: &Selection<usize>,
 8733            buffer_snap: &MultiBufferSnapshot,
 8734        ) -> Option<Selection<usize>> {
 8735            let cursor = selection.head();
 8736            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8737            for symbol in symbols.iter().rev() {
 8738                let start = symbol.range.start.to_offset(buffer_snap);
 8739                let end = symbol.range.end.to_offset(buffer_snap);
 8740                let new_range = start..end;
 8741                if start < selection.start || end > selection.end {
 8742                    return Some(Selection {
 8743                        id: selection.id,
 8744                        start: new_range.start,
 8745                        end: new_range.end,
 8746                        goal: SelectionGoal::None,
 8747                        reversed: selection.reversed,
 8748                    });
 8749                }
 8750            }
 8751            None
 8752        }
 8753
 8754        let mut selected_larger_symbol = false;
 8755        let new_selections = old_selections
 8756            .iter()
 8757            .map(|selection| match update_selection(selection, &buffer) {
 8758                Some(new_selection) => {
 8759                    if new_selection.range() != selection.range() {
 8760                        selected_larger_symbol = true;
 8761                    }
 8762                    new_selection
 8763                }
 8764                None => selection.clone(),
 8765            })
 8766            .collect::<Vec<_>>();
 8767
 8768        if selected_larger_symbol {
 8769            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8770                s.select(new_selections);
 8771            });
 8772        }
 8773    }
 8774
 8775    pub fn select_larger_syntax_node(
 8776        &mut self,
 8777        _: &SelectLargerSyntaxNode,
 8778        cx: &mut ViewContext<Self>,
 8779    ) {
 8780        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8781        let buffer = self.buffer.read(cx).snapshot(cx);
 8782        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8783
 8784        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8785        let mut selected_larger_node = false;
 8786        let new_selections = old_selections
 8787            .iter()
 8788            .map(|selection| {
 8789                let old_range = selection.start..selection.end;
 8790                let mut new_range = old_range.clone();
 8791                while let Some(containing_range) =
 8792                    buffer.range_for_syntax_ancestor(new_range.clone())
 8793                {
 8794                    new_range = containing_range;
 8795                    if !display_map.intersects_fold(new_range.start)
 8796                        && !display_map.intersects_fold(new_range.end)
 8797                    {
 8798                        break;
 8799                    }
 8800                }
 8801
 8802                selected_larger_node |= new_range != old_range;
 8803                Selection {
 8804                    id: selection.id,
 8805                    start: new_range.start,
 8806                    end: new_range.end,
 8807                    goal: SelectionGoal::None,
 8808                    reversed: selection.reversed,
 8809                }
 8810            })
 8811            .collect::<Vec<_>>();
 8812
 8813        if selected_larger_node {
 8814            stack.push(old_selections);
 8815            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8816                s.select(new_selections);
 8817            });
 8818        }
 8819        self.select_larger_syntax_node_stack = stack;
 8820    }
 8821
 8822    pub fn select_smaller_syntax_node(
 8823        &mut self,
 8824        _: &SelectSmallerSyntaxNode,
 8825        cx: &mut ViewContext<Self>,
 8826    ) {
 8827        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8828        if let Some(selections) = stack.pop() {
 8829            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8830                s.select(selections.to_vec());
 8831            });
 8832        }
 8833        self.select_larger_syntax_node_stack = stack;
 8834    }
 8835
 8836    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8837        if !EditorSettings::get_global(cx).gutter.runnables {
 8838            self.clear_tasks();
 8839            return Task::ready(());
 8840        }
 8841        let project = self.project.as_ref().map(Model::downgrade);
 8842        cx.spawn(|this, mut cx| async move {
 8843            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8844            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8845                return;
 8846            };
 8847            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8848                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8849            }) else {
 8850                return;
 8851            };
 8852
 8853            let hide_runnables = project
 8854                .update(&mut cx, |project, cx| {
 8855                    // Do not display any test indicators in non-dev server remote projects.
 8856                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8857                })
 8858                .unwrap_or(true);
 8859            if hide_runnables {
 8860                return;
 8861            }
 8862            let new_rows =
 8863                cx.background_executor()
 8864                    .spawn({
 8865                        let snapshot = display_snapshot.clone();
 8866                        async move {
 8867                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8868                        }
 8869                    })
 8870                    .await;
 8871            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8872
 8873            this.update(&mut cx, |this, _| {
 8874                this.clear_tasks();
 8875                for (key, value) in rows {
 8876                    this.insert_tasks(key, value);
 8877                }
 8878            })
 8879            .ok();
 8880        })
 8881    }
 8882    fn fetch_runnable_ranges(
 8883        snapshot: &DisplaySnapshot,
 8884        range: Range<Anchor>,
 8885    ) -> Vec<language::RunnableRange> {
 8886        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8887    }
 8888
 8889    fn runnable_rows(
 8890        project: Model<Project>,
 8891        snapshot: DisplaySnapshot,
 8892        runnable_ranges: Vec<RunnableRange>,
 8893        mut cx: AsyncWindowContext,
 8894    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8895        runnable_ranges
 8896            .into_iter()
 8897            .filter_map(|mut runnable| {
 8898                let tasks = cx
 8899                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8900                    .ok()?;
 8901                if tasks.is_empty() {
 8902                    return None;
 8903                }
 8904
 8905                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8906
 8907                let row = snapshot
 8908                    .buffer_snapshot
 8909                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8910                    .1
 8911                    .start
 8912                    .row;
 8913
 8914                let context_range =
 8915                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8916                Some((
 8917                    (runnable.buffer_id, row),
 8918                    RunnableTasks {
 8919                        templates: tasks,
 8920                        offset: MultiBufferOffset(runnable.run_range.start),
 8921                        context_range,
 8922                        column: point.column,
 8923                        extra_variables: runnable.extra_captures,
 8924                    },
 8925                ))
 8926            })
 8927            .collect()
 8928    }
 8929
 8930    fn templates_with_tags(
 8931        project: &Model<Project>,
 8932        runnable: &mut Runnable,
 8933        cx: &WindowContext<'_>,
 8934    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8935        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8936            let (worktree_id, file) = project
 8937                .buffer_for_id(runnable.buffer, cx)
 8938                .and_then(|buffer| buffer.read(cx).file())
 8939                .map(|file| (file.worktree_id(cx), file.clone()))
 8940                .unzip();
 8941
 8942            (
 8943                project.task_store().read(cx).task_inventory().cloned(),
 8944                worktree_id,
 8945                file,
 8946            )
 8947        });
 8948
 8949        let tags = mem::take(&mut runnable.tags);
 8950        let mut tags: Vec<_> = tags
 8951            .into_iter()
 8952            .flat_map(|tag| {
 8953                let tag = tag.0.clone();
 8954                inventory
 8955                    .as_ref()
 8956                    .into_iter()
 8957                    .flat_map(|inventory| {
 8958                        inventory.read(cx).list_tasks(
 8959                            file.clone(),
 8960                            Some(runnable.language.clone()),
 8961                            worktree_id,
 8962                            cx,
 8963                        )
 8964                    })
 8965                    .filter(move |(_, template)| {
 8966                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8967                    })
 8968            })
 8969            .sorted_by_key(|(kind, _)| kind.to_owned())
 8970            .collect();
 8971        if let Some((leading_tag_source, _)) = tags.first() {
 8972            // Strongest source wins; if we have worktree tag binding, prefer that to
 8973            // global and language bindings;
 8974            // if we have a global binding, prefer that to language binding.
 8975            let first_mismatch = tags
 8976                .iter()
 8977                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8978            if let Some(index) = first_mismatch {
 8979                tags.truncate(index);
 8980            }
 8981        }
 8982
 8983        tags
 8984    }
 8985
 8986    pub fn move_to_enclosing_bracket(
 8987        &mut self,
 8988        _: &MoveToEnclosingBracket,
 8989        cx: &mut ViewContext<Self>,
 8990    ) {
 8991        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8992            s.move_offsets_with(|snapshot, selection| {
 8993                let Some(enclosing_bracket_ranges) =
 8994                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8995                else {
 8996                    return;
 8997                };
 8998
 8999                let mut best_length = usize::MAX;
 9000                let mut best_inside = false;
 9001                let mut best_in_bracket_range = false;
 9002                let mut best_destination = None;
 9003                for (open, close) in enclosing_bracket_ranges {
 9004                    let close = close.to_inclusive();
 9005                    let length = close.end() - open.start;
 9006                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9007                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9008                        || close.contains(&selection.head());
 9009
 9010                    // If best is next to a bracket and current isn't, skip
 9011                    if !in_bracket_range && best_in_bracket_range {
 9012                        continue;
 9013                    }
 9014
 9015                    // Prefer smaller lengths unless best is inside and current isn't
 9016                    if length > best_length && (best_inside || !inside) {
 9017                        continue;
 9018                    }
 9019
 9020                    best_length = length;
 9021                    best_inside = inside;
 9022                    best_in_bracket_range = in_bracket_range;
 9023                    best_destination = Some(
 9024                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9025                            if inside {
 9026                                open.end
 9027                            } else {
 9028                                open.start
 9029                            }
 9030                        } else if inside {
 9031                            *close.start()
 9032                        } else {
 9033                            *close.end()
 9034                        },
 9035                    );
 9036                }
 9037
 9038                if let Some(destination) = best_destination {
 9039                    selection.collapse_to(destination, SelectionGoal::None);
 9040                }
 9041            })
 9042        });
 9043    }
 9044
 9045    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9046        self.end_selection(cx);
 9047        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9048        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9049            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9050            self.select_next_state = entry.select_next_state;
 9051            self.select_prev_state = entry.select_prev_state;
 9052            self.add_selections_state = entry.add_selections_state;
 9053            self.request_autoscroll(Autoscroll::newest(), cx);
 9054        }
 9055        self.selection_history.mode = SelectionHistoryMode::Normal;
 9056    }
 9057
 9058    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9059        self.end_selection(cx);
 9060        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9061        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9062            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9063            self.select_next_state = entry.select_next_state;
 9064            self.select_prev_state = entry.select_prev_state;
 9065            self.add_selections_state = entry.add_selections_state;
 9066            self.request_autoscroll(Autoscroll::newest(), cx);
 9067        }
 9068        self.selection_history.mode = SelectionHistoryMode::Normal;
 9069    }
 9070
 9071    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9072        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9073    }
 9074
 9075    pub fn expand_excerpts_down(
 9076        &mut self,
 9077        action: &ExpandExcerptsDown,
 9078        cx: &mut ViewContext<Self>,
 9079    ) {
 9080        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9081    }
 9082
 9083    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9084        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9085    }
 9086
 9087    pub fn expand_excerpts_for_direction(
 9088        &mut self,
 9089        lines: u32,
 9090        direction: ExpandExcerptDirection,
 9091        cx: &mut ViewContext<Self>,
 9092    ) {
 9093        let selections = self.selections.disjoint_anchors();
 9094
 9095        let lines = if lines == 0 {
 9096            EditorSettings::get_global(cx).expand_excerpt_lines
 9097        } else {
 9098            lines
 9099        };
 9100
 9101        self.buffer.update(cx, |buffer, cx| {
 9102            buffer.expand_excerpts(
 9103                selections
 9104                    .iter()
 9105                    .map(|selection| selection.head().excerpt_id)
 9106                    .dedup(),
 9107                lines,
 9108                direction,
 9109                cx,
 9110            )
 9111        })
 9112    }
 9113
 9114    pub fn expand_excerpt(
 9115        &mut self,
 9116        excerpt: ExcerptId,
 9117        direction: ExpandExcerptDirection,
 9118        cx: &mut ViewContext<Self>,
 9119    ) {
 9120        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9121        self.buffer.update(cx, |buffer, cx| {
 9122            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9123        })
 9124    }
 9125
 9126    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9127        self.go_to_diagnostic_impl(Direction::Next, cx)
 9128    }
 9129
 9130    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9131        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9132    }
 9133
 9134    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9135        let buffer = self.buffer.read(cx).snapshot(cx);
 9136        let selection = self.selections.newest::<usize>(cx);
 9137
 9138        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9139        if direction == Direction::Next {
 9140            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9141                let (group_id, jump_to) = popover.activation_info();
 9142                if self.activate_diagnostics(group_id, cx) {
 9143                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9144                        let mut new_selection = s.newest_anchor().clone();
 9145                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9146                        s.select_anchors(vec![new_selection.clone()]);
 9147                    });
 9148                }
 9149                return;
 9150            }
 9151        }
 9152
 9153        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9154            active_diagnostics
 9155                .primary_range
 9156                .to_offset(&buffer)
 9157                .to_inclusive()
 9158        });
 9159        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9160            if active_primary_range.contains(&selection.head()) {
 9161                *active_primary_range.start()
 9162            } else {
 9163                selection.head()
 9164            }
 9165        } else {
 9166            selection.head()
 9167        };
 9168        let snapshot = self.snapshot(cx);
 9169        loop {
 9170            let diagnostics = if direction == Direction::Prev {
 9171                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9172            } else {
 9173                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9174            }
 9175            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9176            let group = diagnostics
 9177                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9178                // be sorted in a stable way
 9179                // skip until we are at current active diagnostic, if it exists
 9180                .skip_while(|entry| {
 9181                    (match direction {
 9182                        Direction::Prev => entry.range.start >= search_start,
 9183                        Direction::Next => entry.range.start <= search_start,
 9184                    }) && self
 9185                        .active_diagnostics
 9186                        .as_ref()
 9187                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9188                })
 9189                .find_map(|entry| {
 9190                    if entry.diagnostic.is_primary
 9191                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9192                        && !entry.range.is_empty()
 9193                        // if we match with the active diagnostic, skip it
 9194                        && Some(entry.diagnostic.group_id)
 9195                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9196                    {
 9197                        Some((entry.range, entry.diagnostic.group_id))
 9198                    } else {
 9199                        None
 9200                    }
 9201                });
 9202
 9203            if let Some((primary_range, group_id)) = group {
 9204                if self.activate_diagnostics(group_id, cx) {
 9205                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9206                        s.select(vec![Selection {
 9207                            id: selection.id,
 9208                            start: primary_range.start,
 9209                            end: primary_range.start,
 9210                            reversed: false,
 9211                            goal: SelectionGoal::None,
 9212                        }]);
 9213                    });
 9214                }
 9215                break;
 9216            } else {
 9217                // Cycle around to the start of the buffer, potentially moving back to the start of
 9218                // the currently active diagnostic.
 9219                active_primary_range.take();
 9220                if direction == Direction::Prev {
 9221                    if search_start == buffer.len() {
 9222                        break;
 9223                    } else {
 9224                        search_start = buffer.len();
 9225                    }
 9226                } else if search_start == 0 {
 9227                    break;
 9228                } else {
 9229                    search_start = 0;
 9230                }
 9231            }
 9232        }
 9233    }
 9234
 9235    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9236        let snapshot = self.snapshot(cx);
 9237        let selection = self.selections.newest::<Point>(cx);
 9238        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9239    }
 9240
 9241    fn go_to_hunk_after_position(
 9242        &mut self,
 9243        snapshot: &EditorSnapshot,
 9244        position: Point,
 9245        cx: &mut ViewContext<'_, Editor>,
 9246    ) -> Option<MultiBufferDiffHunk> {
 9247        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9248            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9249                snapshot,
 9250                position,
 9251                ix > 0,
 9252                snapshot.diff_map.diff_hunks_in_range(
 9253                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9254                    &snapshot.buffer_snapshot,
 9255                ),
 9256                cx,
 9257            ) {
 9258                return Some(hunk);
 9259            }
 9260        }
 9261        None
 9262    }
 9263
 9264    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9265        let snapshot = self.snapshot(cx);
 9266        let selection = self.selections.newest::<Point>(cx);
 9267        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9268    }
 9269
 9270    fn go_to_hunk_before_position(
 9271        &mut self,
 9272        snapshot: &EditorSnapshot,
 9273        position: Point,
 9274        cx: &mut ViewContext<'_, Editor>,
 9275    ) -> Option<MultiBufferDiffHunk> {
 9276        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9277            .into_iter()
 9278            .enumerate()
 9279        {
 9280            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9281                snapshot,
 9282                position,
 9283                ix > 0,
 9284                snapshot
 9285                    .diff_map
 9286                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9287                cx,
 9288            ) {
 9289                return Some(hunk);
 9290            }
 9291        }
 9292        None
 9293    }
 9294
 9295    fn go_to_next_hunk_in_direction(
 9296        &mut self,
 9297        snapshot: &DisplaySnapshot,
 9298        initial_point: Point,
 9299        is_wrapped: bool,
 9300        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9301        cx: &mut ViewContext<Editor>,
 9302    ) -> Option<MultiBufferDiffHunk> {
 9303        let display_point = initial_point.to_display_point(snapshot);
 9304        let mut hunks = hunks
 9305            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9306            .filter(|(display_hunk, _)| {
 9307                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9308            })
 9309            .dedup();
 9310
 9311        if let Some((display_hunk, hunk)) = hunks.next() {
 9312            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9313                let row = display_hunk.start_display_row();
 9314                let point = DisplayPoint::new(row, 0);
 9315                s.select_display_ranges([point..point]);
 9316            });
 9317
 9318            Some(hunk)
 9319        } else {
 9320            None
 9321        }
 9322    }
 9323
 9324    pub fn go_to_definition(
 9325        &mut self,
 9326        _: &GoToDefinition,
 9327        cx: &mut ViewContext<Self>,
 9328    ) -> Task<Result<Navigated>> {
 9329        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9330        cx.spawn(|editor, mut cx| async move {
 9331            if definition.await? == Navigated::Yes {
 9332                return Ok(Navigated::Yes);
 9333            }
 9334            match editor.update(&mut cx, |editor, cx| {
 9335                editor.find_all_references(&FindAllReferences, cx)
 9336            })? {
 9337                Some(references) => references.await,
 9338                None => Ok(Navigated::No),
 9339            }
 9340        })
 9341    }
 9342
 9343    pub fn go_to_declaration(
 9344        &mut self,
 9345        _: &GoToDeclaration,
 9346        cx: &mut ViewContext<Self>,
 9347    ) -> Task<Result<Navigated>> {
 9348        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9349    }
 9350
 9351    pub fn go_to_declaration_split(
 9352        &mut self,
 9353        _: &GoToDeclaration,
 9354        cx: &mut ViewContext<Self>,
 9355    ) -> Task<Result<Navigated>> {
 9356        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9357    }
 9358
 9359    pub fn go_to_implementation(
 9360        &mut self,
 9361        _: &GoToImplementation,
 9362        cx: &mut ViewContext<Self>,
 9363    ) -> Task<Result<Navigated>> {
 9364        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9365    }
 9366
 9367    pub fn go_to_implementation_split(
 9368        &mut self,
 9369        _: &GoToImplementationSplit,
 9370        cx: &mut ViewContext<Self>,
 9371    ) -> Task<Result<Navigated>> {
 9372        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9373    }
 9374
 9375    pub fn go_to_type_definition(
 9376        &mut self,
 9377        _: &GoToTypeDefinition,
 9378        cx: &mut ViewContext<Self>,
 9379    ) -> Task<Result<Navigated>> {
 9380        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9381    }
 9382
 9383    pub fn go_to_definition_split(
 9384        &mut self,
 9385        _: &GoToDefinitionSplit,
 9386        cx: &mut ViewContext<Self>,
 9387    ) -> Task<Result<Navigated>> {
 9388        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9389    }
 9390
 9391    pub fn go_to_type_definition_split(
 9392        &mut self,
 9393        _: &GoToTypeDefinitionSplit,
 9394        cx: &mut ViewContext<Self>,
 9395    ) -> Task<Result<Navigated>> {
 9396        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9397    }
 9398
 9399    fn go_to_definition_of_kind(
 9400        &mut self,
 9401        kind: GotoDefinitionKind,
 9402        split: bool,
 9403        cx: &mut ViewContext<Self>,
 9404    ) -> Task<Result<Navigated>> {
 9405        let Some(provider) = self.semantics_provider.clone() else {
 9406            return Task::ready(Ok(Navigated::No));
 9407        };
 9408        let head = self.selections.newest::<usize>(cx).head();
 9409        let buffer = self.buffer.read(cx);
 9410        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9411            text_anchor
 9412        } else {
 9413            return Task::ready(Ok(Navigated::No));
 9414        };
 9415
 9416        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9417            return Task::ready(Ok(Navigated::No));
 9418        };
 9419
 9420        cx.spawn(|editor, mut cx| async move {
 9421            let definitions = definitions.await?;
 9422            let navigated = editor
 9423                .update(&mut cx, |editor, cx| {
 9424                    editor.navigate_to_hover_links(
 9425                        Some(kind),
 9426                        definitions
 9427                            .into_iter()
 9428                            .filter(|location| {
 9429                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9430                            })
 9431                            .map(HoverLink::Text)
 9432                            .collect::<Vec<_>>(),
 9433                        split,
 9434                        cx,
 9435                    )
 9436                })?
 9437                .await?;
 9438            anyhow::Ok(navigated)
 9439        })
 9440    }
 9441
 9442    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9443        let selection = self.selections.newest_anchor();
 9444        let head = selection.head();
 9445        let tail = selection.tail();
 9446
 9447        let Some((buffer, start_position)) =
 9448            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9449        else {
 9450            return;
 9451        };
 9452
 9453        let end_position = if head != tail {
 9454            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9455                return;
 9456            };
 9457            Some(pos)
 9458        } else {
 9459            None
 9460        };
 9461
 9462        let url_finder = cx.spawn(|editor, mut cx| async move {
 9463            let url = if let Some(end_pos) = end_position {
 9464                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9465            } else {
 9466                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9467            };
 9468
 9469            if let Some(url) = url {
 9470                editor.update(&mut cx, |_, cx| {
 9471                    cx.open_url(&url);
 9472                })
 9473            } else {
 9474                Ok(())
 9475            }
 9476        });
 9477
 9478        url_finder.detach();
 9479    }
 9480
 9481    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9482        let Some(workspace) = self.workspace() else {
 9483            return;
 9484        };
 9485
 9486        let position = self.selections.newest_anchor().head();
 9487
 9488        let Some((buffer, buffer_position)) =
 9489            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9490        else {
 9491            return;
 9492        };
 9493
 9494        let project = self.project.clone();
 9495
 9496        cx.spawn(|_, mut cx| async move {
 9497            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9498
 9499            if let Some((_, path)) = result {
 9500                workspace
 9501                    .update(&mut cx, |workspace, cx| {
 9502                        workspace.open_resolved_path(path, cx)
 9503                    })?
 9504                    .await?;
 9505            }
 9506            anyhow::Ok(())
 9507        })
 9508        .detach();
 9509    }
 9510
 9511    pub(crate) fn navigate_to_hover_links(
 9512        &mut self,
 9513        kind: Option<GotoDefinitionKind>,
 9514        mut definitions: Vec<HoverLink>,
 9515        split: bool,
 9516        cx: &mut ViewContext<Editor>,
 9517    ) -> Task<Result<Navigated>> {
 9518        // If there is one definition, just open it directly
 9519        if definitions.len() == 1 {
 9520            let definition = definitions.pop().unwrap();
 9521
 9522            enum TargetTaskResult {
 9523                Location(Option<Location>),
 9524                AlreadyNavigated,
 9525            }
 9526
 9527            let target_task = match definition {
 9528                HoverLink::Text(link) => {
 9529                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9530                }
 9531                HoverLink::InlayHint(lsp_location, server_id) => {
 9532                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9533                    cx.background_executor().spawn(async move {
 9534                        let location = computation.await?;
 9535                        Ok(TargetTaskResult::Location(location))
 9536                    })
 9537                }
 9538                HoverLink::Url(url) => {
 9539                    cx.open_url(&url);
 9540                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9541                }
 9542                HoverLink::File(path) => {
 9543                    if let Some(workspace) = self.workspace() {
 9544                        cx.spawn(|_, mut cx| async move {
 9545                            workspace
 9546                                .update(&mut cx, |workspace, cx| {
 9547                                    workspace.open_resolved_path(path, cx)
 9548                                })?
 9549                                .await
 9550                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9551                        })
 9552                    } else {
 9553                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9554                    }
 9555                }
 9556            };
 9557            cx.spawn(|editor, mut cx| async move {
 9558                let target = match target_task.await.context("target resolution task")? {
 9559                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9560                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9561                    TargetTaskResult::Location(Some(target)) => target,
 9562                };
 9563
 9564                editor.update(&mut cx, |editor, cx| {
 9565                    let Some(workspace) = editor.workspace() else {
 9566                        return Navigated::No;
 9567                    };
 9568                    let pane = workspace.read(cx).active_pane().clone();
 9569
 9570                    let range = target.range.to_offset(target.buffer.read(cx));
 9571                    let range = editor.range_for_match(&range);
 9572
 9573                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9574                        let buffer = target.buffer.read(cx);
 9575                        let range = check_multiline_range(buffer, range);
 9576                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9577                            s.select_ranges([range]);
 9578                        });
 9579                    } else {
 9580                        cx.window_context().defer(move |cx| {
 9581                            let target_editor: View<Self> =
 9582                                workspace.update(cx, |workspace, cx| {
 9583                                    let pane = if split {
 9584                                        workspace.adjacent_pane(cx)
 9585                                    } else {
 9586                                        workspace.active_pane().clone()
 9587                                    };
 9588
 9589                                    workspace.open_project_item(
 9590                                        pane,
 9591                                        target.buffer.clone(),
 9592                                        true,
 9593                                        true,
 9594                                        cx,
 9595                                    )
 9596                                });
 9597                            target_editor.update(cx, |target_editor, cx| {
 9598                                // When selecting a definition in a different buffer, disable the nav history
 9599                                // to avoid creating a history entry at the previous cursor location.
 9600                                pane.update(cx, |pane, _| pane.disable_history());
 9601                                let buffer = target.buffer.read(cx);
 9602                                let range = check_multiline_range(buffer, range);
 9603                                target_editor.change_selections(
 9604                                    Some(Autoscroll::focused()),
 9605                                    cx,
 9606                                    |s| {
 9607                                        s.select_ranges([range]);
 9608                                    },
 9609                                );
 9610                                pane.update(cx, |pane, _| pane.enable_history());
 9611                            });
 9612                        });
 9613                    }
 9614                    Navigated::Yes
 9615                })
 9616            })
 9617        } else if !definitions.is_empty() {
 9618            cx.spawn(|editor, mut cx| async move {
 9619                let (title, location_tasks, workspace) = editor
 9620                    .update(&mut cx, |editor, cx| {
 9621                        let tab_kind = match kind {
 9622                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9623                            _ => "Definitions",
 9624                        };
 9625                        let title = definitions
 9626                            .iter()
 9627                            .find_map(|definition| match definition {
 9628                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9629                                    let buffer = origin.buffer.read(cx);
 9630                                    format!(
 9631                                        "{} for {}",
 9632                                        tab_kind,
 9633                                        buffer
 9634                                            .text_for_range(origin.range.clone())
 9635                                            .collect::<String>()
 9636                                    )
 9637                                }),
 9638                                HoverLink::InlayHint(_, _) => None,
 9639                                HoverLink::Url(_) => None,
 9640                                HoverLink::File(_) => None,
 9641                            })
 9642                            .unwrap_or(tab_kind.to_string());
 9643                        let location_tasks = definitions
 9644                            .into_iter()
 9645                            .map(|definition| match definition {
 9646                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9647                                HoverLink::InlayHint(lsp_location, server_id) => {
 9648                                    editor.compute_target_location(lsp_location, server_id, cx)
 9649                                }
 9650                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9651                                HoverLink::File(_) => Task::ready(Ok(None)),
 9652                            })
 9653                            .collect::<Vec<_>>();
 9654                        (title, location_tasks, editor.workspace().clone())
 9655                    })
 9656                    .context("location tasks preparation")?;
 9657
 9658                let locations = future::join_all(location_tasks)
 9659                    .await
 9660                    .into_iter()
 9661                    .filter_map(|location| location.transpose())
 9662                    .collect::<Result<_>>()
 9663                    .context("location tasks")?;
 9664
 9665                let Some(workspace) = workspace else {
 9666                    return Ok(Navigated::No);
 9667                };
 9668                let opened = workspace
 9669                    .update(&mut cx, |workspace, cx| {
 9670                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9671                    })
 9672                    .ok();
 9673
 9674                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9675            })
 9676        } else {
 9677            Task::ready(Ok(Navigated::No))
 9678        }
 9679    }
 9680
 9681    fn compute_target_location(
 9682        &self,
 9683        lsp_location: lsp::Location,
 9684        server_id: LanguageServerId,
 9685        cx: &mut ViewContext<Self>,
 9686    ) -> Task<anyhow::Result<Option<Location>>> {
 9687        let Some(project) = self.project.clone() else {
 9688            return Task::ready(Ok(None));
 9689        };
 9690
 9691        cx.spawn(move |editor, mut cx| async move {
 9692            let location_task = editor.update(&mut cx, |_, cx| {
 9693                project.update(cx, |project, cx| {
 9694                    let language_server_name = project
 9695                        .language_server_statuses(cx)
 9696                        .find(|(id, _)| server_id == *id)
 9697                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9698                    language_server_name.map(|language_server_name| {
 9699                        project.open_local_buffer_via_lsp(
 9700                            lsp_location.uri.clone(),
 9701                            server_id,
 9702                            language_server_name,
 9703                            cx,
 9704                        )
 9705                    })
 9706                })
 9707            })?;
 9708            let location = match location_task {
 9709                Some(task) => Some({
 9710                    let target_buffer_handle = task.await.context("open local buffer")?;
 9711                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9712                        let target_start = target_buffer
 9713                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9714                        let target_end = target_buffer
 9715                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9716                        target_buffer.anchor_after(target_start)
 9717                            ..target_buffer.anchor_before(target_end)
 9718                    })?;
 9719                    Location {
 9720                        buffer: target_buffer_handle,
 9721                        range,
 9722                    }
 9723                }),
 9724                None => None,
 9725            };
 9726            Ok(location)
 9727        })
 9728    }
 9729
 9730    pub fn find_all_references(
 9731        &mut self,
 9732        _: &FindAllReferences,
 9733        cx: &mut ViewContext<Self>,
 9734    ) -> Option<Task<Result<Navigated>>> {
 9735        let selection = self.selections.newest::<usize>(cx);
 9736        let multi_buffer = self.buffer.read(cx);
 9737        let head = selection.head();
 9738
 9739        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9740        let head_anchor = multi_buffer_snapshot.anchor_at(
 9741            head,
 9742            if head < selection.tail() {
 9743                Bias::Right
 9744            } else {
 9745                Bias::Left
 9746            },
 9747        );
 9748
 9749        match self
 9750            .find_all_references_task_sources
 9751            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9752        {
 9753            Ok(_) => {
 9754                log::info!(
 9755                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9756                );
 9757                return None;
 9758            }
 9759            Err(i) => {
 9760                self.find_all_references_task_sources.insert(i, head_anchor);
 9761            }
 9762        }
 9763
 9764        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9765        let workspace = self.workspace()?;
 9766        let project = workspace.read(cx).project().clone();
 9767        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9768        Some(cx.spawn(|editor, mut cx| async move {
 9769            let _cleanup = defer({
 9770                let mut cx = cx.clone();
 9771                move || {
 9772                    let _ = editor.update(&mut cx, |editor, _| {
 9773                        if let Ok(i) =
 9774                            editor
 9775                                .find_all_references_task_sources
 9776                                .binary_search_by(|anchor| {
 9777                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9778                                })
 9779                        {
 9780                            editor.find_all_references_task_sources.remove(i);
 9781                        }
 9782                    });
 9783                }
 9784            });
 9785
 9786            let locations = references.await?;
 9787            if locations.is_empty() {
 9788                return anyhow::Ok(Navigated::No);
 9789            }
 9790
 9791            workspace.update(&mut cx, |workspace, cx| {
 9792                let title = locations
 9793                    .first()
 9794                    .as_ref()
 9795                    .map(|location| {
 9796                        let buffer = location.buffer.read(cx);
 9797                        format!(
 9798                            "References to `{}`",
 9799                            buffer
 9800                                .text_for_range(location.range.clone())
 9801                                .collect::<String>()
 9802                        )
 9803                    })
 9804                    .unwrap();
 9805                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9806                Navigated::Yes
 9807            })
 9808        }))
 9809    }
 9810
 9811    /// Opens a multibuffer with the given project locations in it
 9812    pub fn open_locations_in_multibuffer(
 9813        workspace: &mut Workspace,
 9814        mut locations: Vec<Location>,
 9815        title: String,
 9816        split: bool,
 9817        cx: &mut ViewContext<Workspace>,
 9818    ) {
 9819        // If there are multiple definitions, open them in a multibuffer
 9820        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9821        let mut locations = locations.into_iter().peekable();
 9822        let mut ranges_to_highlight = Vec::new();
 9823        let capability = workspace.project().read(cx).capability();
 9824
 9825        let excerpt_buffer = cx.new_model(|cx| {
 9826            let mut multibuffer = MultiBuffer::new(capability);
 9827            while let Some(location) = locations.next() {
 9828                let buffer = location.buffer.read(cx);
 9829                let mut ranges_for_buffer = Vec::new();
 9830                let range = location.range.to_offset(buffer);
 9831                ranges_for_buffer.push(range.clone());
 9832
 9833                while let Some(next_location) = locations.peek() {
 9834                    if next_location.buffer == location.buffer {
 9835                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9836                        locations.next();
 9837                    } else {
 9838                        break;
 9839                    }
 9840                }
 9841
 9842                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9843                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9844                    location.buffer.clone(),
 9845                    ranges_for_buffer,
 9846                    DEFAULT_MULTIBUFFER_CONTEXT,
 9847                    cx,
 9848                ))
 9849            }
 9850
 9851            multibuffer.with_title(title)
 9852        });
 9853
 9854        let editor = cx.new_view(|cx| {
 9855            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9856        });
 9857        editor.update(cx, |editor, cx| {
 9858            if let Some(first_range) = ranges_to_highlight.first() {
 9859                editor.change_selections(None, cx, |selections| {
 9860                    selections.clear_disjoint();
 9861                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9862                });
 9863            }
 9864            editor.highlight_background::<Self>(
 9865                &ranges_to_highlight,
 9866                |theme| theme.editor_highlighted_line_background,
 9867                cx,
 9868            );
 9869            editor.register_buffers_with_language_servers(cx);
 9870        });
 9871
 9872        let item = Box::new(editor);
 9873        let item_id = item.item_id();
 9874
 9875        if split {
 9876            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9877        } else {
 9878            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9879                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9880                    pane.close_current_preview_item(cx)
 9881                } else {
 9882                    None
 9883                }
 9884            });
 9885            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9886        }
 9887        workspace.active_pane().update(cx, |pane, cx| {
 9888            pane.set_preview_item_id(Some(item_id), cx);
 9889        });
 9890    }
 9891
 9892    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9893        use language::ToOffset as _;
 9894
 9895        let provider = self.semantics_provider.clone()?;
 9896        let selection = self.selections.newest_anchor().clone();
 9897        let (cursor_buffer, cursor_buffer_position) = self
 9898            .buffer
 9899            .read(cx)
 9900            .text_anchor_for_position(selection.head(), cx)?;
 9901        let (tail_buffer, cursor_buffer_position_end) = self
 9902            .buffer
 9903            .read(cx)
 9904            .text_anchor_for_position(selection.tail(), cx)?;
 9905        if tail_buffer != cursor_buffer {
 9906            return None;
 9907        }
 9908
 9909        let snapshot = cursor_buffer.read(cx).snapshot();
 9910        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9911        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9912        let prepare_rename = provider
 9913            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9914            .unwrap_or_else(|| Task::ready(Ok(None)));
 9915        drop(snapshot);
 9916
 9917        Some(cx.spawn(|this, mut cx| async move {
 9918            let rename_range = if let Some(range) = prepare_rename.await? {
 9919                Some(range)
 9920            } else {
 9921                this.update(&mut cx, |this, cx| {
 9922                    let buffer = this.buffer.read(cx).snapshot(cx);
 9923                    let mut buffer_highlights = this
 9924                        .document_highlights_for_position(selection.head(), &buffer)
 9925                        .filter(|highlight| {
 9926                            highlight.start.excerpt_id == selection.head().excerpt_id
 9927                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9928                        });
 9929                    buffer_highlights
 9930                        .next()
 9931                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9932                })?
 9933            };
 9934            if let Some(rename_range) = rename_range {
 9935                this.update(&mut cx, |this, cx| {
 9936                    let snapshot = cursor_buffer.read(cx).snapshot();
 9937                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9938                    let cursor_offset_in_rename_range =
 9939                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9940                    let cursor_offset_in_rename_range_end =
 9941                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9942
 9943                    this.take_rename(false, cx);
 9944                    let buffer = this.buffer.read(cx).read(cx);
 9945                    let cursor_offset = selection.head().to_offset(&buffer);
 9946                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9947                    let rename_end = rename_start + rename_buffer_range.len();
 9948                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9949                    let mut old_highlight_id = None;
 9950                    let old_name: Arc<str> = buffer
 9951                        .chunks(rename_start..rename_end, true)
 9952                        .map(|chunk| {
 9953                            if old_highlight_id.is_none() {
 9954                                old_highlight_id = chunk.syntax_highlight_id;
 9955                            }
 9956                            chunk.text
 9957                        })
 9958                        .collect::<String>()
 9959                        .into();
 9960
 9961                    drop(buffer);
 9962
 9963                    // Position the selection in the rename editor so that it matches the current selection.
 9964                    this.show_local_selections = false;
 9965                    let rename_editor = cx.new_view(|cx| {
 9966                        let mut editor = Editor::single_line(cx);
 9967                        editor.buffer.update(cx, |buffer, cx| {
 9968                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9969                        });
 9970                        let rename_selection_range = match cursor_offset_in_rename_range
 9971                            .cmp(&cursor_offset_in_rename_range_end)
 9972                        {
 9973                            Ordering::Equal => {
 9974                                editor.select_all(&SelectAll, cx);
 9975                                return editor;
 9976                            }
 9977                            Ordering::Less => {
 9978                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9979                            }
 9980                            Ordering::Greater => {
 9981                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9982                            }
 9983                        };
 9984                        if rename_selection_range.end > old_name.len() {
 9985                            editor.select_all(&SelectAll, cx);
 9986                        } else {
 9987                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9988                                s.select_ranges([rename_selection_range]);
 9989                            });
 9990                        }
 9991                        editor
 9992                    });
 9993                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
 9994                        if e == &EditorEvent::Focused {
 9995                            cx.emit(EditorEvent::FocusedIn)
 9996                        }
 9997                    })
 9998                    .detach();
 9999
10000                    let write_highlights =
10001                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10002                    let read_highlights =
10003                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10004                    let ranges = write_highlights
10005                        .iter()
10006                        .flat_map(|(_, ranges)| ranges.iter())
10007                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10008                        .cloned()
10009                        .collect();
10010
10011                    this.highlight_text::<Rename>(
10012                        ranges,
10013                        HighlightStyle {
10014                            fade_out: Some(0.6),
10015                            ..Default::default()
10016                        },
10017                        cx,
10018                    );
10019                    let rename_focus_handle = rename_editor.focus_handle(cx);
10020                    cx.focus(&rename_focus_handle);
10021                    let block_id = this.insert_blocks(
10022                        [BlockProperties {
10023                            style: BlockStyle::Flex,
10024                            placement: BlockPlacement::Below(range.start),
10025                            height: 1,
10026                            render: Arc::new({
10027                                let rename_editor = rename_editor.clone();
10028                                move |cx: &mut BlockContext| {
10029                                    let mut text_style = cx.editor_style.text.clone();
10030                                    if let Some(highlight_style) = old_highlight_id
10031                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10032                                    {
10033                                        text_style = text_style.highlight(highlight_style);
10034                                    }
10035                                    div()
10036                                        .block_mouse_down()
10037                                        .pl(cx.anchor_x)
10038                                        .child(EditorElement::new(
10039                                            &rename_editor,
10040                                            EditorStyle {
10041                                                background: cx.theme().system().transparent,
10042                                                local_player: cx.editor_style.local_player,
10043                                                text: text_style,
10044                                                scrollbar_width: cx.editor_style.scrollbar_width,
10045                                                syntax: cx.editor_style.syntax.clone(),
10046                                                status: cx.editor_style.status.clone(),
10047                                                inlay_hints_style: HighlightStyle {
10048                                                    font_weight: Some(FontWeight::BOLD),
10049                                                    ..make_inlay_hints_style(cx)
10050                                                },
10051                                                inline_completion_styles: make_suggestion_styles(
10052                                                    cx,
10053                                                ),
10054                                                ..EditorStyle::default()
10055                                            },
10056                                        ))
10057                                        .into_any_element()
10058                                }
10059                            }),
10060                            priority: 0,
10061                        }],
10062                        Some(Autoscroll::fit()),
10063                        cx,
10064                    )[0];
10065                    this.pending_rename = Some(RenameState {
10066                        range,
10067                        old_name,
10068                        editor: rename_editor,
10069                        block_id,
10070                    });
10071                })?;
10072            }
10073
10074            Ok(())
10075        }))
10076    }
10077
10078    pub fn confirm_rename(
10079        &mut self,
10080        _: &ConfirmRename,
10081        cx: &mut ViewContext<Self>,
10082    ) -> Option<Task<Result<()>>> {
10083        let rename = self.take_rename(false, cx)?;
10084        let workspace = self.workspace()?.downgrade();
10085        let (buffer, start) = self
10086            .buffer
10087            .read(cx)
10088            .text_anchor_for_position(rename.range.start, cx)?;
10089        let (end_buffer, _) = self
10090            .buffer
10091            .read(cx)
10092            .text_anchor_for_position(rename.range.end, cx)?;
10093        if buffer != end_buffer {
10094            return None;
10095        }
10096
10097        let old_name = rename.old_name;
10098        let new_name = rename.editor.read(cx).text(cx);
10099
10100        let rename = self.semantics_provider.as_ref()?.perform_rename(
10101            &buffer,
10102            start,
10103            new_name.clone(),
10104            cx,
10105        )?;
10106
10107        Some(cx.spawn(|editor, mut cx| async move {
10108            let project_transaction = rename.await?;
10109            Self::open_project_transaction(
10110                &editor,
10111                workspace,
10112                project_transaction,
10113                format!("Rename: {}{}", old_name, new_name),
10114                cx.clone(),
10115            )
10116            .await?;
10117
10118            editor.update(&mut cx, |editor, cx| {
10119                editor.refresh_document_highlights(cx);
10120            })?;
10121            Ok(())
10122        }))
10123    }
10124
10125    fn take_rename(
10126        &mut self,
10127        moving_cursor: bool,
10128        cx: &mut ViewContext<Self>,
10129    ) -> Option<RenameState> {
10130        let rename = self.pending_rename.take()?;
10131        if rename.editor.focus_handle(cx).is_focused(cx) {
10132            cx.focus(&self.focus_handle);
10133        }
10134
10135        self.remove_blocks(
10136            [rename.block_id].into_iter().collect(),
10137            Some(Autoscroll::fit()),
10138            cx,
10139        );
10140        self.clear_highlights::<Rename>(cx);
10141        self.show_local_selections = true;
10142
10143        if moving_cursor {
10144            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10145                editor.selections.newest::<usize>(cx).head()
10146            });
10147
10148            // Update the selection to match the position of the selection inside
10149            // the rename editor.
10150            let snapshot = self.buffer.read(cx).read(cx);
10151            let rename_range = rename.range.to_offset(&snapshot);
10152            let cursor_in_editor = snapshot
10153                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10154                .min(rename_range.end);
10155            drop(snapshot);
10156
10157            self.change_selections(None, cx, |s| {
10158                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10159            });
10160        } else {
10161            self.refresh_document_highlights(cx);
10162        }
10163
10164        Some(rename)
10165    }
10166
10167    pub fn pending_rename(&self) -> Option<&RenameState> {
10168        self.pending_rename.as_ref()
10169    }
10170
10171    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10172        let project = match &self.project {
10173            Some(project) => project.clone(),
10174            None => return None,
10175        };
10176
10177        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10178    }
10179
10180    fn format_selections(
10181        &mut self,
10182        _: &FormatSelections,
10183        cx: &mut ViewContext<Self>,
10184    ) -> Option<Task<Result<()>>> {
10185        let project = match &self.project {
10186            Some(project) => project.clone(),
10187            None => return None,
10188        };
10189
10190        let selections = self
10191            .selections
10192            .all_adjusted(cx)
10193            .into_iter()
10194            .filter(|s| !s.is_empty())
10195            .collect_vec();
10196
10197        Some(self.perform_format(
10198            project,
10199            FormatTrigger::Manual,
10200            FormatTarget::Ranges(selections),
10201            cx,
10202        ))
10203    }
10204
10205    fn perform_format(
10206        &mut self,
10207        project: Model<Project>,
10208        trigger: FormatTrigger,
10209        target: FormatTarget,
10210        cx: &mut ViewContext<Self>,
10211    ) -> Task<Result<()>> {
10212        let buffer = self.buffer().clone();
10213        let mut buffers = buffer.read(cx).all_buffers();
10214        if trigger == FormatTrigger::Save {
10215            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10216        }
10217
10218        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10219        let format = project.update(cx, |project, cx| {
10220            project.format(buffers, true, trigger, target, cx)
10221        });
10222
10223        cx.spawn(|_, mut cx| async move {
10224            let transaction = futures::select_biased! {
10225                () = timeout => {
10226                    log::warn!("timed out waiting for formatting");
10227                    None
10228                }
10229                transaction = format.log_err().fuse() => transaction,
10230            };
10231
10232            buffer
10233                .update(&mut cx, |buffer, cx| {
10234                    if let Some(transaction) = transaction {
10235                        if !buffer.is_singleton() {
10236                            buffer.push_transaction(&transaction.0, cx);
10237                        }
10238                    }
10239
10240                    cx.notify();
10241                })
10242                .ok();
10243
10244            Ok(())
10245        })
10246    }
10247
10248    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10249        if let Some(project) = self.project.clone() {
10250            self.buffer.update(cx, |multi_buffer, cx| {
10251                project.update(cx, |project, cx| {
10252                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10253                });
10254            })
10255        }
10256    }
10257
10258    fn cancel_language_server_work(
10259        &mut self,
10260        _: &actions::CancelLanguageServerWork,
10261        cx: &mut ViewContext<Self>,
10262    ) {
10263        if let Some(project) = self.project.clone() {
10264            self.buffer.update(cx, |multi_buffer, cx| {
10265                project.update(cx, |project, cx| {
10266                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10267                });
10268            })
10269        }
10270    }
10271
10272    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10273        cx.show_character_palette();
10274    }
10275
10276    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10277        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10278            let buffer = self.buffer.read(cx).snapshot(cx);
10279            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10280            let is_valid = buffer
10281                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10282                .any(|entry| {
10283                    entry.diagnostic.is_primary
10284                        && !entry.range.is_empty()
10285                        && entry.range.start == primary_range_start
10286                        && entry.diagnostic.message == active_diagnostics.primary_message
10287                });
10288
10289            if is_valid != active_diagnostics.is_valid {
10290                active_diagnostics.is_valid = is_valid;
10291                let mut new_styles = HashMap::default();
10292                for (block_id, diagnostic) in &active_diagnostics.blocks {
10293                    new_styles.insert(
10294                        *block_id,
10295                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10296                    );
10297                }
10298                self.display_map.update(cx, |display_map, _cx| {
10299                    display_map.replace_blocks(new_styles)
10300                });
10301            }
10302        }
10303    }
10304
10305    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10306        self.dismiss_diagnostics(cx);
10307        let snapshot = self.snapshot(cx);
10308        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10309            let buffer = self.buffer.read(cx).snapshot(cx);
10310
10311            let mut primary_range = None;
10312            let mut primary_message = None;
10313            let mut group_end = Point::zero();
10314            let diagnostic_group = buffer
10315                .diagnostic_group::<MultiBufferPoint>(group_id)
10316                .filter_map(|entry| {
10317                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10318                        && (entry.range.start.row == entry.range.end.row
10319                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10320                    {
10321                        return None;
10322                    }
10323                    if entry.range.end > group_end {
10324                        group_end = entry.range.end;
10325                    }
10326                    if entry.diagnostic.is_primary {
10327                        primary_range = Some(entry.range.clone());
10328                        primary_message = Some(entry.diagnostic.message.clone());
10329                    }
10330                    Some(entry)
10331                })
10332                .collect::<Vec<_>>();
10333            let primary_range = primary_range?;
10334            let primary_message = primary_message?;
10335            let primary_range =
10336                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10337
10338            let blocks = display_map
10339                .insert_blocks(
10340                    diagnostic_group.iter().map(|entry| {
10341                        let diagnostic = entry.diagnostic.clone();
10342                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10343                        BlockProperties {
10344                            style: BlockStyle::Fixed,
10345                            placement: BlockPlacement::Below(
10346                                buffer.anchor_after(entry.range.start),
10347                            ),
10348                            height: message_height,
10349                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10350                            priority: 0,
10351                        }
10352                    }),
10353                    cx,
10354                )
10355                .into_iter()
10356                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10357                .collect();
10358
10359            Some(ActiveDiagnosticGroup {
10360                primary_range,
10361                primary_message,
10362                group_id,
10363                blocks,
10364                is_valid: true,
10365            })
10366        });
10367        self.active_diagnostics.is_some()
10368    }
10369
10370    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10371        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10372            self.display_map.update(cx, |display_map, cx| {
10373                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10374            });
10375            cx.notify();
10376        }
10377    }
10378
10379    pub fn set_selections_from_remote(
10380        &mut self,
10381        selections: Vec<Selection<Anchor>>,
10382        pending_selection: Option<Selection<Anchor>>,
10383        cx: &mut ViewContext<Self>,
10384    ) {
10385        let old_cursor_position = self.selections.newest_anchor().head();
10386        self.selections.change_with(cx, |s| {
10387            s.select_anchors(selections);
10388            if let Some(pending_selection) = pending_selection {
10389                s.set_pending(pending_selection, SelectMode::Character);
10390            } else {
10391                s.clear_pending();
10392            }
10393        });
10394        self.selections_did_change(false, &old_cursor_position, true, cx);
10395    }
10396
10397    fn push_to_selection_history(&mut self) {
10398        self.selection_history.push(SelectionHistoryEntry {
10399            selections: self.selections.disjoint_anchors(),
10400            select_next_state: self.select_next_state.clone(),
10401            select_prev_state: self.select_prev_state.clone(),
10402            add_selections_state: self.add_selections_state.clone(),
10403        });
10404    }
10405
10406    pub fn transact(
10407        &mut self,
10408        cx: &mut ViewContext<Self>,
10409        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10410    ) -> Option<TransactionId> {
10411        self.start_transaction_at(Instant::now(), cx);
10412        update(self, cx);
10413        self.end_transaction_at(Instant::now(), cx)
10414    }
10415
10416    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10417        self.end_selection(cx);
10418        if let Some(tx_id) = self
10419            .buffer
10420            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10421        {
10422            self.selection_history
10423                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10424            cx.emit(EditorEvent::TransactionBegun {
10425                transaction_id: tx_id,
10426            })
10427        }
10428    }
10429
10430    pub fn end_transaction_at(
10431        &mut self,
10432        now: Instant,
10433        cx: &mut ViewContext<Self>,
10434    ) -> Option<TransactionId> {
10435        if let Some(transaction_id) = self
10436            .buffer
10437            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10438        {
10439            if let Some((_, end_selections)) =
10440                self.selection_history.transaction_mut(transaction_id)
10441            {
10442                *end_selections = Some(self.selections.disjoint_anchors());
10443            } else {
10444                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10445            }
10446
10447            cx.emit(EditorEvent::Edited { transaction_id });
10448            Some(transaction_id)
10449        } else {
10450            None
10451        }
10452    }
10453
10454    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10455        if self.is_singleton(cx) {
10456            let selection = self.selections.newest::<Point>(cx);
10457
10458            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10459            let range = if selection.is_empty() {
10460                let point = selection.head().to_display_point(&display_map);
10461                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10462                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10463                    .to_point(&display_map);
10464                start..end
10465            } else {
10466                selection.range()
10467            };
10468            if display_map.folds_in_range(range).next().is_some() {
10469                self.unfold_lines(&Default::default(), cx)
10470            } else {
10471                self.fold(&Default::default(), cx)
10472            }
10473        } else {
10474            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10475            let mut toggled_buffers = HashSet::default();
10476            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10477                self.selections
10478                    .disjoint_anchors()
10479                    .into_iter()
10480                    .map(|selection| selection.range()),
10481            ) {
10482                let buffer_id = buffer_snapshot.remote_id();
10483                if toggled_buffers.insert(buffer_id) {
10484                    if self.buffer_folded(buffer_id, cx) {
10485                        self.unfold_buffer(buffer_id, cx);
10486                    } else {
10487                        self.fold_buffer(buffer_id, cx);
10488                    }
10489                }
10490            }
10491        }
10492    }
10493
10494    pub fn toggle_fold_recursive(
10495        &mut self,
10496        _: &actions::ToggleFoldRecursive,
10497        cx: &mut ViewContext<Self>,
10498    ) {
10499        let selection = self.selections.newest::<Point>(cx);
10500
10501        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10502        let range = if selection.is_empty() {
10503            let point = selection.head().to_display_point(&display_map);
10504            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10505            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10506                .to_point(&display_map);
10507            start..end
10508        } else {
10509            selection.range()
10510        };
10511        if display_map.folds_in_range(range).next().is_some() {
10512            self.unfold_recursive(&Default::default(), cx)
10513        } else {
10514            self.fold_recursive(&Default::default(), cx)
10515        }
10516    }
10517
10518    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10519        if self.is_singleton(cx) {
10520            let mut to_fold = Vec::new();
10521            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10522            let selections = self.selections.all_adjusted(cx);
10523
10524            for selection in selections {
10525                let range = selection.range().sorted();
10526                let buffer_start_row = range.start.row;
10527
10528                if range.start.row != range.end.row {
10529                    let mut found = false;
10530                    let mut row = range.start.row;
10531                    while row <= range.end.row {
10532                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10533                        {
10534                            found = true;
10535                            row = crease.range().end.row + 1;
10536                            to_fold.push(crease);
10537                        } else {
10538                            row += 1
10539                        }
10540                    }
10541                    if found {
10542                        continue;
10543                    }
10544                }
10545
10546                for row in (0..=range.start.row).rev() {
10547                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10548                        if crease.range().end.row >= buffer_start_row {
10549                            to_fold.push(crease);
10550                            if row <= range.start.row {
10551                                break;
10552                            }
10553                        }
10554                    }
10555                }
10556            }
10557
10558            self.fold_creases(to_fold, true, cx);
10559        } else {
10560            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10561            let mut folded_buffers = HashSet::default();
10562            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10563                self.selections
10564                    .disjoint_anchors()
10565                    .into_iter()
10566                    .map(|selection| selection.range()),
10567            ) {
10568                let buffer_id = buffer_snapshot.remote_id();
10569                if folded_buffers.insert(buffer_id) {
10570                    self.fold_buffer(buffer_id, cx);
10571                }
10572            }
10573        }
10574    }
10575
10576    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10577        if !self.buffer.read(cx).is_singleton() {
10578            return;
10579        }
10580
10581        let fold_at_level = fold_at.level;
10582        let snapshot = self.buffer.read(cx).snapshot(cx);
10583        let mut to_fold = Vec::new();
10584        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10585
10586        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10587            while start_row < end_row {
10588                match self
10589                    .snapshot(cx)
10590                    .crease_for_buffer_row(MultiBufferRow(start_row))
10591                {
10592                    Some(crease) => {
10593                        let nested_start_row = crease.range().start.row + 1;
10594                        let nested_end_row = crease.range().end.row;
10595
10596                        if current_level < fold_at_level {
10597                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10598                        } else if current_level == fold_at_level {
10599                            to_fold.push(crease);
10600                        }
10601
10602                        start_row = nested_end_row + 1;
10603                    }
10604                    None => start_row += 1,
10605                }
10606            }
10607        }
10608
10609        self.fold_creases(to_fold, true, cx);
10610    }
10611
10612    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10613        if self.buffer.read(cx).is_singleton() {
10614            let mut fold_ranges = Vec::new();
10615            let snapshot = self.buffer.read(cx).snapshot(cx);
10616
10617            for row in 0..snapshot.max_row().0 {
10618                if let Some(foldable_range) =
10619                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10620                {
10621                    fold_ranges.push(foldable_range);
10622                }
10623            }
10624
10625            self.fold_creases(fold_ranges, true, cx);
10626        } else {
10627            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10628                editor
10629                    .update(&mut cx, |editor, cx| {
10630                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10631                            editor.fold_buffer(buffer_id, cx);
10632                        }
10633                    })
10634                    .ok();
10635            });
10636        }
10637    }
10638
10639    pub fn fold_function_bodies(
10640        &mut self,
10641        _: &actions::FoldFunctionBodies,
10642        cx: &mut ViewContext<Self>,
10643    ) {
10644        let snapshot = self.buffer.read(cx).snapshot(cx);
10645        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10646            return;
10647        };
10648        let creases = buffer
10649            .function_body_fold_ranges(0..buffer.len())
10650            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10651            .collect();
10652
10653        self.fold_creases(creases, true, cx);
10654    }
10655
10656    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10657        let mut to_fold = Vec::new();
10658        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10659        let selections = self.selections.all_adjusted(cx);
10660
10661        for selection in selections {
10662            let range = selection.range().sorted();
10663            let buffer_start_row = range.start.row;
10664
10665            if range.start.row != range.end.row {
10666                let mut found = false;
10667                for row in range.start.row..=range.end.row {
10668                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10669                        found = true;
10670                        to_fold.push(crease);
10671                    }
10672                }
10673                if found {
10674                    continue;
10675                }
10676            }
10677
10678            for row in (0..=range.start.row).rev() {
10679                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10680                    if crease.range().end.row >= buffer_start_row {
10681                        to_fold.push(crease);
10682                    } else {
10683                        break;
10684                    }
10685                }
10686            }
10687        }
10688
10689        self.fold_creases(to_fold, true, cx);
10690    }
10691
10692    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10693        let buffer_row = fold_at.buffer_row;
10694        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10695
10696        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10697            let autoscroll = self
10698                .selections
10699                .all::<Point>(cx)
10700                .iter()
10701                .any(|selection| crease.range().overlaps(&selection.range()));
10702
10703            self.fold_creases(vec![crease], autoscroll, cx);
10704        }
10705    }
10706
10707    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10708        if self.is_singleton(cx) {
10709            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10710            let buffer = &display_map.buffer_snapshot;
10711            let selections = self.selections.all::<Point>(cx);
10712            let ranges = selections
10713                .iter()
10714                .map(|s| {
10715                    let range = s.display_range(&display_map).sorted();
10716                    let mut start = range.start.to_point(&display_map);
10717                    let mut end = range.end.to_point(&display_map);
10718                    start.column = 0;
10719                    end.column = buffer.line_len(MultiBufferRow(end.row));
10720                    start..end
10721                })
10722                .collect::<Vec<_>>();
10723
10724            self.unfold_ranges(&ranges, true, true, cx);
10725        } else {
10726            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10727            let mut unfolded_buffers = HashSet::default();
10728            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10729                self.selections
10730                    .disjoint_anchors()
10731                    .into_iter()
10732                    .map(|selection| selection.range()),
10733            ) {
10734                let buffer_id = buffer_snapshot.remote_id();
10735                if unfolded_buffers.insert(buffer_id) {
10736                    self.unfold_buffer(buffer_id, cx);
10737                }
10738            }
10739        }
10740    }
10741
10742    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10743        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10744        let selections = self.selections.all::<Point>(cx);
10745        let ranges = selections
10746            .iter()
10747            .map(|s| {
10748                let mut range = s.display_range(&display_map).sorted();
10749                *range.start.column_mut() = 0;
10750                *range.end.column_mut() = display_map.line_len(range.end.row());
10751                let start = range.start.to_point(&display_map);
10752                let end = range.end.to_point(&display_map);
10753                start..end
10754            })
10755            .collect::<Vec<_>>();
10756
10757        self.unfold_ranges(&ranges, true, true, cx);
10758    }
10759
10760    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10761        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10762
10763        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10764            ..Point::new(
10765                unfold_at.buffer_row.0,
10766                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10767            );
10768
10769        let autoscroll = self
10770            .selections
10771            .all::<Point>(cx)
10772            .iter()
10773            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10774
10775        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10776    }
10777
10778    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10779        if self.buffer.read(cx).is_singleton() {
10780            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10781            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10782        } else {
10783            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10784                editor
10785                    .update(&mut cx, |editor, cx| {
10786                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10787                            editor.unfold_buffer(buffer_id, cx);
10788                        }
10789                    })
10790                    .ok();
10791            });
10792        }
10793    }
10794
10795    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10796        let selections = self.selections.all::<Point>(cx);
10797        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10798        let line_mode = self.selections.line_mode;
10799        let ranges = selections
10800            .into_iter()
10801            .map(|s| {
10802                if line_mode {
10803                    let start = Point::new(s.start.row, 0);
10804                    let end = Point::new(
10805                        s.end.row,
10806                        display_map
10807                            .buffer_snapshot
10808                            .line_len(MultiBufferRow(s.end.row)),
10809                    );
10810                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10811                } else {
10812                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10813                }
10814            })
10815            .collect::<Vec<_>>();
10816        self.fold_creases(ranges, true, cx);
10817    }
10818
10819    pub fn fold_creases<T: ToOffset + Clone>(
10820        &mut self,
10821        creases: Vec<Crease<T>>,
10822        auto_scroll: bool,
10823        cx: &mut ViewContext<Self>,
10824    ) {
10825        if creases.is_empty() {
10826            return;
10827        }
10828
10829        let mut buffers_affected = HashSet::default();
10830        let multi_buffer = self.buffer().read(cx);
10831        for crease in &creases {
10832            if let Some((_, buffer, _)) =
10833                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10834            {
10835                buffers_affected.insert(buffer.read(cx).remote_id());
10836            };
10837        }
10838
10839        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10840
10841        if auto_scroll {
10842            self.request_autoscroll(Autoscroll::fit(), cx);
10843        }
10844
10845        for buffer_id in buffers_affected {
10846            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10847        }
10848
10849        cx.notify();
10850
10851        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10852            // Clear diagnostics block when folding a range that contains it.
10853            let snapshot = self.snapshot(cx);
10854            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10855                drop(snapshot);
10856                self.active_diagnostics = Some(active_diagnostics);
10857                self.dismiss_diagnostics(cx);
10858            } else {
10859                self.active_diagnostics = Some(active_diagnostics);
10860            }
10861        }
10862
10863        self.scrollbar_marker_state.dirty = true;
10864    }
10865
10866    /// Removes any folds whose ranges intersect any of the given ranges.
10867    pub fn unfold_ranges<T: ToOffset + Clone>(
10868        &mut self,
10869        ranges: &[Range<T>],
10870        inclusive: bool,
10871        auto_scroll: bool,
10872        cx: &mut ViewContext<Self>,
10873    ) {
10874        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10875            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10876        });
10877    }
10878
10879    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10880        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10881            return;
10882        }
10883        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10884            return;
10885        };
10886        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10887        self.display_map
10888            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10889        cx.emit(EditorEvent::BufferFoldToggled {
10890            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10891            folded: true,
10892        });
10893        cx.notify();
10894    }
10895
10896    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10897        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10898            return;
10899        }
10900        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10901            return;
10902        };
10903        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10904        self.display_map.update(cx, |display_map, cx| {
10905            display_map.unfold_buffer(buffer_id, cx);
10906        });
10907        cx.emit(EditorEvent::BufferFoldToggled {
10908            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10909            folded: false,
10910        });
10911        cx.notify();
10912    }
10913
10914    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10915        self.display_map.read(cx).buffer_folded(buffer)
10916    }
10917
10918    /// Removes any folds with the given ranges.
10919    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10920        &mut self,
10921        ranges: &[Range<T>],
10922        type_id: TypeId,
10923        auto_scroll: bool,
10924        cx: &mut ViewContext<Self>,
10925    ) {
10926        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10927            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10928        });
10929    }
10930
10931    fn remove_folds_with<T: ToOffset + Clone>(
10932        &mut self,
10933        ranges: &[Range<T>],
10934        auto_scroll: bool,
10935        cx: &mut ViewContext<Self>,
10936        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10937    ) {
10938        if ranges.is_empty() {
10939            return;
10940        }
10941
10942        let mut buffers_affected = HashSet::default();
10943        let multi_buffer = self.buffer().read(cx);
10944        for range in ranges {
10945            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10946                buffers_affected.insert(buffer.read(cx).remote_id());
10947            };
10948        }
10949
10950        self.display_map.update(cx, update);
10951
10952        if auto_scroll {
10953            self.request_autoscroll(Autoscroll::fit(), cx);
10954        }
10955
10956        for buffer_id in buffers_affected {
10957            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10958        }
10959
10960        cx.notify();
10961        self.scrollbar_marker_state.dirty = true;
10962        self.active_indent_guides_state.dirty = true;
10963    }
10964
10965    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10966        self.display_map.read(cx).fold_placeholder.clone()
10967    }
10968
10969    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10970        if hovered != self.gutter_hovered {
10971            self.gutter_hovered = hovered;
10972            cx.notify();
10973        }
10974    }
10975
10976    pub fn insert_blocks(
10977        &mut self,
10978        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10979        autoscroll: Option<Autoscroll>,
10980        cx: &mut ViewContext<Self>,
10981    ) -> Vec<CustomBlockId> {
10982        let blocks = self
10983            .display_map
10984            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10985        if let Some(autoscroll) = autoscroll {
10986            self.request_autoscroll(autoscroll, cx);
10987        }
10988        cx.notify();
10989        blocks
10990    }
10991
10992    pub fn resize_blocks(
10993        &mut self,
10994        heights: HashMap<CustomBlockId, u32>,
10995        autoscroll: Option<Autoscroll>,
10996        cx: &mut ViewContext<Self>,
10997    ) {
10998        self.display_map
10999            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11000        if let Some(autoscroll) = autoscroll {
11001            self.request_autoscroll(autoscroll, cx);
11002        }
11003        cx.notify();
11004    }
11005
11006    pub fn replace_blocks(
11007        &mut self,
11008        renderers: HashMap<CustomBlockId, RenderBlock>,
11009        autoscroll: Option<Autoscroll>,
11010        cx: &mut ViewContext<Self>,
11011    ) {
11012        self.display_map
11013            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11014        if let Some(autoscroll) = autoscroll {
11015            self.request_autoscroll(autoscroll, cx);
11016        }
11017        cx.notify();
11018    }
11019
11020    pub fn remove_blocks(
11021        &mut self,
11022        block_ids: HashSet<CustomBlockId>,
11023        autoscroll: Option<Autoscroll>,
11024        cx: &mut ViewContext<Self>,
11025    ) {
11026        self.display_map.update(cx, |display_map, cx| {
11027            display_map.remove_blocks(block_ids, cx)
11028        });
11029        if let Some(autoscroll) = autoscroll {
11030            self.request_autoscroll(autoscroll, cx);
11031        }
11032        cx.notify();
11033    }
11034
11035    pub fn row_for_block(
11036        &self,
11037        block_id: CustomBlockId,
11038        cx: &mut ViewContext<Self>,
11039    ) -> Option<DisplayRow> {
11040        self.display_map
11041            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11042    }
11043
11044    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11045        self.focused_block = Some(focused_block);
11046    }
11047
11048    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11049        self.focused_block.take()
11050    }
11051
11052    pub fn insert_creases(
11053        &mut self,
11054        creases: impl IntoIterator<Item = Crease<Anchor>>,
11055        cx: &mut ViewContext<Self>,
11056    ) -> Vec<CreaseId> {
11057        self.display_map
11058            .update(cx, |map, cx| map.insert_creases(creases, cx))
11059    }
11060
11061    pub fn remove_creases(
11062        &mut self,
11063        ids: impl IntoIterator<Item = CreaseId>,
11064        cx: &mut ViewContext<Self>,
11065    ) {
11066        self.display_map
11067            .update(cx, |map, cx| map.remove_creases(ids, cx));
11068    }
11069
11070    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11071        self.display_map
11072            .update(cx, |map, cx| map.snapshot(cx))
11073            .longest_row()
11074    }
11075
11076    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11077        self.display_map
11078            .update(cx, |map, cx| map.snapshot(cx))
11079            .max_point()
11080    }
11081
11082    pub fn text(&self, cx: &AppContext) -> String {
11083        self.buffer.read(cx).read(cx).text()
11084    }
11085
11086    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11087        let text = self.text(cx);
11088        let text = text.trim();
11089
11090        if text.is_empty() {
11091            return None;
11092        }
11093
11094        Some(text.to_string())
11095    }
11096
11097    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11098        self.transact(cx, |this, cx| {
11099            this.buffer
11100                .read(cx)
11101                .as_singleton()
11102                .expect("you can only call set_text on editors for singleton buffers")
11103                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11104        });
11105    }
11106
11107    pub fn display_text(&self, cx: &mut AppContext) -> String {
11108        self.display_map
11109            .update(cx, |map, cx| map.snapshot(cx))
11110            .text()
11111    }
11112
11113    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11114        let mut wrap_guides = smallvec::smallvec![];
11115
11116        if self.show_wrap_guides == Some(false) {
11117            return wrap_guides;
11118        }
11119
11120        let settings = self.buffer.read(cx).settings_at(0, cx);
11121        if settings.show_wrap_guides {
11122            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11123                wrap_guides.push((soft_wrap as usize, true));
11124            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11125                wrap_guides.push((soft_wrap as usize, true));
11126            }
11127            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11128        }
11129
11130        wrap_guides
11131    }
11132
11133    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11134        let settings = self.buffer.read(cx).settings_at(0, cx);
11135        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11136        match mode {
11137            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11138                SoftWrap::None
11139            }
11140            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11141            language_settings::SoftWrap::PreferredLineLength => {
11142                SoftWrap::Column(settings.preferred_line_length)
11143            }
11144            language_settings::SoftWrap::Bounded => {
11145                SoftWrap::Bounded(settings.preferred_line_length)
11146            }
11147        }
11148    }
11149
11150    pub fn set_soft_wrap_mode(
11151        &mut self,
11152        mode: language_settings::SoftWrap,
11153        cx: &mut ViewContext<Self>,
11154    ) {
11155        self.soft_wrap_mode_override = Some(mode);
11156        cx.notify();
11157    }
11158
11159    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11160        self.text_style_refinement = Some(style);
11161    }
11162
11163    /// called by the Element so we know what style we were most recently rendered with.
11164    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11165        let rem_size = cx.rem_size();
11166        self.display_map.update(cx, |map, cx| {
11167            map.set_font(
11168                style.text.font(),
11169                style.text.font_size.to_pixels(rem_size),
11170                cx,
11171            )
11172        });
11173        self.style = Some(style);
11174    }
11175
11176    pub fn style(&self) -> Option<&EditorStyle> {
11177        self.style.as_ref()
11178    }
11179
11180    // Called by the element. This method is not designed to be called outside of the editor
11181    // element's layout code because it does not notify when rewrapping is computed synchronously.
11182    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11183        self.display_map
11184            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11185    }
11186
11187    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11188        if self.soft_wrap_mode_override.is_some() {
11189            self.soft_wrap_mode_override.take();
11190        } else {
11191            let soft_wrap = match self.soft_wrap_mode(cx) {
11192                SoftWrap::GitDiff => return,
11193                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11194                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11195                    language_settings::SoftWrap::None
11196                }
11197            };
11198            self.soft_wrap_mode_override = Some(soft_wrap);
11199        }
11200        cx.notify();
11201    }
11202
11203    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11204        let Some(workspace) = self.workspace() else {
11205            return;
11206        };
11207        let fs = workspace.read(cx).app_state().fs.clone();
11208        let current_show = TabBarSettings::get_global(cx).show;
11209        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11210            setting.show = Some(!current_show);
11211        });
11212    }
11213
11214    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11215        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11216            self.buffer
11217                .read(cx)
11218                .settings_at(0, cx)
11219                .indent_guides
11220                .enabled
11221        });
11222        self.show_indent_guides = Some(!currently_enabled);
11223        cx.notify();
11224    }
11225
11226    fn should_show_indent_guides(&self) -> Option<bool> {
11227        self.show_indent_guides
11228    }
11229
11230    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11231        let mut editor_settings = EditorSettings::get_global(cx).clone();
11232        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11233        EditorSettings::override_global(editor_settings, cx);
11234    }
11235
11236    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11237        self.use_relative_line_numbers
11238            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11239    }
11240
11241    pub fn toggle_relative_line_numbers(
11242        &mut self,
11243        _: &ToggleRelativeLineNumbers,
11244        cx: &mut ViewContext<Self>,
11245    ) {
11246        let is_relative = self.should_use_relative_line_numbers(cx);
11247        self.set_relative_line_number(Some(!is_relative), cx)
11248    }
11249
11250    pub fn set_relative_line_number(
11251        &mut self,
11252        is_relative: Option<bool>,
11253        cx: &mut ViewContext<Self>,
11254    ) {
11255        self.use_relative_line_numbers = is_relative;
11256        cx.notify();
11257    }
11258
11259    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11260        self.show_gutter = show_gutter;
11261        cx.notify();
11262    }
11263
11264    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11265        self.show_line_numbers = Some(show_line_numbers);
11266        cx.notify();
11267    }
11268
11269    pub fn set_show_git_diff_gutter(
11270        &mut self,
11271        show_git_diff_gutter: bool,
11272        cx: &mut ViewContext<Self>,
11273    ) {
11274        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11275        cx.notify();
11276    }
11277
11278    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11279        self.show_code_actions = Some(show_code_actions);
11280        cx.notify();
11281    }
11282
11283    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11284        self.show_runnables = Some(show_runnables);
11285        cx.notify();
11286    }
11287
11288    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11289        if self.display_map.read(cx).masked != masked {
11290            self.display_map.update(cx, |map, _| map.masked = masked);
11291        }
11292        cx.notify()
11293    }
11294
11295    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11296        self.show_wrap_guides = Some(show_wrap_guides);
11297        cx.notify();
11298    }
11299
11300    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11301        self.show_indent_guides = Some(show_indent_guides);
11302        cx.notify();
11303    }
11304
11305    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11306        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11307            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11308                if let Some(dir) = file.abs_path(cx).parent() {
11309                    return Some(dir.to_owned());
11310                }
11311            }
11312
11313            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11314                return Some(project_path.path.to_path_buf());
11315            }
11316        }
11317
11318        None
11319    }
11320
11321    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11322        self.active_excerpt(cx)?
11323            .1
11324            .read(cx)
11325            .file()
11326            .and_then(|f| f.as_local())
11327    }
11328
11329    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11330        if let Some(target) = self.target_file(cx) {
11331            cx.reveal_path(&target.abs_path(cx));
11332        }
11333    }
11334
11335    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11336        if let Some(file) = self.target_file(cx) {
11337            if let Some(path) = file.abs_path(cx).to_str() {
11338                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11339            }
11340        }
11341    }
11342
11343    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11344        if let Some(file) = self.target_file(cx) {
11345            if let Some(path) = file.path().to_str() {
11346                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11347            }
11348        }
11349    }
11350
11351    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11352        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11353
11354        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11355            self.start_git_blame(true, cx);
11356        }
11357
11358        cx.notify();
11359    }
11360
11361    pub fn toggle_git_blame_inline(
11362        &mut self,
11363        _: &ToggleGitBlameInline,
11364        cx: &mut ViewContext<Self>,
11365    ) {
11366        self.toggle_git_blame_inline_internal(true, cx);
11367        cx.notify();
11368    }
11369
11370    pub fn git_blame_inline_enabled(&self) -> bool {
11371        self.git_blame_inline_enabled
11372    }
11373
11374    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11375        self.show_selection_menu = self
11376            .show_selection_menu
11377            .map(|show_selections_menu| !show_selections_menu)
11378            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11379
11380        cx.notify();
11381    }
11382
11383    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11384        self.show_selection_menu
11385            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11386    }
11387
11388    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11389        if let Some(project) = self.project.as_ref() {
11390            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11391                return;
11392            };
11393
11394            if buffer.read(cx).file().is_none() {
11395                return;
11396            }
11397
11398            let focused = self.focus_handle(cx).contains_focused(cx);
11399
11400            let project = project.clone();
11401            let blame =
11402                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11403            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11404            self.blame = Some(blame);
11405        }
11406    }
11407
11408    fn toggle_git_blame_inline_internal(
11409        &mut self,
11410        user_triggered: bool,
11411        cx: &mut ViewContext<Self>,
11412    ) {
11413        if self.git_blame_inline_enabled {
11414            self.git_blame_inline_enabled = false;
11415            self.show_git_blame_inline = false;
11416            self.show_git_blame_inline_delay_task.take();
11417        } else {
11418            self.git_blame_inline_enabled = true;
11419            self.start_git_blame_inline(user_triggered, cx);
11420        }
11421
11422        cx.notify();
11423    }
11424
11425    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11426        self.start_git_blame(user_triggered, cx);
11427
11428        if ProjectSettings::get_global(cx)
11429            .git
11430            .inline_blame_delay()
11431            .is_some()
11432        {
11433            self.start_inline_blame_timer(cx);
11434        } else {
11435            self.show_git_blame_inline = true
11436        }
11437    }
11438
11439    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11440        self.blame.as_ref()
11441    }
11442
11443    pub fn show_git_blame_gutter(&self) -> bool {
11444        self.show_git_blame_gutter
11445    }
11446
11447    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11448        self.show_git_blame_gutter && self.has_blame_entries(cx)
11449    }
11450
11451    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11452        self.show_git_blame_inline
11453            && self.focus_handle.is_focused(cx)
11454            && !self.newest_selection_head_on_empty_line(cx)
11455            && self.has_blame_entries(cx)
11456    }
11457
11458    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11459        self.blame()
11460            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11461    }
11462
11463    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11464        let cursor_anchor = self.selections.newest_anchor().head();
11465
11466        let snapshot = self.buffer.read(cx).snapshot(cx);
11467        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11468
11469        snapshot.line_len(buffer_row) == 0
11470    }
11471
11472    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11473        let buffer_and_selection = maybe!({
11474            let selection = self.selections.newest::<Point>(cx);
11475            let selection_range = selection.range();
11476
11477            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11478                (buffer, selection_range.start.row..selection_range.end.row)
11479            } else {
11480                let buffer_ranges = self
11481                    .buffer()
11482                    .read(cx)
11483                    .range_to_buffer_ranges(selection_range, cx);
11484
11485                let (buffer, range, _) = if selection.reversed {
11486                    buffer_ranges.first()
11487                } else {
11488                    buffer_ranges.last()
11489                }?;
11490
11491                let snapshot = buffer.read(cx).snapshot();
11492                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11493                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11494                (buffer.clone(), selection)
11495            };
11496
11497            Some((buffer, selection))
11498        });
11499
11500        let Some((buffer, selection)) = buffer_and_selection else {
11501            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11502        };
11503
11504        let Some(project) = self.project.as_ref() else {
11505            return Task::ready(Err(anyhow!("editor does not have project")));
11506        };
11507
11508        project.update(cx, |project, cx| {
11509            project.get_permalink_to_line(&buffer, selection, cx)
11510        })
11511    }
11512
11513    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11514        let permalink_task = self.get_permalink_to_line(cx);
11515        let workspace = self.workspace();
11516
11517        cx.spawn(|_, mut cx| async move {
11518            match permalink_task.await {
11519                Ok(permalink) => {
11520                    cx.update(|cx| {
11521                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11522                    })
11523                    .ok();
11524                }
11525                Err(err) => {
11526                    let message = format!("Failed to copy permalink: {err}");
11527
11528                    Err::<(), anyhow::Error>(err).log_err();
11529
11530                    if let Some(workspace) = workspace {
11531                        workspace
11532                            .update(&mut cx, |workspace, cx| {
11533                                struct CopyPermalinkToLine;
11534
11535                                workspace.show_toast(
11536                                    Toast::new(
11537                                        NotificationId::unique::<CopyPermalinkToLine>(),
11538                                        message,
11539                                    ),
11540                                    cx,
11541                                )
11542                            })
11543                            .ok();
11544                    }
11545                }
11546            }
11547        })
11548        .detach();
11549    }
11550
11551    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11552        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11553        if let Some(file) = self.target_file(cx) {
11554            if let Some(path) = file.path().to_str() {
11555                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11556            }
11557        }
11558    }
11559
11560    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11561        let permalink_task = self.get_permalink_to_line(cx);
11562        let workspace = self.workspace();
11563
11564        cx.spawn(|_, mut cx| async move {
11565            match permalink_task.await {
11566                Ok(permalink) => {
11567                    cx.update(|cx| {
11568                        cx.open_url(permalink.as_ref());
11569                    })
11570                    .ok();
11571                }
11572                Err(err) => {
11573                    let message = format!("Failed to open permalink: {err}");
11574
11575                    Err::<(), anyhow::Error>(err).log_err();
11576
11577                    if let Some(workspace) = workspace {
11578                        workspace
11579                            .update(&mut cx, |workspace, cx| {
11580                                struct OpenPermalinkToLine;
11581
11582                                workspace.show_toast(
11583                                    Toast::new(
11584                                        NotificationId::unique::<OpenPermalinkToLine>(),
11585                                        message,
11586                                    ),
11587                                    cx,
11588                                )
11589                            })
11590                            .ok();
11591                    }
11592                }
11593            }
11594        })
11595        .detach();
11596    }
11597
11598    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11599        self.insert_uuid(UuidVersion::V4, cx);
11600    }
11601
11602    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11603        self.insert_uuid(UuidVersion::V7, cx);
11604    }
11605
11606    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11607        self.transact(cx, |this, cx| {
11608            let edits = this
11609                .selections
11610                .all::<Point>(cx)
11611                .into_iter()
11612                .map(|selection| {
11613                    let uuid = match version {
11614                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11615                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11616                    };
11617
11618                    (selection.range(), uuid.to_string())
11619                });
11620            this.edit(edits, cx);
11621            this.refresh_inline_completion(true, false, cx);
11622        });
11623    }
11624
11625    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11626    /// last highlight added will be used.
11627    ///
11628    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11629    pub fn highlight_rows<T: 'static>(
11630        &mut self,
11631        range: Range<Anchor>,
11632        color: Hsla,
11633        should_autoscroll: bool,
11634        cx: &mut ViewContext<Self>,
11635    ) {
11636        let snapshot = self.buffer().read(cx).snapshot(cx);
11637        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11638        let ix = row_highlights.binary_search_by(|highlight| {
11639            Ordering::Equal
11640                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11641                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11642        });
11643
11644        if let Err(mut ix) = ix {
11645            let index = post_inc(&mut self.highlight_order);
11646
11647            // If this range intersects with the preceding highlight, then merge it with
11648            // the preceding highlight. Otherwise insert a new highlight.
11649            let mut merged = false;
11650            if ix > 0 {
11651                let prev_highlight = &mut row_highlights[ix - 1];
11652                if prev_highlight
11653                    .range
11654                    .end
11655                    .cmp(&range.start, &snapshot)
11656                    .is_ge()
11657                {
11658                    ix -= 1;
11659                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11660                        prev_highlight.range.end = range.end;
11661                    }
11662                    merged = true;
11663                    prev_highlight.index = index;
11664                    prev_highlight.color = color;
11665                    prev_highlight.should_autoscroll = should_autoscroll;
11666                }
11667            }
11668
11669            if !merged {
11670                row_highlights.insert(
11671                    ix,
11672                    RowHighlight {
11673                        range: range.clone(),
11674                        index,
11675                        color,
11676                        should_autoscroll,
11677                    },
11678                );
11679            }
11680
11681            // If any of the following highlights intersect with this one, merge them.
11682            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11683                let highlight = &row_highlights[ix];
11684                if next_highlight
11685                    .range
11686                    .start
11687                    .cmp(&highlight.range.end, &snapshot)
11688                    .is_le()
11689                {
11690                    if next_highlight
11691                        .range
11692                        .end
11693                        .cmp(&highlight.range.end, &snapshot)
11694                        .is_gt()
11695                    {
11696                        row_highlights[ix].range.end = next_highlight.range.end;
11697                    }
11698                    row_highlights.remove(ix + 1);
11699                } else {
11700                    break;
11701                }
11702            }
11703        }
11704    }
11705
11706    /// Remove any highlighted row ranges of the given type that intersect the
11707    /// given ranges.
11708    pub fn remove_highlighted_rows<T: 'static>(
11709        &mut self,
11710        ranges_to_remove: Vec<Range<Anchor>>,
11711        cx: &mut ViewContext<Self>,
11712    ) {
11713        let snapshot = self.buffer().read(cx).snapshot(cx);
11714        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11715        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11716        row_highlights.retain(|highlight| {
11717            while let Some(range_to_remove) = ranges_to_remove.peek() {
11718                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11719                    Ordering::Less | Ordering::Equal => {
11720                        ranges_to_remove.next();
11721                    }
11722                    Ordering::Greater => {
11723                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11724                            Ordering::Less | Ordering::Equal => {
11725                                return false;
11726                            }
11727                            Ordering::Greater => break,
11728                        }
11729                    }
11730                }
11731            }
11732
11733            true
11734        })
11735    }
11736
11737    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11738    pub fn clear_row_highlights<T: 'static>(&mut self) {
11739        self.highlighted_rows.remove(&TypeId::of::<T>());
11740    }
11741
11742    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11743    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11744        self.highlighted_rows
11745            .get(&TypeId::of::<T>())
11746            .map_or(&[] as &[_], |vec| vec.as_slice())
11747            .iter()
11748            .map(|highlight| (highlight.range.clone(), highlight.color))
11749    }
11750
11751    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11752    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11753    /// Allows to ignore certain kinds of highlights.
11754    pub fn highlighted_display_rows(
11755        &mut self,
11756        cx: &mut WindowContext,
11757    ) -> BTreeMap<DisplayRow, Hsla> {
11758        let snapshot = self.snapshot(cx);
11759        let mut used_highlight_orders = HashMap::default();
11760        self.highlighted_rows
11761            .iter()
11762            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11763            .fold(
11764                BTreeMap::<DisplayRow, Hsla>::new(),
11765                |mut unique_rows, highlight| {
11766                    let start = highlight.range.start.to_display_point(&snapshot);
11767                    let end = highlight.range.end.to_display_point(&snapshot);
11768                    let start_row = start.row().0;
11769                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11770                        && end.column() == 0
11771                    {
11772                        end.row().0.saturating_sub(1)
11773                    } else {
11774                        end.row().0
11775                    };
11776                    for row in start_row..=end_row {
11777                        let used_index =
11778                            used_highlight_orders.entry(row).or_insert(highlight.index);
11779                        if highlight.index >= *used_index {
11780                            *used_index = highlight.index;
11781                            unique_rows.insert(DisplayRow(row), highlight.color);
11782                        }
11783                    }
11784                    unique_rows
11785                },
11786            )
11787    }
11788
11789    pub fn highlighted_display_row_for_autoscroll(
11790        &self,
11791        snapshot: &DisplaySnapshot,
11792    ) -> Option<DisplayRow> {
11793        self.highlighted_rows
11794            .values()
11795            .flat_map(|highlighted_rows| highlighted_rows.iter())
11796            .filter_map(|highlight| {
11797                if highlight.should_autoscroll {
11798                    Some(highlight.range.start.to_display_point(snapshot).row())
11799                } else {
11800                    None
11801                }
11802            })
11803            .min()
11804    }
11805
11806    pub fn set_search_within_ranges(
11807        &mut self,
11808        ranges: &[Range<Anchor>],
11809        cx: &mut ViewContext<Self>,
11810    ) {
11811        self.highlight_background::<SearchWithinRange>(
11812            ranges,
11813            |colors| colors.editor_document_highlight_read_background,
11814            cx,
11815        )
11816    }
11817
11818    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11819        self.breadcrumb_header = Some(new_header);
11820    }
11821
11822    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11823        self.clear_background_highlights::<SearchWithinRange>(cx);
11824    }
11825
11826    pub fn highlight_background<T: 'static>(
11827        &mut self,
11828        ranges: &[Range<Anchor>],
11829        color_fetcher: fn(&ThemeColors) -> Hsla,
11830        cx: &mut ViewContext<Self>,
11831    ) {
11832        self.background_highlights
11833            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11834        self.scrollbar_marker_state.dirty = true;
11835        cx.notify();
11836    }
11837
11838    pub fn clear_background_highlights<T: 'static>(
11839        &mut self,
11840        cx: &mut ViewContext<Self>,
11841    ) -> Option<BackgroundHighlight> {
11842        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11843        if !text_highlights.1.is_empty() {
11844            self.scrollbar_marker_state.dirty = true;
11845            cx.notify();
11846        }
11847        Some(text_highlights)
11848    }
11849
11850    pub fn highlight_gutter<T: 'static>(
11851        &mut self,
11852        ranges: &[Range<Anchor>],
11853        color_fetcher: fn(&AppContext) -> Hsla,
11854        cx: &mut ViewContext<Self>,
11855    ) {
11856        self.gutter_highlights
11857            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11858        cx.notify();
11859    }
11860
11861    pub fn clear_gutter_highlights<T: 'static>(
11862        &mut self,
11863        cx: &mut ViewContext<Self>,
11864    ) -> Option<GutterHighlight> {
11865        cx.notify();
11866        self.gutter_highlights.remove(&TypeId::of::<T>())
11867    }
11868
11869    #[cfg(feature = "test-support")]
11870    pub fn all_text_background_highlights(
11871        &mut self,
11872        cx: &mut ViewContext<Self>,
11873    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11874        let snapshot = self.snapshot(cx);
11875        let buffer = &snapshot.buffer_snapshot;
11876        let start = buffer.anchor_before(0);
11877        let end = buffer.anchor_after(buffer.len());
11878        let theme = cx.theme().colors();
11879        self.background_highlights_in_range(start..end, &snapshot, theme)
11880    }
11881
11882    #[cfg(feature = "test-support")]
11883    pub fn search_background_highlights(
11884        &mut self,
11885        cx: &mut ViewContext<Self>,
11886    ) -> Vec<Range<Point>> {
11887        let snapshot = self.buffer().read(cx).snapshot(cx);
11888
11889        let highlights = self
11890            .background_highlights
11891            .get(&TypeId::of::<items::BufferSearchHighlights>());
11892
11893        if let Some((_color, ranges)) = highlights {
11894            ranges
11895                .iter()
11896                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11897                .collect_vec()
11898        } else {
11899            vec![]
11900        }
11901    }
11902
11903    fn document_highlights_for_position<'a>(
11904        &'a self,
11905        position: Anchor,
11906        buffer: &'a MultiBufferSnapshot,
11907    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11908        let read_highlights = self
11909            .background_highlights
11910            .get(&TypeId::of::<DocumentHighlightRead>())
11911            .map(|h| &h.1);
11912        let write_highlights = self
11913            .background_highlights
11914            .get(&TypeId::of::<DocumentHighlightWrite>())
11915            .map(|h| &h.1);
11916        let left_position = position.bias_left(buffer);
11917        let right_position = position.bias_right(buffer);
11918        read_highlights
11919            .into_iter()
11920            .chain(write_highlights)
11921            .flat_map(move |ranges| {
11922                let start_ix = match ranges.binary_search_by(|probe| {
11923                    let cmp = probe.end.cmp(&left_position, buffer);
11924                    if cmp.is_ge() {
11925                        Ordering::Greater
11926                    } else {
11927                        Ordering::Less
11928                    }
11929                }) {
11930                    Ok(i) | Err(i) => i,
11931                };
11932
11933                ranges[start_ix..]
11934                    .iter()
11935                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11936            })
11937    }
11938
11939    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11940        self.background_highlights
11941            .get(&TypeId::of::<T>())
11942            .map_or(false, |(_, highlights)| !highlights.is_empty())
11943    }
11944
11945    pub fn background_highlights_in_range(
11946        &self,
11947        search_range: Range<Anchor>,
11948        display_snapshot: &DisplaySnapshot,
11949        theme: &ThemeColors,
11950    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11951        let mut results = Vec::new();
11952        for (color_fetcher, ranges) in self.background_highlights.values() {
11953            let color = color_fetcher(theme);
11954            let start_ix = match ranges.binary_search_by(|probe| {
11955                let cmp = probe
11956                    .end
11957                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11958                if cmp.is_gt() {
11959                    Ordering::Greater
11960                } else {
11961                    Ordering::Less
11962                }
11963            }) {
11964                Ok(i) | Err(i) => i,
11965            };
11966            for range in &ranges[start_ix..] {
11967                if range
11968                    .start
11969                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11970                    .is_ge()
11971                {
11972                    break;
11973                }
11974
11975                let start = range.start.to_display_point(display_snapshot);
11976                let end = range.end.to_display_point(display_snapshot);
11977                results.push((start..end, color))
11978            }
11979        }
11980        results
11981    }
11982
11983    pub fn background_highlight_row_ranges<T: 'static>(
11984        &self,
11985        search_range: Range<Anchor>,
11986        display_snapshot: &DisplaySnapshot,
11987        count: usize,
11988    ) -> Vec<RangeInclusive<DisplayPoint>> {
11989        let mut results = Vec::new();
11990        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11991            return vec![];
11992        };
11993
11994        let start_ix = match ranges.binary_search_by(|probe| {
11995            let cmp = probe
11996                .end
11997                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11998            if cmp.is_gt() {
11999                Ordering::Greater
12000            } else {
12001                Ordering::Less
12002            }
12003        }) {
12004            Ok(i) | Err(i) => i,
12005        };
12006        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12007            if let (Some(start_display), Some(end_display)) = (start, end) {
12008                results.push(
12009                    start_display.to_display_point(display_snapshot)
12010                        ..=end_display.to_display_point(display_snapshot),
12011                );
12012            }
12013        };
12014        let mut start_row: Option<Point> = None;
12015        let mut end_row: Option<Point> = None;
12016        if ranges.len() > count {
12017            return Vec::new();
12018        }
12019        for range in &ranges[start_ix..] {
12020            if range
12021                .start
12022                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12023                .is_ge()
12024            {
12025                break;
12026            }
12027            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12028            if let Some(current_row) = &end_row {
12029                if end.row == current_row.row {
12030                    continue;
12031                }
12032            }
12033            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12034            if start_row.is_none() {
12035                assert_eq!(end_row, None);
12036                start_row = Some(start);
12037                end_row = Some(end);
12038                continue;
12039            }
12040            if let Some(current_end) = end_row.as_mut() {
12041                if start.row > current_end.row + 1 {
12042                    push_region(start_row, end_row);
12043                    start_row = Some(start);
12044                    end_row = Some(end);
12045                } else {
12046                    // Merge two hunks.
12047                    *current_end = end;
12048                }
12049            } else {
12050                unreachable!();
12051            }
12052        }
12053        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12054        push_region(start_row, end_row);
12055        results
12056    }
12057
12058    pub fn gutter_highlights_in_range(
12059        &self,
12060        search_range: Range<Anchor>,
12061        display_snapshot: &DisplaySnapshot,
12062        cx: &AppContext,
12063    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12064        let mut results = Vec::new();
12065        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12066            let color = color_fetcher(cx);
12067            let start_ix = match ranges.binary_search_by(|probe| {
12068                let cmp = probe
12069                    .end
12070                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12071                if cmp.is_gt() {
12072                    Ordering::Greater
12073                } else {
12074                    Ordering::Less
12075                }
12076            }) {
12077                Ok(i) | Err(i) => i,
12078            };
12079            for range in &ranges[start_ix..] {
12080                if range
12081                    .start
12082                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12083                    .is_ge()
12084                {
12085                    break;
12086                }
12087
12088                let start = range.start.to_display_point(display_snapshot);
12089                let end = range.end.to_display_point(display_snapshot);
12090                results.push((start..end, color))
12091            }
12092        }
12093        results
12094    }
12095
12096    /// Get the text ranges corresponding to the redaction query
12097    pub fn redacted_ranges(
12098        &self,
12099        search_range: Range<Anchor>,
12100        display_snapshot: &DisplaySnapshot,
12101        cx: &WindowContext,
12102    ) -> Vec<Range<DisplayPoint>> {
12103        display_snapshot
12104            .buffer_snapshot
12105            .redacted_ranges(search_range, |file| {
12106                if let Some(file) = file {
12107                    file.is_private()
12108                        && EditorSettings::get(
12109                            Some(SettingsLocation {
12110                                worktree_id: file.worktree_id(cx),
12111                                path: file.path().as_ref(),
12112                            }),
12113                            cx,
12114                        )
12115                        .redact_private_values
12116                } else {
12117                    false
12118                }
12119            })
12120            .map(|range| {
12121                range.start.to_display_point(display_snapshot)
12122                    ..range.end.to_display_point(display_snapshot)
12123            })
12124            .collect()
12125    }
12126
12127    pub fn highlight_text<T: 'static>(
12128        &mut self,
12129        ranges: Vec<Range<Anchor>>,
12130        style: HighlightStyle,
12131        cx: &mut ViewContext<Self>,
12132    ) {
12133        self.display_map.update(cx, |map, _| {
12134            map.highlight_text(TypeId::of::<T>(), ranges, style)
12135        });
12136        cx.notify();
12137    }
12138
12139    pub(crate) fn highlight_inlays<T: 'static>(
12140        &mut self,
12141        highlights: Vec<InlayHighlight>,
12142        style: HighlightStyle,
12143        cx: &mut ViewContext<Self>,
12144    ) {
12145        self.display_map.update(cx, |map, _| {
12146            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12147        });
12148        cx.notify();
12149    }
12150
12151    pub fn text_highlights<'a, T: 'static>(
12152        &'a self,
12153        cx: &'a AppContext,
12154    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12155        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12156    }
12157
12158    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12159        let cleared = self
12160            .display_map
12161            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12162        if cleared {
12163            cx.notify();
12164        }
12165    }
12166
12167    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12168        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12169            && self.focus_handle.is_focused(cx)
12170    }
12171
12172    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12173        self.show_cursor_when_unfocused = is_enabled;
12174        cx.notify();
12175    }
12176
12177    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12178        self.project
12179            .as_ref()
12180            .map(|project| project.read(cx).lsp_store())
12181    }
12182
12183    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12184        cx.notify();
12185    }
12186
12187    fn on_buffer_event(
12188        &mut self,
12189        multibuffer: Model<MultiBuffer>,
12190        event: &multi_buffer::Event,
12191        cx: &mut ViewContext<Self>,
12192    ) {
12193        match event {
12194            multi_buffer::Event::Edited {
12195                singleton_buffer_edited,
12196                edited_buffer: buffer_edited,
12197            } => {
12198                self.scrollbar_marker_state.dirty = true;
12199                self.active_indent_guides_state.dirty = true;
12200                self.refresh_active_diagnostics(cx);
12201                self.refresh_code_actions(cx);
12202                if self.has_active_inline_completion() {
12203                    self.update_visible_inline_completion(cx);
12204                }
12205                if let Some(buffer) = buffer_edited {
12206                    let buffer_id = buffer.read(cx).remote_id();
12207                    if !self.registered_buffers.contains_key(&buffer_id) {
12208                        if let Some(lsp_store) = self.lsp_store(cx) {
12209                            lsp_store.update(cx, |lsp_store, cx| {
12210                                self.registered_buffers.insert(
12211                                    buffer_id,
12212                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12213                                );
12214                            })
12215                        }
12216                    }
12217                }
12218                cx.emit(EditorEvent::BufferEdited);
12219                cx.emit(SearchEvent::MatchesInvalidated);
12220                if *singleton_buffer_edited {
12221                    if let Some(project) = &self.project {
12222                        let project = project.read(cx);
12223                        #[allow(clippy::mutable_key_type)]
12224                        let languages_affected = multibuffer
12225                            .read(cx)
12226                            .all_buffers()
12227                            .into_iter()
12228                            .filter_map(|buffer| {
12229                                let buffer = buffer.read(cx);
12230                                let language = buffer.language()?;
12231                                if project.is_local()
12232                                    && project
12233                                        .language_servers_for_local_buffer(buffer, cx)
12234                                        .count()
12235                                        == 0
12236                                {
12237                                    None
12238                                } else {
12239                                    Some(language)
12240                                }
12241                            })
12242                            .cloned()
12243                            .collect::<HashSet<_>>();
12244                        if !languages_affected.is_empty() {
12245                            self.refresh_inlay_hints(
12246                                InlayHintRefreshReason::BufferEdited(languages_affected),
12247                                cx,
12248                            );
12249                        }
12250                    }
12251                }
12252
12253                let Some(project) = &self.project else { return };
12254                let (telemetry, is_via_ssh) = {
12255                    let project = project.read(cx);
12256                    let telemetry = project.client().telemetry().clone();
12257                    let is_via_ssh = project.is_via_ssh();
12258                    (telemetry, is_via_ssh)
12259                };
12260                refresh_linked_ranges(self, cx);
12261                telemetry.log_edit_event("editor", is_via_ssh);
12262            }
12263            multi_buffer::Event::ExcerptsAdded {
12264                buffer,
12265                predecessor,
12266                excerpts,
12267            } => {
12268                self.tasks_update_task = Some(self.refresh_runnables(cx));
12269                let buffer_id = buffer.read(cx).remote_id();
12270                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12271                    if let Some(project) = &self.project {
12272                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12273                    }
12274                }
12275                cx.emit(EditorEvent::ExcerptsAdded {
12276                    buffer: buffer.clone(),
12277                    predecessor: *predecessor,
12278                    excerpts: excerpts.clone(),
12279                });
12280                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12281            }
12282            multi_buffer::Event::ExcerptsRemoved { ids } => {
12283                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12284                let buffer = self.buffer.read(cx);
12285                self.registered_buffers
12286                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12287                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12288            }
12289            multi_buffer::Event::ExcerptsEdited { ids } => {
12290                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12291            }
12292            multi_buffer::Event::ExcerptsExpanded { ids } => {
12293                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12294            }
12295            multi_buffer::Event::Reparsed(buffer_id) => {
12296                self.tasks_update_task = Some(self.refresh_runnables(cx));
12297
12298                cx.emit(EditorEvent::Reparsed(*buffer_id));
12299            }
12300            multi_buffer::Event::LanguageChanged(buffer_id) => {
12301                linked_editing_ranges::refresh_linked_ranges(self, cx);
12302                cx.emit(EditorEvent::Reparsed(*buffer_id));
12303                cx.notify();
12304            }
12305            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12306            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12307            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12308                cx.emit(EditorEvent::TitleChanged)
12309            }
12310            // multi_buffer::Event::DiffBaseChanged => {
12311            //     self.scrollbar_marker_state.dirty = true;
12312            //     cx.emit(EditorEvent::DiffBaseChanged);
12313            //     cx.notify();
12314            // }
12315            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12316            multi_buffer::Event::DiagnosticsUpdated => {
12317                self.refresh_active_diagnostics(cx);
12318                self.scrollbar_marker_state.dirty = true;
12319                cx.notify();
12320            }
12321            _ => {}
12322        };
12323    }
12324
12325    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12326        cx.notify();
12327    }
12328
12329    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12330        self.tasks_update_task = Some(self.refresh_runnables(cx));
12331        self.refresh_inline_completion(true, false, cx);
12332        self.refresh_inlay_hints(
12333            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12334                self.selections.newest_anchor().head(),
12335                &self.buffer.read(cx).snapshot(cx),
12336                cx,
12337            )),
12338            cx,
12339        );
12340
12341        let old_cursor_shape = self.cursor_shape;
12342
12343        {
12344            let editor_settings = EditorSettings::get_global(cx);
12345            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12346            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12347            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12348        }
12349
12350        if old_cursor_shape != self.cursor_shape {
12351            cx.emit(EditorEvent::CursorShapeChanged);
12352        }
12353
12354        let project_settings = ProjectSettings::get_global(cx);
12355        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12356
12357        if self.mode == EditorMode::Full {
12358            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12359            if self.git_blame_inline_enabled != inline_blame_enabled {
12360                self.toggle_git_blame_inline_internal(false, cx);
12361            }
12362        }
12363
12364        cx.notify();
12365    }
12366
12367    pub fn set_searchable(&mut self, searchable: bool) {
12368        self.searchable = searchable;
12369    }
12370
12371    pub fn searchable(&self) -> bool {
12372        self.searchable
12373    }
12374
12375    fn open_proposed_changes_editor(
12376        &mut self,
12377        _: &OpenProposedChangesEditor,
12378        cx: &mut ViewContext<Self>,
12379    ) {
12380        let Some(workspace) = self.workspace() else {
12381            cx.propagate();
12382            return;
12383        };
12384
12385        let selections = self.selections.all::<usize>(cx);
12386        let buffer = self.buffer.read(cx);
12387        let mut new_selections_by_buffer = HashMap::default();
12388        for selection in selections {
12389            for (buffer, range, _) in
12390                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12391            {
12392                let mut range = range.to_point(buffer.read(cx));
12393                range.start.column = 0;
12394                range.end.column = buffer.read(cx).line_len(range.end.row);
12395                new_selections_by_buffer
12396                    .entry(buffer)
12397                    .or_insert(Vec::new())
12398                    .push(range)
12399            }
12400        }
12401
12402        let proposed_changes_buffers = new_selections_by_buffer
12403            .into_iter()
12404            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12405            .collect::<Vec<_>>();
12406        let proposed_changes_editor = cx.new_view(|cx| {
12407            ProposedChangesEditor::new(
12408                "Proposed changes",
12409                proposed_changes_buffers,
12410                self.project.clone(),
12411                cx,
12412            )
12413        });
12414
12415        cx.window_context().defer(move |cx| {
12416            workspace.update(cx, |workspace, cx| {
12417                workspace.active_pane().update(cx, |pane, cx| {
12418                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12419                });
12420            });
12421        });
12422    }
12423
12424    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12425        self.open_excerpts_common(None, true, cx)
12426    }
12427
12428    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12429        self.open_excerpts_common(None, false, cx)
12430    }
12431
12432    fn open_excerpts_common(
12433        &mut self,
12434        jump_data: Option<JumpData>,
12435        split: bool,
12436        cx: &mut ViewContext<Self>,
12437    ) {
12438        let Some(workspace) = self.workspace() else {
12439            cx.propagate();
12440            return;
12441        };
12442
12443        if self.buffer.read(cx).is_singleton() {
12444            cx.propagate();
12445            return;
12446        }
12447
12448        let mut new_selections_by_buffer = HashMap::default();
12449        match &jump_data {
12450            Some(jump_data) => {
12451                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12452                if let Some(buffer) = multi_buffer_snapshot
12453                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12454                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12455                {
12456                    let buffer_snapshot = buffer.read(cx).snapshot();
12457                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12458                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12459                    } else {
12460                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12461                    };
12462                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12463                    new_selections_by_buffer.insert(
12464                        buffer,
12465                        (
12466                            vec![jump_to_offset..jump_to_offset],
12467                            Some(jump_data.line_offset_from_top),
12468                        ),
12469                    );
12470                }
12471            }
12472            None => {
12473                let selections = self.selections.all::<usize>(cx);
12474                let buffer = self.buffer.read(cx);
12475                for selection in selections {
12476                    for (mut buffer_handle, mut range, _) in
12477                        buffer.range_to_buffer_ranges(selection.range(), cx)
12478                    {
12479                        // When editing branch buffers, jump to the corresponding location
12480                        // in their base buffer.
12481                        let buffer = buffer_handle.read(cx);
12482                        if let Some(base_buffer) = buffer.base_buffer() {
12483                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12484                            buffer_handle = base_buffer;
12485                        }
12486
12487                        if selection.reversed {
12488                            mem::swap(&mut range.start, &mut range.end);
12489                        }
12490                        new_selections_by_buffer
12491                            .entry(buffer_handle)
12492                            .or_insert((Vec::new(), None))
12493                            .0
12494                            .push(range)
12495                    }
12496                }
12497            }
12498        }
12499
12500        if new_selections_by_buffer.is_empty() {
12501            return;
12502        }
12503
12504        // We defer the pane interaction because we ourselves are a workspace item
12505        // and activating a new item causes the pane to call a method on us reentrantly,
12506        // which panics if we're on the stack.
12507        cx.window_context().defer(move |cx| {
12508            workspace.update(cx, |workspace, cx| {
12509                let pane = if split {
12510                    workspace.adjacent_pane(cx)
12511                } else {
12512                    workspace.active_pane().clone()
12513                };
12514
12515                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12516                    let editor = buffer
12517                        .read(cx)
12518                        .file()
12519                        .is_none()
12520                        .then(|| {
12521                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12522                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12523                            // Instead, we try to activate the existing editor in the pane first.
12524                            let (editor, pane_item_index) =
12525                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12526                                    let editor = item.downcast::<Editor>()?;
12527                                    let singleton_buffer =
12528                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12529                                    if singleton_buffer == buffer {
12530                                        Some((editor, i))
12531                                    } else {
12532                                        None
12533                                    }
12534                                })?;
12535                            pane.update(cx, |pane, cx| {
12536                                pane.activate_item(pane_item_index, true, true, cx)
12537                            });
12538                            Some(editor)
12539                        })
12540                        .flatten()
12541                        .unwrap_or_else(|| {
12542                            workspace.open_project_item::<Self>(
12543                                pane.clone(),
12544                                buffer,
12545                                true,
12546                                true,
12547                                cx,
12548                            )
12549                        });
12550
12551                    editor.update(cx, |editor, cx| {
12552                        let autoscroll = match scroll_offset {
12553                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12554                            None => Autoscroll::newest(),
12555                        };
12556                        let nav_history = editor.nav_history.take();
12557                        editor.change_selections(Some(autoscroll), cx, |s| {
12558                            s.select_ranges(ranges);
12559                        });
12560                        editor.nav_history = nav_history;
12561                    });
12562                }
12563            })
12564        });
12565    }
12566
12567    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12568        let snapshot = self.buffer.read(cx).read(cx);
12569        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12570        Some(
12571            ranges
12572                .iter()
12573                .map(move |range| {
12574                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12575                })
12576                .collect(),
12577        )
12578    }
12579
12580    fn selection_replacement_ranges(
12581        &self,
12582        range: Range<OffsetUtf16>,
12583        cx: &mut AppContext,
12584    ) -> Vec<Range<OffsetUtf16>> {
12585        let selections = self.selections.all::<OffsetUtf16>(cx);
12586        let newest_selection = selections
12587            .iter()
12588            .max_by_key(|selection| selection.id)
12589            .unwrap();
12590        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12591        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12592        let snapshot = self.buffer.read(cx).read(cx);
12593        selections
12594            .into_iter()
12595            .map(|mut selection| {
12596                selection.start.0 =
12597                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12598                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12599                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12600                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12601            })
12602            .collect()
12603    }
12604
12605    fn report_editor_event(
12606        &self,
12607        event_type: &'static str,
12608        file_extension: Option<String>,
12609        cx: &AppContext,
12610    ) {
12611        if cfg!(any(test, feature = "test-support")) {
12612            return;
12613        }
12614
12615        let Some(project) = &self.project else { return };
12616
12617        // If None, we are in a file without an extension
12618        let file = self
12619            .buffer
12620            .read(cx)
12621            .as_singleton()
12622            .and_then(|b| b.read(cx).file());
12623        let file_extension = file_extension.or(file
12624            .as_ref()
12625            .and_then(|file| Path::new(file.file_name(cx)).extension())
12626            .and_then(|e| e.to_str())
12627            .map(|a| a.to_string()));
12628
12629        let vim_mode = cx
12630            .global::<SettingsStore>()
12631            .raw_user_settings()
12632            .get("vim_mode")
12633            == Some(&serde_json::Value::Bool(true));
12634
12635        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12636            == language::language_settings::InlineCompletionProvider::Copilot;
12637        let copilot_enabled_for_language = self
12638            .buffer
12639            .read(cx)
12640            .settings_at(0, cx)
12641            .show_inline_completions;
12642
12643        let project = project.read(cx);
12644        telemetry::event!(
12645            event_type,
12646            file_extension,
12647            vim_mode,
12648            copilot_enabled,
12649            copilot_enabled_for_language,
12650            is_via_ssh = project.is_via_ssh(),
12651        );
12652    }
12653
12654    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12655    /// with each line being an array of {text, highlight} objects.
12656    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12657        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12658            return;
12659        };
12660
12661        #[derive(Serialize)]
12662        struct Chunk<'a> {
12663            text: String,
12664            highlight: Option<&'a str>,
12665        }
12666
12667        let snapshot = buffer.read(cx).snapshot();
12668        let range = self
12669            .selected_text_range(false, cx)
12670            .and_then(|selection| {
12671                if selection.range.is_empty() {
12672                    None
12673                } else {
12674                    Some(selection.range)
12675                }
12676            })
12677            .unwrap_or_else(|| 0..snapshot.len());
12678
12679        let chunks = snapshot.chunks(range, true);
12680        let mut lines = Vec::new();
12681        let mut line: VecDeque<Chunk> = VecDeque::new();
12682
12683        let Some(style) = self.style.as_ref() else {
12684            return;
12685        };
12686
12687        for chunk in chunks {
12688            let highlight = chunk
12689                .syntax_highlight_id
12690                .and_then(|id| id.name(&style.syntax));
12691            let mut chunk_lines = chunk.text.split('\n').peekable();
12692            while let Some(text) = chunk_lines.next() {
12693                let mut merged_with_last_token = false;
12694                if let Some(last_token) = line.back_mut() {
12695                    if last_token.highlight == highlight {
12696                        last_token.text.push_str(text);
12697                        merged_with_last_token = true;
12698                    }
12699                }
12700
12701                if !merged_with_last_token {
12702                    line.push_back(Chunk {
12703                        text: text.into(),
12704                        highlight,
12705                    });
12706                }
12707
12708                if chunk_lines.peek().is_some() {
12709                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12710                        line.pop_front();
12711                    }
12712                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12713                        line.pop_back();
12714                    }
12715
12716                    lines.push(mem::take(&mut line));
12717                }
12718            }
12719        }
12720
12721        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12722            return;
12723        };
12724        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12725    }
12726
12727    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12728        self.request_autoscroll(Autoscroll::newest(), cx);
12729        let position = self.selections.newest_display(cx).start;
12730        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12731    }
12732
12733    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12734        &self.inlay_hint_cache
12735    }
12736
12737    pub fn replay_insert_event(
12738        &mut self,
12739        text: &str,
12740        relative_utf16_range: Option<Range<isize>>,
12741        cx: &mut ViewContext<Self>,
12742    ) {
12743        if !self.input_enabled {
12744            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12745            return;
12746        }
12747        if let Some(relative_utf16_range) = relative_utf16_range {
12748            let selections = self.selections.all::<OffsetUtf16>(cx);
12749            self.change_selections(None, cx, |s| {
12750                let new_ranges = selections.into_iter().map(|range| {
12751                    let start = OffsetUtf16(
12752                        range
12753                            .head()
12754                            .0
12755                            .saturating_add_signed(relative_utf16_range.start),
12756                    );
12757                    let end = OffsetUtf16(
12758                        range
12759                            .head()
12760                            .0
12761                            .saturating_add_signed(relative_utf16_range.end),
12762                    );
12763                    start..end
12764                });
12765                s.select_ranges(new_ranges);
12766            });
12767        }
12768
12769        self.handle_input(text, cx);
12770    }
12771
12772    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12773        let Some(provider) = self.semantics_provider.as_ref() else {
12774            return false;
12775        };
12776
12777        let mut supports = false;
12778        self.buffer().read(cx).for_each_buffer(|buffer| {
12779            supports |= provider.supports_inlay_hints(buffer, cx);
12780        });
12781        supports
12782    }
12783
12784    pub fn focus(&self, cx: &mut WindowContext) {
12785        cx.focus(&self.focus_handle)
12786    }
12787
12788    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12789        self.focus_handle.is_focused(cx)
12790    }
12791
12792    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12793        cx.emit(EditorEvent::Focused);
12794
12795        if let Some(descendant) = self
12796            .last_focused_descendant
12797            .take()
12798            .and_then(|descendant| descendant.upgrade())
12799        {
12800            cx.focus(&descendant);
12801        } else {
12802            if let Some(blame) = self.blame.as_ref() {
12803                blame.update(cx, GitBlame::focus)
12804            }
12805
12806            self.blink_manager.update(cx, BlinkManager::enable);
12807            self.show_cursor_names(cx);
12808            self.buffer.update(cx, |buffer, cx| {
12809                buffer.finalize_last_transaction(cx);
12810                if self.leader_peer_id.is_none() {
12811                    buffer.set_active_selections(
12812                        &self.selections.disjoint_anchors(),
12813                        self.selections.line_mode,
12814                        self.cursor_shape,
12815                        cx,
12816                    );
12817                }
12818            });
12819        }
12820    }
12821
12822    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12823        cx.emit(EditorEvent::FocusedIn)
12824    }
12825
12826    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12827        if event.blurred != self.focus_handle {
12828            self.last_focused_descendant = Some(event.blurred);
12829        }
12830    }
12831
12832    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12833        self.blink_manager.update(cx, BlinkManager::disable);
12834        self.buffer
12835            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12836
12837        if let Some(blame) = self.blame.as_ref() {
12838            blame.update(cx, GitBlame::blur)
12839        }
12840        if !self.hover_state.focused(cx) {
12841            hide_hover(self, cx);
12842        }
12843
12844        self.hide_context_menu(cx);
12845        cx.emit(EditorEvent::Blurred);
12846        cx.notify();
12847    }
12848
12849    pub fn register_action<A: Action>(
12850        &mut self,
12851        listener: impl Fn(&A, &mut WindowContext) + 'static,
12852    ) -> Subscription {
12853        let id = self.next_editor_action_id.post_inc();
12854        let listener = Arc::new(listener);
12855        self.editor_actions.borrow_mut().insert(
12856            id,
12857            Box::new(move |cx| {
12858                let cx = cx.window_context();
12859                let listener = listener.clone();
12860                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12861                    let action = action.downcast_ref().unwrap();
12862                    if phase == DispatchPhase::Bubble {
12863                        listener(action, cx)
12864                    }
12865                })
12866            }),
12867        );
12868
12869        let editor_actions = self.editor_actions.clone();
12870        Subscription::new(move || {
12871            editor_actions.borrow_mut().remove(&id);
12872        })
12873    }
12874
12875    pub fn file_header_size(&self) -> u32 {
12876        FILE_HEADER_HEIGHT
12877    }
12878
12879    pub fn revert(
12880        &mut self,
12881        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12882        cx: &mut ViewContext<Self>,
12883    ) {
12884        self.buffer().update(cx, |multi_buffer, cx| {
12885            for (buffer_id, changes) in revert_changes {
12886                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12887                    buffer.update(cx, |buffer, cx| {
12888                        buffer.edit(
12889                            changes.into_iter().map(|(range, text)| {
12890                                (range, text.to_string().map(Arc::<str>::from))
12891                            }),
12892                            None,
12893                            cx,
12894                        );
12895                    });
12896                }
12897            }
12898        });
12899        self.change_selections(None, cx, |selections| selections.refresh());
12900    }
12901
12902    pub fn to_pixel_point(
12903        &mut self,
12904        source: multi_buffer::Anchor,
12905        editor_snapshot: &EditorSnapshot,
12906        cx: &mut ViewContext<Self>,
12907    ) -> Option<gpui::Point<Pixels>> {
12908        let source_point = source.to_display_point(editor_snapshot);
12909        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12910    }
12911
12912    pub fn display_to_pixel_point(
12913        &self,
12914        source: DisplayPoint,
12915        editor_snapshot: &EditorSnapshot,
12916        cx: &WindowContext,
12917    ) -> Option<gpui::Point<Pixels>> {
12918        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12919        let text_layout_details = self.text_layout_details(cx);
12920        let scroll_top = text_layout_details
12921            .scroll_anchor
12922            .scroll_position(editor_snapshot)
12923            .y;
12924
12925        if source.row().as_f32() < scroll_top.floor() {
12926            return None;
12927        }
12928        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12929        let source_y = line_height * (source.row().as_f32() - scroll_top);
12930        Some(gpui::Point::new(source_x, source_y))
12931    }
12932
12933    pub fn has_active_completions_menu(&self) -> bool {
12934        self.context_menu.borrow().as_ref().map_or(false, |menu| {
12935            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12936        })
12937    }
12938
12939    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12940        self.addons
12941            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12942    }
12943
12944    pub fn unregister_addon<T: Addon>(&mut self) {
12945        self.addons.remove(&std::any::TypeId::of::<T>());
12946    }
12947
12948    pub fn addon<T: Addon>(&self) -> Option<&T> {
12949        let type_id = std::any::TypeId::of::<T>();
12950        self.addons
12951            .get(&type_id)
12952            .and_then(|item| item.to_any().downcast_ref::<T>())
12953    }
12954
12955    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12956        let text_layout_details = self.text_layout_details(cx);
12957        let style = &text_layout_details.editor_style;
12958        let font_id = cx.text_system().resolve_font(&style.text.font());
12959        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12960        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12961
12962        let em_width = cx
12963            .text_system()
12964            .typographic_bounds(font_id, font_size, 'm')
12965            .unwrap()
12966            .size
12967            .width;
12968
12969        gpui::Point::new(em_width, line_height)
12970    }
12971}
12972
12973fn get_unstaged_changes_for_buffers(
12974    project: &Model<Project>,
12975    buffers: impl IntoIterator<Item = Model<Buffer>>,
12976    cx: &mut ViewContext<Editor>,
12977) {
12978    let mut tasks = Vec::new();
12979    project.update(cx, |project, cx| {
12980        for buffer in buffers {
12981            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12982        }
12983    });
12984    cx.spawn(|this, mut cx| async move {
12985        let change_sets = futures::future::join_all(tasks).await;
12986        this.update(&mut cx, |this, cx| {
12987            for change_set in change_sets {
12988                if let Some(change_set) = change_set.log_err() {
12989                    this.diff_map.add_change_set(change_set, cx);
12990                }
12991            }
12992        })
12993        .ok();
12994    })
12995    .detach();
12996}
12997
12998fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12999    let tab_size = tab_size.get() as usize;
13000    let mut width = offset;
13001
13002    for ch in text.chars() {
13003        width += if ch == '\t' {
13004            tab_size - (width % tab_size)
13005        } else {
13006            1
13007        };
13008    }
13009
13010    width - offset
13011}
13012
13013#[cfg(test)]
13014mod tests {
13015    use super::*;
13016
13017    #[test]
13018    fn test_string_size_with_expanded_tabs() {
13019        let nz = |val| NonZeroU32::new(val).unwrap();
13020        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13021        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13022        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13023        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13024        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13025        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13026        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13027        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13028    }
13029}
13030
13031/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13032struct WordBreakingTokenizer<'a> {
13033    input: &'a str,
13034}
13035
13036impl<'a> WordBreakingTokenizer<'a> {
13037    fn new(input: &'a str) -> Self {
13038        Self { input }
13039    }
13040}
13041
13042fn is_char_ideographic(ch: char) -> bool {
13043    use unicode_script::Script::*;
13044    use unicode_script::UnicodeScript;
13045    matches!(ch.script(), Han | Tangut | Yi)
13046}
13047
13048fn is_grapheme_ideographic(text: &str) -> bool {
13049    text.chars().any(is_char_ideographic)
13050}
13051
13052fn is_grapheme_whitespace(text: &str) -> bool {
13053    text.chars().any(|x| x.is_whitespace())
13054}
13055
13056fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13057    text.chars().next().map_or(false, |ch| {
13058        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13059    })
13060}
13061
13062#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13063struct WordBreakToken<'a> {
13064    token: &'a str,
13065    grapheme_len: usize,
13066    is_whitespace: bool,
13067}
13068
13069impl<'a> Iterator for WordBreakingTokenizer<'a> {
13070    /// Yields a span, the count of graphemes in the token, and whether it was
13071    /// whitespace. Note that it also breaks at word boundaries.
13072    type Item = WordBreakToken<'a>;
13073
13074    fn next(&mut self) -> Option<Self::Item> {
13075        use unicode_segmentation::UnicodeSegmentation;
13076        if self.input.is_empty() {
13077            return None;
13078        }
13079
13080        let mut iter = self.input.graphemes(true).peekable();
13081        let mut offset = 0;
13082        let mut graphemes = 0;
13083        if let Some(first_grapheme) = iter.next() {
13084            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13085            offset += first_grapheme.len();
13086            graphemes += 1;
13087            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13088                if let Some(grapheme) = iter.peek().copied() {
13089                    if should_stay_with_preceding_ideograph(grapheme) {
13090                        offset += grapheme.len();
13091                        graphemes += 1;
13092                    }
13093                }
13094            } else {
13095                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13096                let mut next_word_bound = words.peek().copied();
13097                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13098                    next_word_bound = words.next();
13099                }
13100                while let Some(grapheme) = iter.peek().copied() {
13101                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13102                        break;
13103                    };
13104                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13105                        break;
13106                    };
13107                    offset += grapheme.len();
13108                    graphemes += 1;
13109                    iter.next();
13110                }
13111            }
13112            let token = &self.input[..offset];
13113            self.input = &self.input[offset..];
13114            if is_whitespace {
13115                Some(WordBreakToken {
13116                    token: " ",
13117                    grapheme_len: 1,
13118                    is_whitespace: true,
13119                })
13120            } else {
13121                Some(WordBreakToken {
13122                    token,
13123                    grapheme_len: graphemes,
13124                    is_whitespace: false,
13125                })
13126            }
13127        } else {
13128            None
13129        }
13130    }
13131}
13132
13133#[test]
13134fn test_word_breaking_tokenizer() {
13135    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13136        ("", &[]),
13137        ("  ", &[(" ", 1, true)]),
13138        ("Ʒ", &[("Ʒ", 1, false)]),
13139        ("Ǽ", &[("Ǽ", 1, false)]),
13140        ("", &[("", 1, false)]),
13141        ("⋑⋑", &[("⋑⋑", 2, false)]),
13142        (
13143            "原理,进而",
13144            &[
13145                ("", 1, false),
13146                ("理,", 2, false),
13147                ("", 1, false),
13148                ("", 1, false),
13149            ],
13150        ),
13151        (
13152            "hello world",
13153            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13154        ),
13155        (
13156            "hello, world",
13157            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13158        ),
13159        (
13160            "  hello world",
13161            &[
13162                (" ", 1, true),
13163                ("hello", 5, false),
13164                (" ", 1, true),
13165                ("world", 5, false),
13166            ],
13167        ),
13168        (
13169            "这是什么 \n 钢笔",
13170            &[
13171                ("", 1, false),
13172                ("", 1, false),
13173                ("", 1, false),
13174                ("", 1, false),
13175                (" ", 1, true),
13176                ("", 1, false),
13177                ("", 1, false),
13178            ],
13179        ),
13180        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13181    ];
13182
13183    for (input, result) in tests {
13184        assert_eq!(
13185            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13186            result
13187                .iter()
13188                .copied()
13189                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13190                    token,
13191                    grapheme_len,
13192                    is_whitespace,
13193                })
13194                .collect::<Vec<_>>()
13195        );
13196    }
13197}
13198
13199fn wrap_with_prefix(
13200    line_prefix: String,
13201    unwrapped_text: String,
13202    wrap_column: usize,
13203    tab_size: NonZeroU32,
13204) -> String {
13205    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13206    let mut wrapped_text = String::new();
13207    let mut current_line = line_prefix.clone();
13208
13209    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13210    let mut current_line_len = line_prefix_len;
13211    for WordBreakToken {
13212        token,
13213        grapheme_len,
13214        is_whitespace,
13215    } in tokenizer
13216    {
13217        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13218            wrapped_text.push_str(current_line.trim_end());
13219            wrapped_text.push('\n');
13220            current_line.truncate(line_prefix.len());
13221            current_line_len = line_prefix_len;
13222            if !is_whitespace {
13223                current_line.push_str(token);
13224                current_line_len += grapheme_len;
13225            }
13226        } else if !is_whitespace {
13227            current_line.push_str(token);
13228            current_line_len += grapheme_len;
13229        } else if current_line_len != line_prefix_len {
13230            current_line.push(' ');
13231            current_line_len += 1;
13232        }
13233    }
13234
13235    if !current_line.is_empty() {
13236        wrapped_text.push_str(&current_line);
13237    }
13238    wrapped_text
13239}
13240
13241#[test]
13242fn test_wrap_with_prefix() {
13243    assert_eq!(
13244        wrap_with_prefix(
13245            "# ".to_string(),
13246            "abcdefg".to_string(),
13247            4,
13248            NonZeroU32::new(4).unwrap()
13249        ),
13250        "# abcdefg"
13251    );
13252    assert_eq!(
13253        wrap_with_prefix(
13254            "".to_string(),
13255            "\thello world".to_string(),
13256            8,
13257            NonZeroU32::new(4).unwrap()
13258        ),
13259        "hello\nworld"
13260    );
13261    assert_eq!(
13262        wrap_with_prefix(
13263            "// ".to_string(),
13264            "xx \nyy zz aa bb cc".to_string(),
13265            12,
13266            NonZeroU32::new(4).unwrap()
13267        ),
13268        "// xx yy zz\n// aa bb cc"
13269    );
13270    assert_eq!(
13271        wrap_with_prefix(
13272            String::new(),
13273            "这是什么 \n 钢笔".to_string(),
13274            3,
13275            NonZeroU32::new(4).unwrap()
13276        ),
13277        "这是什\n么 钢\n"
13278    );
13279}
13280
13281fn hunks_for_selections(
13282    snapshot: &EditorSnapshot,
13283    selections: &[Selection<Point>],
13284) -> Vec<MultiBufferDiffHunk> {
13285    hunks_for_ranges(
13286        selections.iter().map(|selection| selection.range()),
13287        snapshot,
13288    )
13289}
13290
13291pub fn hunks_for_ranges(
13292    ranges: impl Iterator<Item = Range<Point>>,
13293    snapshot: &EditorSnapshot,
13294) -> Vec<MultiBufferDiffHunk> {
13295    let mut hunks = Vec::new();
13296    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13297        HashMap::default();
13298    for query_range in ranges {
13299        let query_rows =
13300            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13301        for hunk in snapshot.diff_map.diff_hunks_in_range(
13302            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13303            &snapshot.buffer_snapshot,
13304        ) {
13305            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13306            // when the caret is just above or just below the deleted hunk.
13307            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13308            let related_to_selection = if allow_adjacent {
13309                hunk.row_range.overlaps(&query_rows)
13310                    || hunk.row_range.start == query_rows.end
13311                    || hunk.row_range.end == query_rows.start
13312            } else {
13313                hunk.row_range.overlaps(&query_rows)
13314            };
13315            if related_to_selection {
13316                if !processed_buffer_rows
13317                    .entry(hunk.buffer_id)
13318                    .or_default()
13319                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13320                {
13321                    continue;
13322                }
13323                hunks.push(hunk);
13324            }
13325        }
13326    }
13327
13328    hunks
13329}
13330
13331pub trait CollaborationHub {
13332    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13333    fn user_participant_indices<'a>(
13334        &self,
13335        cx: &'a AppContext,
13336    ) -> &'a HashMap<u64, ParticipantIndex>;
13337    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13338}
13339
13340impl CollaborationHub for Model<Project> {
13341    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13342        self.read(cx).collaborators()
13343    }
13344
13345    fn user_participant_indices<'a>(
13346        &self,
13347        cx: &'a AppContext,
13348    ) -> &'a HashMap<u64, ParticipantIndex> {
13349        self.read(cx).user_store().read(cx).participant_indices()
13350    }
13351
13352    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13353        let this = self.read(cx);
13354        let user_ids = this.collaborators().values().map(|c| c.user_id);
13355        this.user_store().read_with(cx, |user_store, cx| {
13356            user_store.participant_names(user_ids, cx)
13357        })
13358    }
13359}
13360
13361pub trait SemanticsProvider {
13362    fn hover(
13363        &self,
13364        buffer: &Model<Buffer>,
13365        position: text::Anchor,
13366        cx: &mut AppContext,
13367    ) -> Option<Task<Vec<project::Hover>>>;
13368
13369    fn inlay_hints(
13370        &self,
13371        buffer_handle: Model<Buffer>,
13372        range: Range<text::Anchor>,
13373        cx: &mut AppContext,
13374    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13375
13376    fn resolve_inlay_hint(
13377        &self,
13378        hint: InlayHint,
13379        buffer_handle: Model<Buffer>,
13380        server_id: LanguageServerId,
13381        cx: &mut AppContext,
13382    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13383
13384    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13385
13386    fn document_highlights(
13387        &self,
13388        buffer: &Model<Buffer>,
13389        position: text::Anchor,
13390        cx: &mut AppContext,
13391    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13392
13393    fn definitions(
13394        &self,
13395        buffer: &Model<Buffer>,
13396        position: text::Anchor,
13397        kind: GotoDefinitionKind,
13398        cx: &mut AppContext,
13399    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13400
13401    fn range_for_rename(
13402        &self,
13403        buffer: &Model<Buffer>,
13404        position: text::Anchor,
13405        cx: &mut AppContext,
13406    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13407
13408    fn perform_rename(
13409        &self,
13410        buffer: &Model<Buffer>,
13411        position: text::Anchor,
13412        new_name: String,
13413        cx: &mut AppContext,
13414    ) -> Option<Task<Result<ProjectTransaction>>>;
13415}
13416
13417pub trait CompletionProvider {
13418    fn completions(
13419        &self,
13420        buffer: &Model<Buffer>,
13421        buffer_position: text::Anchor,
13422        trigger: CompletionContext,
13423        cx: &mut ViewContext<Editor>,
13424    ) -> Task<Result<Vec<Completion>>>;
13425
13426    fn resolve_completions(
13427        &self,
13428        buffer: Model<Buffer>,
13429        completion_indices: Vec<usize>,
13430        completions: Rc<RefCell<Box<[Completion]>>>,
13431        cx: &mut ViewContext<Editor>,
13432    ) -> Task<Result<bool>>;
13433
13434    fn apply_additional_edits_for_completion(
13435        &self,
13436        buffer: Model<Buffer>,
13437        completion: Completion,
13438        push_to_history: bool,
13439        cx: &mut ViewContext<Editor>,
13440    ) -> Task<Result<Option<language::Transaction>>>;
13441
13442    fn is_completion_trigger(
13443        &self,
13444        buffer: &Model<Buffer>,
13445        position: language::Anchor,
13446        text: &str,
13447        trigger_in_words: bool,
13448        cx: &mut ViewContext<Editor>,
13449    ) -> bool;
13450
13451    fn sort_completions(&self) -> bool {
13452        true
13453    }
13454}
13455
13456pub trait CodeActionProvider {
13457    fn code_actions(
13458        &self,
13459        buffer: &Model<Buffer>,
13460        range: Range<text::Anchor>,
13461        cx: &mut WindowContext,
13462    ) -> Task<Result<Vec<CodeAction>>>;
13463
13464    fn apply_code_action(
13465        &self,
13466        buffer_handle: Model<Buffer>,
13467        action: CodeAction,
13468        excerpt_id: ExcerptId,
13469        push_to_history: bool,
13470        cx: &mut WindowContext,
13471    ) -> Task<Result<ProjectTransaction>>;
13472}
13473
13474impl CodeActionProvider for Model<Project> {
13475    fn code_actions(
13476        &self,
13477        buffer: &Model<Buffer>,
13478        range: Range<text::Anchor>,
13479        cx: &mut WindowContext,
13480    ) -> Task<Result<Vec<CodeAction>>> {
13481        self.update(cx, |project, cx| {
13482            project.code_actions(buffer, range, None, cx)
13483        })
13484    }
13485
13486    fn apply_code_action(
13487        &self,
13488        buffer_handle: Model<Buffer>,
13489        action: CodeAction,
13490        _excerpt_id: ExcerptId,
13491        push_to_history: bool,
13492        cx: &mut WindowContext,
13493    ) -> Task<Result<ProjectTransaction>> {
13494        self.update(cx, |project, cx| {
13495            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13496        })
13497    }
13498}
13499
13500fn snippet_completions(
13501    project: &Project,
13502    buffer: &Model<Buffer>,
13503    buffer_position: text::Anchor,
13504    cx: &mut AppContext,
13505) -> Task<Result<Vec<Completion>>> {
13506    let language = buffer.read(cx).language_at(buffer_position);
13507    let language_name = language.as_ref().map(|language| language.lsp_id());
13508    let snippet_store = project.snippets().read(cx);
13509    let snippets = snippet_store.snippets_for(language_name, cx);
13510
13511    if snippets.is_empty() {
13512        return Task::ready(Ok(vec![]));
13513    }
13514    let snapshot = buffer.read(cx).text_snapshot();
13515    let chars: String = snapshot
13516        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13517        .collect();
13518
13519    let scope = language.map(|language| language.default_scope());
13520    let executor = cx.background_executor().clone();
13521
13522    cx.background_executor().spawn(async move {
13523        let classifier = CharClassifier::new(scope).for_completion(true);
13524        let mut last_word = chars
13525            .chars()
13526            .take_while(|c| classifier.is_word(*c))
13527            .collect::<String>();
13528        last_word = last_word.chars().rev().collect();
13529
13530        if last_word.is_empty() {
13531            return Ok(vec![]);
13532        }
13533
13534        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13535        let to_lsp = |point: &text::Anchor| {
13536            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13537            point_to_lsp(end)
13538        };
13539        let lsp_end = to_lsp(&buffer_position);
13540
13541        let candidates = snippets
13542            .iter()
13543            .enumerate()
13544            .flat_map(|(ix, snippet)| {
13545                snippet
13546                    .prefix
13547                    .iter()
13548                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13549            })
13550            .collect::<Vec<StringMatchCandidate>>();
13551
13552        let mut matches = fuzzy::match_strings(
13553            &candidates,
13554            &last_word,
13555            last_word.chars().any(|c| c.is_uppercase()),
13556            100,
13557            &Default::default(),
13558            executor,
13559        )
13560        .await;
13561
13562        // Remove all candidates where the query's start does not match the start of any word in the candidate
13563        if let Some(query_start) = last_word.chars().next() {
13564            matches.retain(|string_match| {
13565                split_words(&string_match.string).any(|word| {
13566                    // Check that the first codepoint of the word as lowercase matches the first
13567                    // codepoint of the query as lowercase
13568                    word.chars()
13569                        .flat_map(|codepoint| codepoint.to_lowercase())
13570                        .zip(query_start.to_lowercase())
13571                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13572                })
13573            });
13574        }
13575
13576        let matched_strings = matches
13577            .into_iter()
13578            .map(|m| m.string)
13579            .collect::<HashSet<_>>();
13580
13581        let result: Vec<Completion> = snippets
13582            .into_iter()
13583            .filter_map(|snippet| {
13584                let matching_prefix = snippet
13585                    .prefix
13586                    .iter()
13587                    .find(|prefix| matched_strings.contains(*prefix))?;
13588                let start = as_offset - last_word.len();
13589                let start = snapshot.anchor_before(start);
13590                let range = start..buffer_position;
13591                let lsp_start = to_lsp(&start);
13592                let lsp_range = lsp::Range {
13593                    start: lsp_start,
13594                    end: lsp_end,
13595                };
13596                Some(Completion {
13597                    old_range: range,
13598                    new_text: snippet.body.clone(),
13599                    label: CodeLabel {
13600                        text: matching_prefix.clone(),
13601                        runs: vec![],
13602                        filter_range: 0..matching_prefix.len(),
13603                    },
13604                    server_id: LanguageServerId(usize::MAX),
13605                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13606                    lsp_completion: lsp::CompletionItem {
13607                        label: snippet.prefix.first().unwrap().clone(),
13608                        kind: Some(CompletionItemKind::SNIPPET),
13609                        label_details: snippet.description.as_ref().map(|description| {
13610                            lsp::CompletionItemLabelDetails {
13611                                detail: Some(description.clone()),
13612                                description: None,
13613                            }
13614                        }),
13615                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13616                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13617                            lsp::InsertReplaceEdit {
13618                                new_text: snippet.body.clone(),
13619                                insert: lsp_range,
13620                                replace: lsp_range,
13621                            },
13622                        )),
13623                        filter_text: Some(snippet.body.clone()),
13624                        sort_text: Some(char::MAX.to_string()),
13625                        ..Default::default()
13626                    },
13627                    confirm: None,
13628                })
13629            })
13630            .collect();
13631
13632        Ok(result)
13633    })
13634}
13635
13636impl CompletionProvider for Model<Project> {
13637    fn completions(
13638        &self,
13639        buffer: &Model<Buffer>,
13640        buffer_position: text::Anchor,
13641        options: CompletionContext,
13642        cx: &mut ViewContext<Editor>,
13643    ) -> Task<Result<Vec<Completion>>> {
13644        self.update(cx, |project, cx| {
13645            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13646            let project_completions = project.completions(buffer, buffer_position, options, cx);
13647            cx.background_executor().spawn(async move {
13648                let mut completions = project_completions.await?;
13649                let snippets_completions = snippets.await?;
13650                completions.extend(snippets_completions);
13651                Ok(completions)
13652            })
13653        })
13654    }
13655
13656    fn resolve_completions(
13657        &self,
13658        buffer: Model<Buffer>,
13659        completion_indices: Vec<usize>,
13660        completions: Rc<RefCell<Box<[Completion]>>>,
13661        cx: &mut ViewContext<Editor>,
13662    ) -> Task<Result<bool>> {
13663        self.update(cx, |project, cx| {
13664            project.resolve_completions(buffer, completion_indices, completions, cx)
13665        })
13666    }
13667
13668    fn apply_additional_edits_for_completion(
13669        &self,
13670        buffer: Model<Buffer>,
13671        completion: Completion,
13672        push_to_history: bool,
13673        cx: &mut ViewContext<Editor>,
13674    ) -> Task<Result<Option<language::Transaction>>> {
13675        self.update(cx, |project, cx| {
13676            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13677        })
13678    }
13679
13680    fn is_completion_trigger(
13681        &self,
13682        buffer: &Model<Buffer>,
13683        position: language::Anchor,
13684        text: &str,
13685        trigger_in_words: bool,
13686        cx: &mut ViewContext<Editor>,
13687    ) -> bool {
13688        let mut chars = text.chars();
13689        let char = if let Some(char) = chars.next() {
13690            char
13691        } else {
13692            return false;
13693        };
13694        if chars.next().is_some() {
13695            return false;
13696        }
13697
13698        let buffer = buffer.read(cx);
13699        let snapshot = buffer.snapshot();
13700        if !snapshot.settings_at(position, cx).show_completions_on_input {
13701            return false;
13702        }
13703        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13704        if trigger_in_words && classifier.is_word(char) {
13705            return true;
13706        }
13707
13708        buffer.completion_triggers().contains(text)
13709    }
13710}
13711
13712impl SemanticsProvider for Model<Project> {
13713    fn hover(
13714        &self,
13715        buffer: &Model<Buffer>,
13716        position: text::Anchor,
13717        cx: &mut AppContext,
13718    ) -> Option<Task<Vec<project::Hover>>> {
13719        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13720    }
13721
13722    fn document_highlights(
13723        &self,
13724        buffer: &Model<Buffer>,
13725        position: text::Anchor,
13726        cx: &mut AppContext,
13727    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13728        Some(self.update(cx, |project, cx| {
13729            project.document_highlights(buffer, position, cx)
13730        }))
13731    }
13732
13733    fn definitions(
13734        &self,
13735        buffer: &Model<Buffer>,
13736        position: text::Anchor,
13737        kind: GotoDefinitionKind,
13738        cx: &mut AppContext,
13739    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13740        Some(self.update(cx, |project, cx| match kind {
13741            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13742            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13743            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13744            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13745        }))
13746    }
13747
13748    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13749        // TODO: make this work for remote projects
13750        self.read(cx)
13751            .language_servers_for_local_buffer(buffer.read(cx), cx)
13752            .any(
13753                |(_, server)| match server.capabilities().inlay_hint_provider {
13754                    Some(lsp::OneOf::Left(enabled)) => enabled,
13755                    Some(lsp::OneOf::Right(_)) => true,
13756                    None => false,
13757                },
13758            )
13759    }
13760
13761    fn inlay_hints(
13762        &self,
13763        buffer_handle: Model<Buffer>,
13764        range: Range<text::Anchor>,
13765        cx: &mut AppContext,
13766    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13767        Some(self.update(cx, |project, cx| {
13768            project.inlay_hints(buffer_handle, range, cx)
13769        }))
13770    }
13771
13772    fn resolve_inlay_hint(
13773        &self,
13774        hint: InlayHint,
13775        buffer_handle: Model<Buffer>,
13776        server_id: LanguageServerId,
13777        cx: &mut AppContext,
13778    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13779        Some(self.update(cx, |project, cx| {
13780            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13781        }))
13782    }
13783
13784    fn range_for_rename(
13785        &self,
13786        buffer: &Model<Buffer>,
13787        position: text::Anchor,
13788        cx: &mut AppContext,
13789    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13790        Some(self.update(cx, |project, cx| {
13791            project.prepare_rename(buffer.clone(), position, cx)
13792        }))
13793    }
13794
13795    fn perform_rename(
13796        &self,
13797        buffer: &Model<Buffer>,
13798        position: text::Anchor,
13799        new_name: String,
13800        cx: &mut AppContext,
13801    ) -> Option<Task<Result<ProjectTransaction>>> {
13802        Some(self.update(cx, |project, cx| {
13803            project.perform_rename(buffer.clone(), position, new_name, cx)
13804        }))
13805    }
13806}
13807
13808fn inlay_hint_settings(
13809    location: Anchor,
13810    snapshot: &MultiBufferSnapshot,
13811    cx: &mut ViewContext<'_, Editor>,
13812) -> InlayHintSettings {
13813    let file = snapshot.file_at(location);
13814    let language = snapshot.language_at(location).map(|l| l.name());
13815    language_settings(language, file, cx).inlay_hints
13816}
13817
13818fn consume_contiguous_rows(
13819    contiguous_row_selections: &mut Vec<Selection<Point>>,
13820    selection: &Selection<Point>,
13821    display_map: &DisplaySnapshot,
13822    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13823) -> (MultiBufferRow, MultiBufferRow) {
13824    contiguous_row_selections.push(selection.clone());
13825    let start_row = MultiBufferRow(selection.start.row);
13826    let mut end_row = ending_row(selection, display_map);
13827
13828    while let Some(next_selection) = selections.peek() {
13829        if next_selection.start.row <= end_row.0 {
13830            end_row = ending_row(next_selection, display_map);
13831            contiguous_row_selections.push(selections.next().unwrap().clone());
13832        } else {
13833            break;
13834        }
13835    }
13836    (start_row, end_row)
13837}
13838
13839fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13840    if next_selection.end.column > 0 || next_selection.is_empty() {
13841        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13842    } else {
13843        MultiBufferRow(next_selection.end.row)
13844    }
13845}
13846
13847impl EditorSnapshot {
13848    pub fn remote_selections_in_range<'a>(
13849        &'a self,
13850        range: &'a Range<Anchor>,
13851        collaboration_hub: &dyn CollaborationHub,
13852        cx: &'a AppContext,
13853    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13854        let participant_names = collaboration_hub.user_names(cx);
13855        let participant_indices = collaboration_hub.user_participant_indices(cx);
13856        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13857        let collaborators_by_replica_id = collaborators_by_peer_id
13858            .iter()
13859            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13860            .collect::<HashMap<_, _>>();
13861        self.buffer_snapshot
13862            .selections_in_range(range, false)
13863            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13864                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13865                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13866                let user_name = participant_names.get(&collaborator.user_id).cloned();
13867                Some(RemoteSelection {
13868                    replica_id,
13869                    selection,
13870                    cursor_shape,
13871                    line_mode,
13872                    participant_index,
13873                    peer_id: collaborator.peer_id,
13874                    user_name,
13875                })
13876            })
13877    }
13878
13879    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13880        self.display_snapshot.buffer_snapshot.language_at(position)
13881    }
13882
13883    pub fn is_focused(&self) -> bool {
13884        self.is_focused
13885    }
13886
13887    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13888        self.placeholder_text.as_ref()
13889    }
13890
13891    pub fn scroll_position(&self) -> gpui::Point<f32> {
13892        self.scroll_anchor.scroll_position(&self.display_snapshot)
13893    }
13894
13895    fn gutter_dimensions(
13896        &self,
13897        font_id: FontId,
13898        font_size: Pixels,
13899        em_width: Pixels,
13900        em_advance: Pixels,
13901        max_line_number_width: Pixels,
13902        cx: &AppContext,
13903    ) -> GutterDimensions {
13904        if !self.show_gutter {
13905            return GutterDimensions::default();
13906        }
13907        let descent = cx.text_system().descent(font_id, font_size);
13908
13909        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13910            matches!(
13911                ProjectSettings::get_global(cx).git.git_gutter,
13912                Some(GitGutterSetting::TrackedFiles)
13913            )
13914        });
13915        let gutter_settings = EditorSettings::get_global(cx).gutter;
13916        let show_line_numbers = self
13917            .show_line_numbers
13918            .unwrap_or(gutter_settings.line_numbers);
13919        let line_gutter_width = if show_line_numbers {
13920            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13921            let min_width_for_number_on_gutter = em_advance * 4.0;
13922            max_line_number_width.max(min_width_for_number_on_gutter)
13923        } else {
13924            0.0.into()
13925        };
13926
13927        let show_code_actions = self
13928            .show_code_actions
13929            .unwrap_or(gutter_settings.code_actions);
13930
13931        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13932
13933        let git_blame_entries_width =
13934            self.git_blame_gutter_max_author_length
13935                .map(|max_author_length| {
13936                    // Length of the author name, but also space for the commit hash,
13937                    // the spacing and the timestamp.
13938                    let max_char_count = max_author_length
13939                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13940                        + 7 // length of commit sha
13941                        + 14 // length of max relative timestamp ("60 minutes ago")
13942                        + 4; // gaps and margins
13943
13944                    em_advance * max_char_count
13945                });
13946
13947        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13948        left_padding += if show_code_actions || show_runnables {
13949            em_width * 3.0
13950        } else if show_git_gutter && show_line_numbers {
13951            em_width * 2.0
13952        } else if show_git_gutter || show_line_numbers {
13953            em_width
13954        } else {
13955            px(0.)
13956        };
13957
13958        let right_padding = if gutter_settings.folds && show_line_numbers {
13959            em_width * 4.0
13960        } else if gutter_settings.folds {
13961            em_width * 3.0
13962        } else if show_line_numbers {
13963            em_width
13964        } else {
13965            px(0.)
13966        };
13967
13968        GutterDimensions {
13969            left_padding,
13970            right_padding,
13971            width: line_gutter_width + left_padding + right_padding,
13972            margin: -descent,
13973            git_blame_entries_width,
13974        }
13975    }
13976
13977    pub fn render_crease_toggle(
13978        &self,
13979        buffer_row: MultiBufferRow,
13980        row_contains_cursor: bool,
13981        editor: View<Editor>,
13982        cx: &mut WindowContext,
13983    ) -> Option<AnyElement> {
13984        let folded = self.is_line_folded(buffer_row);
13985        let mut is_foldable = false;
13986
13987        if let Some(crease) = self
13988            .crease_snapshot
13989            .query_row(buffer_row, &self.buffer_snapshot)
13990        {
13991            is_foldable = true;
13992            match crease {
13993                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13994                    if let Some(render_toggle) = render_toggle {
13995                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13996                            if folded {
13997                                editor.update(cx, |editor, cx| {
13998                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13999                                });
14000                            } else {
14001                                editor.update(cx, |editor, cx| {
14002                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14003                                });
14004                            }
14005                        });
14006                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14007                    }
14008                }
14009            }
14010        }
14011
14012        is_foldable |= self.starts_indent(buffer_row);
14013
14014        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14015            Some(
14016                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14017                    .toggle_state(folded)
14018                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14019                        if folded {
14020                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14021                        } else {
14022                            this.fold_at(&FoldAt { buffer_row }, cx);
14023                        }
14024                    }))
14025                    .into_any_element(),
14026            )
14027        } else {
14028            None
14029        }
14030    }
14031
14032    pub fn render_crease_trailer(
14033        &self,
14034        buffer_row: MultiBufferRow,
14035        cx: &mut WindowContext,
14036    ) -> Option<AnyElement> {
14037        let folded = self.is_line_folded(buffer_row);
14038        if let Crease::Inline { render_trailer, .. } = self
14039            .crease_snapshot
14040            .query_row(buffer_row, &self.buffer_snapshot)?
14041        {
14042            let render_trailer = render_trailer.as_ref()?;
14043            Some(render_trailer(buffer_row, folded, cx))
14044        } else {
14045            None
14046        }
14047    }
14048}
14049
14050impl Deref for EditorSnapshot {
14051    type Target = DisplaySnapshot;
14052
14053    fn deref(&self) -> &Self::Target {
14054        &self.display_snapshot
14055    }
14056}
14057
14058#[derive(Clone, Debug, PartialEq, Eq)]
14059pub enum EditorEvent {
14060    InputIgnored {
14061        text: Arc<str>,
14062    },
14063    InputHandled {
14064        utf16_range_to_replace: Option<Range<isize>>,
14065        text: Arc<str>,
14066    },
14067    ExcerptsAdded {
14068        buffer: Model<Buffer>,
14069        predecessor: ExcerptId,
14070        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14071    },
14072    ExcerptsRemoved {
14073        ids: Vec<ExcerptId>,
14074    },
14075    BufferFoldToggled {
14076        ids: Vec<ExcerptId>,
14077        folded: bool,
14078    },
14079    ExcerptsEdited {
14080        ids: Vec<ExcerptId>,
14081    },
14082    ExcerptsExpanded {
14083        ids: Vec<ExcerptId>,
14084    },
14085    BufferEdited,
14086    Edited {
14087        transaction_id: clock::Lamport,
14088    },
14089    Reparsed(BufferId),
14090    Focused,
14091    FocusedIn,
14092    Blurred,
14093    DirtyChanged,
14094    Saved,
14095    TitleChanged,
14096    DiffBaseChanged,
14097    SelectionsChanged {
14098        local: bool,
14099    },
14100    ScrollPositionChanged {
14101        local: bool,
14102        autoscroll: bool,
14103    },
14104    Closed,
14105    TransactionUndone {
14106        transaction_id: clock::Lamport,
14107    },
14108    TransactionBegun {
14109        transaction_id: clock::Lamport,
14110    },
14111    Reloaded,
14112    CursorShapeChanged,
14113}
14114
14115impl EventEmitter<EditorEvent> for Editor {}
14116
14117impl FocusableView for Editor {
14118    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14119        self.focus_handle.clone()
14120    }
14121}
14122
14123impl Render for Editor {
14124    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14125        let settings = ThemeSettings::get_global(cx);
14126
14127        let mut text_style = match self.mode {
14128            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14129                color: cx.theme().colors().editor_foreground,
14130                font_family: settings.ui_font.family.clone(),
14131                font_features: settings.ui_font.features.clone(),
14132                font_fallbacks: settings.ui_font.fallbacks.clone(),
14133                font_size: rems(0.875).into(),
14134                font_weight: settings.ui_font.weight,
14135                line_height: relative(settings.buffer_line_height.value()),
14136                ..Default::default()
14137            },
14138            EditorMode::Full => TextStyle {
14139                color: cx.theme().colors().editor_foreground,
14140                font_family: settings.buffer_font.family.clone(),
14141                font_features: settings.buffer_font.features.clone(),
14142                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14143                font_size: settings.buffer_font_size(cx).into(),
14144                font_weight: settings.buffer_font.weight,
14145                line_height: relative(settings.buffer_line_height.value()),
14146                ..Default::default()
14147            },
14148        };
14149        if let Some(text_style_refinement) = &self.text_style_refinement {
14150            text_style.refine(text_style_refinement)
14151        }
14152
14153        let background = match self.mode {
14154            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14155            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14156            EditorMode::Full => cx.theme().colors().editor_background,
14157        };
14158
14159        EditorElement::new(
14160            cx.view(),
14161            EditorStyle {
14162                background,
14163                local_player: cx.theme().players().local(),
14164                text: text_style,
14165                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14166                syntax: cx.theme().syntax().clone(),
14167                status: cx.theme().status().clone(),
14168                inlay_hints_style: make_inlay_hints_style(cx),
14169                inline_completion_styles: make_suggestion_styles(cx),
14170                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14171            },
14172        )
14173    }
14174}
14175
14176impl ViewInputHandler for Editor {
14177    fn text_for_range(
14178        &mut self,
14179        range_utf16: Range<usize>,
14180        adjusted_range: &mut Option<Range<usize>>,
14181        cx: &mut ViewContext<Self>,
14182    ) -> Option<String> {
14183        let snapshot = self.buffer.read(cx).read(cx);
14184        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14185        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14186        if (start.0..end.0) != range_utf16 {
14187            adjusted_range.replace(start.0..end.0);
14188        }
14189        Some(snapshot.text_for_range(start..end).collect())
14190    }
14191
14192    fn selected_text_range(
14193        &mut self,
14194        ignore_disabled_input: bool,
14195        cx: &mut ViewContext<Self>,
14196    ) -> Option<UTF16Selection> {
14197        // Prevent the IME menu from appearing when holding down an alphabetic key
14198        // while input is disabled.
14199        if !ignore_disabled_input && !self.input_enabled {
14200            return None;
14201        }
14202
14203        let selection = self.selections.newest::<OffsetUtf16>(cx);
14204        let range = selection.range();
14205
14206        Some(UTF16Selection {
14207            range: range.start.0..range.end.0,
14208            reversed: selection.reversed,
14209        })
14210    }
14211
14212    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14213        let snapshot = self.buffer.read(cx).read(cx);
14214        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14215        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14216    }
14217
14218    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14219        self.clear_highlights::<InputComposition>(cx);
14220        self.ime_transaction.take();
14221    }
14222
14223    fn replace_text_in_range(
14224        &mut self,
14225        range_utf16: Option<Range<usize>>,
14226        text: &str,
14227        cx: &mut ViewContext<Self>,
14228    ) {
14229        if !self.input_enabled {
14230            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14231            return;
14232        }
14233
14234        self.transact(cx, |this, cx| {
14235            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14236                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14237                Some(this.selection_replacement_ranges(range_utf16, cx))
14238            } else {
14239                this.marked_text_ranges(cx)
14240            };
14241
14242            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14243                let newest_selection_id = this.selections.newest_anchor().id;
14244                this.selections
14245                    .all::<OffsetUtf16>(cx)
14246                    .iter()
14247                    .zip(ranges_to_replace.iter())
14248                    .find_map(|(selection, range)| {
14249                        if selection.id == newest_selection_id {
14250                            Some(
14251                                (range.start.0 as isize - selection.head().0 as isize)
14252                                    ..(range.end.0 as isize - selection.head().0 as isize),
14253                            )
14254                        } else {
14255                            None
14256                        }
14257                    })
14258            });
14259
14260            cx.emit(EditorEvent::InputHandled {
14261                utf16_range_to_replace: range_to_replace,
14262                text: text.into(),
14263            });
14264
14265            if let Some(new_selected_ranges) = new_selected_ranges {
14266                this.change_selections(None, cx, |selections| {
14267                    selections.select_ranges(new_selected_ranges)
14268                });
14269                this.backspace(&Default::default(), cx);
14270            }
14271
14272            this.handle_input(text, cx);
14273        });
14274
14275        if let Some(transaction) = self.ime_transaction {
14276            self.buffer.update(cx, |buffer, cx| {
14277                buffer.group_until_transaction(transaction, cx);
14278            });
14279        }
14280
14281        self.unmark_text(cx);
14282    }
14283
14284    fn replace_and_mark_text_in_range(
14285        &mut self,
14286        range_utf16: Option<Range<usize>>,
14287        text: &str,
14288        new_selected_range_utf16: Option<Range<usize>>,
14289        cx: &mut ViewContext<Self>,
14290    ) {
14291        if !self.input_enabled {
14292            return;
14293        }
14294
14295        let transaction = self.transact(cx, |this, cx| {
14296            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14297                let snapshot = this.buffer.read(cx).read(cx);
14298                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14299                    for marked_range in &mut marked_ranges {
14300                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14301                        marked_range.start.0 += relative_range_utf16.start;
14302                        marked_range.start =
14303                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14304                        marked_range.end =
14305                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14306                    }
14307                }
14308                Some(marked_ranges)
14309            } else if let Some(range_utf16) = range_utf16 {
14310                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14311                Some(this.selection_replacement_ranges(range_utf16, cx))
14312            } else {
14313                None
14314            };
14315
14316            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14317                let newest_selection_id = this.selections.newest_anchor().id;
14318                this.selections
14319                    .all::<OffsetUtf16>(cx)
14320                    .iter()
14321                    .zip(ranges_to_replace.iter())
14322                    .find_map(|(selection, range)| {
14323                        if selection.id == newest_selection_id {
14324                            Some(
14325                                (range.start.0 as isize - selection.head().0 as isize)
14326                                    ..(range.end.0 as isize - selection.head().0 as isize),
14327                            )
14328                        } else {
14329                            None
14330                        }
14331                    })
14332            });
14333
14334            cx.emit(EditorEvent::InputHandled {
14335                utf16_range_to_replace: range_to_replace,
14336                text: text.into(),
14337            });
14338
14339            if let Some(ranges) = ranges_to_replace {
14340                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14341            }
14342
14343            let marked_ranges = {
14344                let snapshot = this.buffer.read(cx).read(cx);
14345                this.selections
14346                    .disjoint_anchors()
14347                    .iter()
14348                    .map(|selection| {
14349                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14350                    })
14351                    .collect::<Vec<_>>()
14352            };
14353
14354            if text.is_empty() {
14355                this.unmark_text(cx);
14356            } else {
14357                this.highlight_text::<InputComposition>(
14358                    marked_ranges.clone(),
14359                    HighlightStyle {
14360                        underline: Some(UnderlineStyle {
14361                            thickness: px(1.),
14362                            color: None,
14363                            wavy: false,
14364                        }),
14365                        ..Default::default()
14366                    },
14367                    cx,
14368                );
14369            }
14370
14371            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14372            let use_autoclose = this.use_autoclose;
14373            let use_auto_surround = this.use_auto_surround;
14374            this.set_use_autoclose(false);
14375            this.set_use_auto_surround(false);
14376            this.handle_input(text, cx);
14377            this.set_use_autoclose(use_autoclose);
14378            this.set_use_auto_surround(use_auto_surround);
14379
14380            if let Some(new_selected_range) = new_selected_range_utf16 {
14381                let snapshot = this.buffer.read(cx).read(cx);
14382                let new_selected_ranges = marked_ranges
14383                    .into_iter()
14384                    .map(|marked_range| {
14385                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14386                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14387                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14388                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14389                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14390                    })
14391                    .collect::<Vec<_>>();
14392
14393                drop(snapshot);
14394                this.change_selections(None, cx, |selections| {
14395                    selections.select_ranges(new_selected_ranges)
14396                });
14397            }
14398        });
14399
14400        self.ime_transaction = self.ime_transaction.or(transaction);
14401        if let Some(transaction) = self.ime_transaction {
14402            self.buffer.update(cx, |buffer, cx| {
14403                buffer.group_until_transaction(transaction, cx);
14404            });
14405        }
14406
14407        if self.text_highlights::<InputComposition>(cx).is_none() {
14408            self.ime_transaction.take();
14409        }
14410    }
14411
14412    fn bounds_for_range(
14413        &mut self,
14414        range_utf16: Range<usize>,
14415        element_bounds: gpui::Bounds<Pixels>,
14416        cx: &mut ViewContext<Self>,
14417    ) -> Option<gpui::Bounds<Pixels>> {
14418        let text_layout_details = self.text_layout_details(cx);
14419        let gpui::Point {
14420            x: em_width,
14421            y: line_height,
14422        } = self.character_size(cx);
14423
14424        let snapshot = self.snapshot(cx);
14425        let scroll_position = snapshot.scroll_position();
14426        let scroll_left = scroll_position.x * em_width;
14427
14428        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14429        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14430            + self.gutter_dimensions.width
14431            + self.gutter_dimensions.margin;
14432        let y = line_height * (start.row().as_f32() - scroll_position.y);
14433
14434        Some(Bounds {
14435            origin: element_bounds.origin + point(x, y),
14436            size: size(em_width, line_height),
14437        })
14438    }
14439}
14440
14441trait SelectionExt {
14442    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14443    fn spanned_rows(
14444        &self,
14445        include_end_if_at_line_start: bool,
14446        map: &DisplaySnapshot,
14447    ) -> Range<MultiBufferRow>;
14448}
14449
14450impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14451    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14452        let start = self
14453            .start
14454            .to_point(&map.buffer_snapshot)
14455            .to_display_point(map);
14456        let end = self
14457            .end
14458            .to_point(&map.buffer_snapshot)
14459            .to_display_point(map);
14460        if self.reversed {
14461            end..start
14462        } else {
14463            start..end
14464        }
14465    }
14466
14467    fn spanned_rows(
14468        &self,
14469        include_end_if_at_line_start: bool,
14470        map: &DisplaySnapshot,
14471    ) -> Range<MultiBufferRow> {
14472        let start = self.start.to_point(&map.buffer_snapshot);
14473        let mut end = self.end.to_point(&map.buffer_snapshot);
14474        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14475            end.row -= 1;
14476        }
14477
14478        let buffer_start = map.prev_line_boundary(start).0;
14479        let buffer_end = map.next_line_boundary(end).0;
14480        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14481    }
14482}
14483
14484impl<T: InvalidationRegion> InvalidationStack<T> {
14485    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14486    where
14487        S: Clone + ToOffset,
14488    {
14489        while let Some(region) = self.last() {
14490            let all_selections_inside_invalidation_ranges =
14491                if selections.len() == region.ranges().len() {
14492                    selections
14493                        .iter()
14494                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14495                        .all(|(selection, invalidation_range)| {
14496                            let head = selection.head().to_offset(buffer);
14497                            invalidation_range.start <= head && invalidation_range.end >= head
14498                        })
14499                } else {
14500                    false
14501                };
14502
14503            if all_selections_inside_invalidation_ranges {
14504                break;
14505            } else {
14506                self.pop();
14507            }
14508        }
14509    }
14510}
14511
14512impl<T> Default for InvalidationStack<T> {
14513    fn default() -> Self {
14514        Self(Default::default())
14515    }
14516}
14517
14518impl<T> Deref for InvalidationStack<T> {
14519    type Target = Vec<T>;
14520
14521    fn deref(&self) -> &Self::Target {
14522        &self.0
14523    }
14524}
14525
14526impl<T> DerefMut for InvalidationStack<T> {
14527    fn deref_mut(&mut self) -> &mut Self::Target {
14528        &mut self.0
14529    }
14530}
14531
14532impl InvalidationRegion for SnippetState {
14533    fn ranges(&self) -> &[Range<Anchor>] {
14534        &self.ranges[self.active_index]
14535    }
14536}
14537
14538pub fn diagnostic_block_renderer(
14539    diagnostic: Diagnostic,
14540    max_message_rows: Option<u8>,
14541    allow_closing: bool,
14542    _is_valid: bool,
14543) -> RenderBlock {
14544    let (text_without_backticks, code_ranges) =
14545        highlight_diagnostic_message(&diagnostic, max_message_rows);
14546
14547    Arc::new(move |cx: &mut BlockContext| {
14548        let group_id: SharedString = cx.block_id.to_string().into();
14549
14550        let mut text_style = cx.text_style().clone();
14551        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14552        let theme_settings = ThemeSettings::get_global(cx);
14553        text_style.font_family = theme_settings.buffer_font.family.clone();
14554        text_style.font_style = theme_settings.buffer_font.style;
14555        text_style.font_features = theme_settings.buffer_font.features.clone();
14556        text_style.font_weight = theme_settings.buffer_font.weight;
14557
14558        let multi_line_diagnostic = diagnostic.message.contains('\n');
14559
14560        let buttons = |diagnostic: &Diagnostic| {
14561            if multi_line_diagnostic {
14562                v_flex()
14563            } else {
14564                h_flex()
14565            }
14566            .when(allow_closing, |div| {
14567                div.children(diagnostic.is_primary.then(|| {
14568                    IconButton::new("close-block", IconName::XCircle)
14569                        .icon_color(Color::Muted)
14570                        .size(ButtonSize::Compact)
14571                        .style(ButtonStyle::Transparent)
14572                        .visible_on_hover(group_id.clone())
14573                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14574                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14575                }))
14576            })
14577            .child(
14578                IconButton::new("copy-block", IconName::Copy)
14579                    .icon_color(Color::Muted)
14580                    .size(ButtonSize::Compact)
14581                    .style(ButtonStyle::Transparent)
14582                    .visible_on_hover(group_id.clone())
14583                    .on_click({
14584                        let message = diagnostic.message.clone();
14585                        move |_click, cx| {
14586                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14587                        }
14588                    })
14589                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14590            )
14591        };
14592
14593        let icon_size = buttons(&diagnostic)
14594            .into_any_element()
14595            .layout_as_root(AvailableSpace::min_size(), cx);
14596
14597        h_flex()
14598            .id(cx.block_id)
14599            .group(group_id.clone())
14600            .relative()
14601            .size_full()
14602            .block_mouse_down()
14603            .pl(cx.gutter_dimensions.width)
14604            .w(cx.max_width - cx.gutter_dimensions.full_width())
14605            .child(
14606                div()
14607                    .flex()
14608                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14609                    .flex_shrink(),
14610            )
14611            .child(buttons(&diagnostic))
14612            .child(div().flex().flex_shrink_0().child(
14613                StyledText::new(text_without_backticks.clone()).with_highlights(
14614                    &text_style,
14615                    code_ranges.iter().map(|range| {
14616                        (
14617                            range.clone(),
14618                            HighlightStyle {
14619                                font_weight: Some(FontWeight::BOLD),
14620                                ..Default::default()
14621                            },
14622                        )
14623                    }),
14624                ),
14625            ))
14626            .into_any_element()
14627    })
14628}
14629
14630fn inline_completion_edit_text(
14631    editor_snapshot: &EditorSnapshot,
14632    edits: &Vec<(Range<Anchor>, String)>,
14633    include_deletions: bool,
14634    cx: &WindowContext,
14635) -> InlineCompletionText {
14636    let edit_start = edits
14637        .first()
14638        .unwrap()
14639        .0
14640        .start
14641        .to_display_point(editor_snapshot);
14642
14643    let mut text = String::new();
14644    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14645    let mut highlights = Vec::new();
14646    for (old_range, new_text) in edits {
14647        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14648        text.extend(
14649            editor_snapshot
14650                .buffer_snapshot
14651                .chunks(offset..old_offset_range.start, false)
14652                .map(|chunk| chunk.text),
14653        );
14654        offset = old_offset_range.end;
14655
14656        let start = text.len();
14657        let color = if include_deletions && new_text.is_empty() {
14658            text.extend(
14659                editor_snapshot
14660                    .buffer_snapshot
14661                    .chunks(old_offset_range.start..offset, false)
14662                    .map(|chunk| chunk.text),
14663            );
14664            cx.theme().status().deleted_background
14665        } else {
14666            text.push_str(new_text);
14667            cx.theme().status().created_background
14668        };
14669        let end = text.len();
14670
14671        highlights.push((
14672            start..end,
14673            HighlightStyle {
14674                background_color: Some(color),
14675                ..Default::default()
14676            },
14677        ));
14678    }
14679
14680    let edit_end = edits
14681        .last()
14682        .unwrap()
14683        .0
14684        .end
14685        .to_display_point(editor_snapshot);
14686    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14687        .to_offset(editor_snapshot, Bias::Right);
14688    text.extend(
14689        editor_snapshot
14690            .buffer_snapshot
14691            .chunks(offset..end_of_line, false)
14692            .map(|chunk| chunk.text),
14693    );
14694
14695    InlineCompletionText::Edit {
14696        text: text.into(),
14697        highlights,
14698    }
14699}
14700
14701pub fn highlight_diagnostic_message(
14702    diagnostic: &Diagnostic,
14703    mut max_message_rows: Option<u8>,
14704) -> (SharedString, Vec<Range<usize>>) {
14705    let mut text_without_backticks = String::new();
14706    let mut code_ranges = Vec::new();
14707
14708    if let Some(source) = &diagnostic.source {
14709        text_without_backticks.push_str(source);
14710        code_ranges.push(0..source.len());
14711        text_without_backticks.push_str(": ");
14712    }
14713
14714    let mut prev_offset = 0;
14715    let mut in_code_block = false;
14716    let has_row_limit = max_message_rows.is_some();
14717    let mut newline_indices = diagnostic
14718        .message
14719        .match_indices('\n')
14720        .filter(|_| has_row_limit)
14721        .map(|(ix, _)| ix)
14722        .fuse()
14723        .peekable();
14724
14725    for (quote_ix, _) in diagnostic
14726        .message
14727        .match_indices('`')
14728        .chain([(diagnostic.message.len(), "")])
14729    {
14730        let mut first_newline_ix = None;
14731        let mut last_newline_ix = None;
14732        while let Some(newline_ix) = newline_indices.peek() {
14733            if *newline_ix < quote_ix {
14734                if first_newline_ix.is_none() {
14735                    first_newline_ix = Some(*newline_ix);
14736                }
14737                last_newline_ix = Some(*newline_ix);
14738
14739                if let Some(rows_left) = &mut max_message_rows {
14740                    if *rows_left == 0 {
14741                        break;
14742                    } else {
14743                        *rows_left -= 1;
14744                    }
14745                }
14746                let _ = newline_indices.next();
14747            } else {
14748                break;
14749            }
14750        }
14751        let prev_len = text_without_backticks.len();
14752        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14753        text_without_backticks.push_str(new_text);
14754        if in_code_block {
14755            code_ranges.push(prev_len..text_without_backticks.len());
14756        }
14757        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14758        in_code_block = !in_code_block;
14759        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14760            text_without_backticks.push_str("...");
14761            break;
14762        }
14763    }
14764
14765    (text_without_backticks.into(), code_ranges)
14766}
14767
14768fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14769    match severity {
14770        DiagnosticSeverity::ERROR => colors.error,
14771        DiagnosticSeverity::WARNING => colors.warning,
14772        DiagnosticSeverity::INFORMATION => colors.info,
14773        DiagnosticSeverity::HINT => colors.info,
14774        _ => colors.ignored,
14775    }
14776}
14777
14778pub fn styled_runs_for_code_label<'a>(
14779    label: &'a CodeLabel,
14780    syntax_theme: &'a theme::SyntaxTheme,
14781) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14782    let fade_out = HighlightStyle {
14783        fade_out: Some(0.35),
14784        ..Default::default()
14785    };
14786
14787    let mut prev_end = label.filter_range.end;
14788    label
14789        .runs
14790        .iter()
14791        .enumerate()
14792        .flat_map(move |(ix, (range, highlight_id))| {
14793            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14794                style
14795            } else {
14796                return Default::default();
14797            };
14798            let mut muted_style = style;
14799            muted_style.highlight(fade_out);
14800
14801            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14802            if range.start >= label.filter_range.end {
14803                if range.start > prev_end {
14804                    runs.push((prev_end..range.start, fade_out));
14805                }
14806                runs.push((range.clone(), muted_style));
14807            } else if range.end <= label.filter_range.end {
14808                runs.push((range.clone(), style));
14809            } else {
14810                runs.push((range.start..label.filter_range.end, style));
14811                runs.push((label.filter_range.end..range.end, muted_style));
14812            }
14813            prev_end = cmp::max(prev_end, range.end);
14814
14815            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14816                runs.push((prev_end..label.text.len(), fade_out));
14817            }
14818
14819            runs
14820        })
14821}
14822
14823pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14824    let mut prev_index = 0;
14825    let mut prev_codepoint: Option<char> = None;
14826    text.char_indices()
14827        .chain([(text.len(), '\0')])
14828        .filter_map(move |(index, codepoint)| {
14829            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14830            let is_boundary = index == text.len()
14831                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14832                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14833            if is_boundary {
14834                let chunk = &text[prev_index..index];
14835                prev_index = index;
14836                Some(chunk)
14837            } else {
14838                None
14839            }
14840        })
14841}
14842
14843pub trait RangeToAnchorExt: Sized {
14844    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14845
14846    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14847        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14848        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14849    }
14850}
14851
14852impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14853    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14854        let start_offset = self.start.to_offset(snapshot);
14855        let end_offset = self.end.to_offset(snapshot);
14856        if start_offset == end_offset {
14857            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14858        } else {
14859            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14860        }
14861    }
14862}
14863
14864pub trait RowExt {
14865    fn as_f32(&self) -> f32;
14866
14867    fn next_row(&self) -> Self;
14868
14869    fn previous_row(&self) -> Self;
14870
14871    fn minus(&self, other: Self) -> u32;
14872}
14873
14874impl RowExt for DisplayRow {
14875    fn as_f32(&self) -> f32 {
14876        self.0 as f32
14877    }
14878
14879    fn next_row(&self) -> Self {
14880        Self(self.0 + 1)
14881    }
14882
14883    fn previous_row(&self) -> Self {
14884        Self(self.0.saturating_sub(1))
14885    }
14886
14887    fn minus(&self, other: Self) -> u32 {
14888        self.0 - other.0
14889    }
14890}
14891
14892impl RowExt for MultiBufferRow {
14893    fn as_f32(&self) -> f32 {
14894        self.0 as f32
14895    }
14896
14897    fn next_row(&self) -> Self {
14898        Self(self.0 + 1)
14899    }
14900
14901    fn previous_row(&self) -> Self {
14902        Self(self.0.saturating_sub(1))
14903    }
14904
14905    fn minus(&self, other: Self) -> u32 {
14906        self.0 - other.0
14907    }
14908}
14909
14910trait RowRangeExt {
14911    type Row;
14912
14913    fn len(&self) -> usize;
14914
14915    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14916}
14917
14918impl RowRangeExt for Range<MultiBufferRow> {
14919    type Row = MultiBufferRow;
14920
14921    fn len(&self) -> usize {
14922        (self.end.0 - self.start.0) as usize
14923    }
14924
14925    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14926        (self.start.0..self.end.0).map(MultiBufferRow)
14927    }
14928}
14929
14930impl RowRangeExt for Range<DisplayRow> {
14931    type Row = DisplayRow;
14932
14933    fn len(&self) -> usize {
14934        (self.end.0 - self.start.0) as usize
14935    }
14936
14937    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14938        (self.start.0..self.end.0).map(DisplayRow)
14939    }
14940}
14941
14942fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14943    if hunk.diff_base_byte_range.is_empty() {
14944        DiffHunkStatus::Added
14945    } else if hunk.row_range.is_empty() {
14946        DiffHunkStatus::Removed
14947    } else {
14948        DiffHunkStatus::Modified
14949    }
14950}
14951
14952/// If select range has more than one line, we
14953/// just point the cursor to range.start.
14954fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14955    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14956        range
14957    } else {
14958        range.start..range.start
14959    }
14960}
14961
14962pub struct KillRing(ClipboardItem);
14963impl Global for KillRing {}
14964
14965const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);