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_visible_completions(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                                menu.show_inline_completion_hint(hint);
 3750                            }
 3751                        } else {
 3752                            editor.discard_inline_completion(false, cx);
 3753                        }
 3754
 3755                        *editor.context_menu.borrow_mut() =
 3756                            Some(CodeContextMenu::Completions(menu));
 3757
 3758                        cx.notify();
 3759                    } else if editor.completion_tasks.len() <= 1 {
 3760                        // If there are no more completion tasks and the last menu was
 3761                        // empty, we should hide it.
 3762                        let was_hidden = editor.hide_context_menu(cx).is_none();
 3763                        // If it was already hidden and we don't show inline
 3764                        // completions in the menu, we should also show the
 3765                        // inline-completion when available.
 3766                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3767                            editor.update_visible_inline_completion(cx);
 3768                        }
 3769                    }
 3770                })?;
 3771
 3772                Ok::<_, anyhow::Error>(())
 3773            }
 3774            .log_err()
 3775        });
 3776
 3777        self.completion_tasks.push((id, task));
 3778    }
 3779
 3780    pub fn confirm_completion(
 3781        &mut self,
 3782        action: &ConfirmCompletion,
 3783        cx: &mut ViewContext<Self>,
 3784    ) -> Option<Task<Result<()>>> {
 3785        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3786    }
 3787
 3788    pub fn compose_completion(
 3789        &mut self,
 3790        action: &ComposeCompletion,
 3791        cx: &mut ViewContext<Self>,
 3792    ) -> Option<Task<Result<()>>> {
 3793        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3794    }
 3795
 3796    fn do_completion(
 3797        &mut self,
 3798        item_ix: Option<usize>,
 3799        intent: CompletionIntent,
 3800        cx: &mut ViewContext<Editor>,
 3801    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3802        use language::ToOffset as _;
 3803
 3804        let completions_menu =
 3805            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3806                menu
 3807            } else {
 3808                return None;
 3809            };
 3810
 3811        let mat = completions_menu
 3812            .entries
 3813            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3814
 3815        let mat = match mat {
 3816            CompletionEntry::InlineCompletionHint { .. } => {
 3817                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3818                cx.stop_propagation();
 3819                return Some(Task::ready(Ok(())));
 3820            }
 3821            CompletionEntry::Match(mat) => {
 3822                if self.show_inline_completions_in_menu(cx) {
 3823                    self.discard_inline_completion(true, cx);
 3824                }
 3825                mat
 3826            }
 3827        };
 3828
 3829        let buffer_handle = completions_menu.buffer;
 3830        let completions = completions_menu.completions.borrow_mut();
 3831        let completion = completions.get(mat.candidate_id)?;
 3832        cx.stop_propagation();
 3833
 3834        let snippet;
 3835        let text;
 3836
 3837        if completion.is_snippet() {
 3838            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3839            text = snippet.as_ref().unwrap().text.clone();
 3840        } else {
 3841            snippet = None;
 3842            text = completion.new_text.clone();
 3843        };
 3844        let selections = self.selections.all::<usize>(cx);
 3845        let buffer = buffer_handle.read(cx);
 3846        let old_range = completion.old_range.to_offset(buffer);
 3847        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3848
 3849        let newest_selection = self.selections.newest_anchor();
 3850        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3851            return None;
 3852        }
 3853
 3854        let lookbehind = newest_selection
 3855            .start
 3856            .text_anchor
 3857            .to_offset(buffer)
 3858            .saturating_sub(old_range.start);
 3859        let lookahead = old_range
 3860            .end
 3861            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3862        let mut common_prefix_len = old_text
 3863            .bytes()
 3864            .zip(text.bytes())
 3865            .take_while(|(a, b)| a == b)
 3866            .count();
 3867
 3868        let snapshot = self.buffer.read(cx).snapshot(cx);
 3869        let mut range_to_replace: Option<Range<isize>> = None;
 3870        let mut ranges = Vec::new();
 3871        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3872        for selection in &selections {
 3873            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3874                let start = selection.start.saturating_sub(lookbehind);
 3875                let end = selection.end + lookahead;
 3876                if selection.id == newest_selection.id {
 3877                    range_to_replace = Some(
 3878                        ((start + common_prefix_len) as isize - selection.start as isize)
 3879                            ..(end as isize - selection.start as isize),
 3880                    );
 3881                }
 3882                ranges.push(start + common_prefix_len..end);
 3883            } else {
 3884                common_prefix_len = 0;
 3885                ranges.clear();
 3886                ranges.extend(selections.iter().map(|s| {
 3887                    if s.id == newest_selection.id {
 3888                        range_to_replace = Some(
 3889                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3890                                - selection.start as isize
 3891                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3892                                    - selection.start as isize,
 3893                        );
 3894                        old_range.clone()
 3895                    } else {
 3896                        s.start..s.end
 3897                    }
 3898                }));
 3899                break;
 3900            }
 3901            if !self.linked_edit_ranges.is_empty() {
 3902                let start_anchor = snapshot.anchor_before(selection.head());
 3903                let end_anchor = snapshot.anchor_after(selection.tail());
 3904                if let Some(ranges) = self
 3905                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3906                {
 3907                    for (buffer, edits) in ranges {
 3908                        linked_edits.entry(buffer.clone()).or_default().extend(
 3909                            edits
 3910                                .into_iter()
 3911                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3912                        );
 3913                    }
 3914                }
 3915            }
 3916        }
 3917        let text = &text[common_prefix_len..];
 3918
 3919        cx.emit(EditorEvent::InputHandled {
 3920            utf16_range_to_replace: range_to_replace,
 3921            text: text.into(),
 3922        });
 3923
 3924        self.transact(cx, |this, cx| {
 3925            if let Some(mut snippet) = snippet {
 3926                snippet.text = text.to_string();
 3927                for tabstop in snippet
 3928                    .tabstops
 3929                    .iter_mut()
 3930                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3931                {
 3932                    tabstop.start -= common_prefix_len as isize;
 3933                    tabstop.end -= common_prefix_len as isize;
 3934                }
 3935
 3936                this.insert_snippet(&ranges, snippet, cx).log_err();
 3937            } else {
 3938                this.buffer.update(cx, |buffer, cx| {
 3939                    buffer.edit(
 3940                        ranges.iter().map(|range| (range.clone(), text)),
 3941                        this.autoindent_mode.clone(),
 3942                        cx,
 3943                    );
 3944                });
 3945            }
 3946            for (buffer, edits) in linked_edits {
 3947                buffer.update(cx, |buffer, cx| {
 3948                    let snapshot = buffer.snapshot();
 3949                    let edits = edits
 3950                        .into_iter()
 3951                        .map(|(range, text)| {
 3952                            use text::ToPoint as TP;
 3953                            let end_point = TP::to_point(&range.end, &snapshot);
 3954                            let start_point = TP::to_point(&range.start, &snapshot);
 3955                            (start_point..end_point, text)
 3956                        })
 3957                        .sorted_by_key(|(range, _)| range.start)
 3958                        .collect::<Vec<_>>();
 3959                    buffer.edit(edits, None, cx);
 3960                })
 3961            }
 3962
 3963            this.refresh_inline_completion(true, false, cx);
 3964        });
 3965
 3966        let show_new_completions_on_confirm = completion
 3967            .confirm
 3968            .as_ref()
 3969            .map_or(false, |confirm| confirm(intent, cx));
 3970        if show_new_completions_on_confirm {
 3971            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3972        }
 3973
 3974        let provider = self.completion_provider.as_ref()?;
 3975        let apply_edits = provider.apply_additional_edits_for_completion(
 3976            buffer_handle,
 3977            completion.clone(),
 3978            true,
 3979            cx,
 3980        );
 3981
 3982        let editor_settings = EditorSettings::get_global(cx);
 3983        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 3984            // After the code completion is finished, users often want to know what signatures are needed.
 3985            // so we should automatically call signature_help
 3986            self.show_signature_help(&ShowSignatureHelp, cx);
 3987        }
 3988
 3989        Some(cx.foreground_executor().spawn(async move {
 3990            apply_edits.await?;
 3991            Ok(())
 3992        }))
 3993    }
 3994
 3995    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 3996        let mut context_menu = self.context_menu.borrow_mut();
 3997        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 3998            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 3999                // Toggle if we're selecting the same one
 4000                *context_menu = None;
 4001                cx.notify();
 4002                return;
 4003            } else {
 4004                // Otherwise, clear it and start a new one
 4005                *context_menu = None;
 4006                cx.notify();
 4007            }
 4008        }
 4009        drop(context_menu);
 4010        let snapshot = self.snapshot(cx);
 4011        let deployed_from_indicator = action.deployed_from_indicator;
 4012        let mut task = self.code_actions_task.take();
 4013        let action = action.clone();
 4014        cx.spawn(|editor, mut cx| async move {
 4015            while let Some(prev_task) = task {
 4016                prev_task.await.log_err();
 4017                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4018            }
 4019
 4020            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4021                if editor.focus_handle.is_focused(cx) {
 4022                    let multibuffer_point = action
 4023                        .deployed_from_indicator
 4024                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4025                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4026                    let (buffer, buffer_row) = snapshot
 4027                        .buffer_snapshot
 4028                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4029                        .and_then(|(buffer_snapshot, range)| {
 4030                            editor
 4031                                .buffer
 4032                                .read(cx)
 4033                                .buffer(buffer_snapshot.remote_id())
 4034                                .map(|buffer| (buffer, range.start.row))
 4035                        })?;
 4036                    let (_, code_actions) = editor
 4037                        .available_code_actions
 4038                        .clone()
 4039                        .and_then(|(location, code_actions)| {
 4040                            let snapshot = location.buffer.read(cx).snapshot();
 4041                            let point_range = location.range.to_point(&snapshot);
 4042                            let point_range = point_range.start.row..=point_range.end.row;
 4043                            if point_range.contains(&buffer_row) {
 4044                                Some((location, code_actions))
 4045                            } else {
 4046                                None
 4047                            }
 4048                        })
 4049                        .unzip();
 4050                    let buffer_id = buffer.read(cx).remote_id();
 4051                    let tasks = editor
 4052                        .tasks
 4053                        .get(&(buffer_id, buffer_row))
 4054                        .map(|t| Arc::new(t.to_owned()));
 4055                    if tasks.is_none() && code_actions.is_none() {
 4056                        return None;
 4057                    }
 4058
 4059                    editor.completion_tasks.clear();
 4060                    editor.discard_inline_completion(false, cx);
 4061                    let task_context =
 4062                        tasks
 4063                            .as_ref()
 4064                            .zip(editor.project.clone())
 4065                            .map(|(tasks, project)| {
 4066                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4067                            });
 4068
 4069                    Some(cx.spawn(|editor, mut cx| async move {
 4070                        let task_context = match task_context {
 4071                            Some(task_context) => task_context.await,
 4072                            None => None,
 4073                        };
 4074                        let resolved_tasks =
 4075                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4076                                Rc::new(ResolvedTasks {
 4077                                    templates: tasks.resolve(&task_context).collect(),
 4078                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4079                                        multibuffer_point.row,
 4080                                        tasks.column,
 4081                                    )),
 4082                                })
 4083                            });
 4084                        let spawn_straight_away = resolved_tasks
 4085                            .as_ref()
 4086                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4087                            && code_actions
 4088                                .as_ref()
 4089                                .map_or(true, |actions| actions.is_empty());
 4090                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4091                            *editor.context_menu.borrow_mut() =
 4092                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4093                                    buffer,
 4094                                    actions: CodeActionContents {
 4095                                        tasks: resolved_tasks,
 4096                                        actions: code_actions,
 4097                                    },
 4098                                    selected_item: Default::default(),
 4099                                    scroll_handle: UniformListScrollHandle::default(),
 4100                                    deployed_from_indicator,
 4101                                }));
 4102                            if spawn_straight_away {
 4103                                if let Some(task) = editor.confirm_code_action(
 4104                                    &ConfirmCodeAction { item_ix: Some(0) },
 4105                                    cx,
 4106                                ) {
 4107                                    cx.notify();
 4108                                    return task;
 4109                                }
 4110                            }
 4111                            cx.notify();
 4112                            Task::ready(Ok(()))
 4113                        }) {
 4114                            task.await
 4115                        } else {
 4116                            Ok(())
 4117                        }
 4118                    }))
 4119                } else {
 4120                    Some(Task::ready(Ok(())))
 4121                }
 4122            })?;
 4123            if let Some(task) = spawned_test_task {
 4124                task.await?;
 4125            }
 4126
 4127            Ok::<_, anyhow::Error>(())
 4128        })
 4129        .detach_and_log_err(cx);
 4130    }
 4131
 4132    pub fn confirm_code_action(
 4133        &mut self,
 4134        action: &ConfirmCodeAction,
 4135        cx: &mut ViewContext<Self>,
 4136    ) -> Option<Task<Result<()>>> {
 4137        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4138            menu
 4139        } else {
 4140            return None;
 4141        };
 4142        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4143        let action = actions_menu.actions.get(action_ix)?;
 4144        let title = action.label();
 4145        let buffer = actions_menu.buffer;
 4146        let workspace = self.workspace()?;
 4147
 4148        match action {
 4149            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4150                workspace.update(cx, |workspace, cx| {
 4151                    workspace::tasks::schedule_resolved_task(
 4152                        workspace,
 4153                        task_source_kind,
 4154                        resolved_task,
 4155                        false,
 4156                        cx,
 4157                    );
 4158
 4159                    Some(Task::ready(Ok(())))
 4160                })
 4161            }
 4162            CodeActionsItem::CodeAction {
 4163                excerpt_id,
 4164                action,
 4165                provider,
 4166            } => {
 4167                let apply_code_action =
 4168                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4169                let workspace = workspace.downgrade();
 4170                Some(cx.spawn(|editor, cx| async move {
 4171                    let project_transaction = apply_code_action.await?;
 4172                    Self::open_project_transaction(
 4173                        &editor,
 4174                        workspace,
 4175                        project_transaction,
 4176                        title,
 4177                        cx,
 4178                    )
 4179                    .await
 4180                }))
 4181            }
 4182        }
 4183    }
 4184
 4185    pub async fn open_project_transaction(
 4186        this: &WeakView<Editor>,
 4187        workspace: WeakView<Workspace>,
 4188        transaction: ProjectTransaction,
 4189        title: String,
 4190        mut cx: AsyncWindowContext,
 4191    ) -> Result<()> {
 4192        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4193        cx.update(|cx| {
 4194            entries.sort_unstable_by_key(|(buffer, _)| {
 4195                buffer.read(cx).file().map(|f| f.path().clone())
 4196            });
 4197        })?;
 4198
 4199        // If the project transaction's edits are all contained within this editor, then
 4200        // avoid opening a new editor to display them.
 4201
 4202        if let Some((buffer, transaction)) = entries.first() {
 4203            if entries.len() == 1 {
 4204                let excerpt = this.update(&mut cx, |editor, cx| {
 4205                    editor
 4206                        .buffer()
 4207                        .read(cx)
 4208                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4209                })?;
 4210                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4211                    if excerpted_buffer == *buffer {
 4212                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4213                            let excerpt_range = excerpt_range.to_offset(buffer);
 4214                            buffer
 4215                                .edited_ranges_for_transaction::<usize>(transaction)
 4216                                .all(|range| {
 4217                                    excerpt_range.start <= range.start
 4218                                        && excerpt_range.end >= range.end
 4219                                })
 4220                        })?;
 4221
 4222                        if all_edits_within_excerpt {
 4223                            return Ok(());
 4224                        }
 4225                    }
 4226                }
 4227            }
 4228        } else {
 4229            return Ok(());
 4230        }
 4231
 4232        let mut ranges_to_highlight = Vec::new();
 4233        let excerpt_buffer = cx.new_model(|cx| {
 4234            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4235            for (buffer_handle, transaction) in &entries {
 4236                let buffer = buffer_handle.read(cx);
 4237                ranges_to_highlight.extend(
 4238                    multibuffer.push_excerpts_with_context_lines(
 4239                        buffer_handle.clone(),
 4240                        buffer
 4241                            .edited_ranges_for_transaction::<usize>(transaction)
 4242                            .collect(),
 4243                        DEFAULT_MULTIBUFFER_CONTEXT,
 4244                        cx,
 4245                    ),
 4246                );
 4247            }
 4248            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4249            multibuffer
 4250        })?;
 4251
 4252        workspace.update(&mut cx, |workspace, cx| {
 4253            let project = workspace.project().clone();
 4254            let editor =
 4255                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4256            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4257            editor.update(cx, |editor, cx| {
 4258                editor.highlight_background::<Self>(
 4259                    &ranges_to_highlight,
 4260                    |theme| theme.editor_highlighted_line_background,
 4261                    cx,
 4262                );
 4263            });
 4264        })?;
 4265
 4266        Ok(())
 4267    }
 4268
 4269    pub fn clear_code_action_providers(&mut self) {
 4270        self.code_action_providers.clear();
 4271        self.available_code_actions.take();
 4272    }
 4273
 4274    pub fn push_code_action_provider(
 4275        &mut self,
 4276        provider: Rc<dyn CodeActionProvider>,
 4277        cx: &mut ViewContext<Self>,
 4278    ) {
 4279        self.code_action_providers.push(provider);
 4280        self.refresh_code_actions(cx);
 4281    }
 4282
 4283    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4284        let buffer = self.buffer.read(cx);
 4285        let newest_selection = self.selections.newest_anchor().clone();
 4286        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4287        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4288        if start_buffer != end_buffer {
 4289            return None;
 4290        }
 4291
 4292        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4293            cx.background_executor()
 4294                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4295                .await;
 4296
 4297            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4298                let providers = this.code_action_providers.clone();
 4299                let tasks = this
 4300                    .code_action_providers
 4301                    .iter()
 4302                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4303                    .collect::<Vec<_>>();
 4304                (providers, tasks)
 4305            })?;
 4306
 4307            let mut actions = Vec::new();
 4308            for (provider, provider_actions) in
 4309                providers.into_iter().zip(future::join_all(tasks).await)
 4310            {
 4311                if let Some(provider_actions) = provider_actions.log_err() {
 4312                    actions.extend(provider_actions.into_iter().map(|action| {
 4313                        AvailableCodeAction {
 4314                            excerpt_id: newest_selection.start.excerpt_id,
 4315                            action,
 4316                            provider: provider.clone(),
 4317                        }
 4318                    }));
 4319                }
 4320            }
 4321
 4322            this.update(&mut cx, |this, cx| {
 4323                this.available_code_actions = if actions.is_empty() {
 4324                    None
 4325                } else {
 4326                    Some((
 4327                        Location {
 4328                            buffer: start_buffer,
 4329                            range: start..end,
 4330                        },
 4331                        actions.into(),
 4332                    ))
 4333                };
 4334                cx.notify();
 4335            })
 4336        }));
 4337        None
 4338    }
 4339
 4340    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4341        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4342            self.show_git_blame_inline = false;
 4343
 4344            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4345                cx.background_executor().timer(delay).await;
 4346
 4347                this.update(&mut cx, |this, cx| {
 4348                    this.show_git_blame_inline = true;
 4349                    cx.notify();
 4350                })
 4351                .log_err();
 4352            }));
 4353        }
 4354    }
 4355
 4356    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4357        if self.pending_rename.is_some() {
 4358            return None;
 4359        }
 4360
 4361        let provider = self.semantics_provider.clone()?;
 4362        let buffer = self.buffer.read(cx);
 4363        let newest_selection = self.selections.newest_anchor().clone();
 4364        let cursor_position = newest_selection.head();
 4365        let (cursor_buffer, cursor_buffer_position) =
 4366            buffer.text_anchor_for_position(cursor_position, cx)?;
 4367        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4368        if cursor_buffer != tail_buffer {
 4369            return None;
 4370        }
 4371        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4372        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4373            cx.background_executor()
 4374                .timer(Duration::from_millis(debounce))
 4375                .await;
 4376
 4377            let highlights = if let Some(highlights) = cx
 4378                .update(|cx| {
 4379                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4380                })
 4381                .ok()
 4382                .flatten()
 4383            {
 4384                highlights.await.log_err()
 4385            } else {
 4386                None
 4387            };
 4388
 4389            if let Some(highlights) = highlights {
 4390                this.update(&mut cx, |this, cx| {
 4391                    if this.pending_rename.is_some() {
 4392                        return;
 4393                    }
 4394
 4395                    let buffer_id = cursor_position.buffer_id;
 4396                    let buffer = this.buffer.read(cx);
 4397                    if !buffer
 4398                        .text_anchor_for_position(cursor_position, cx)
 4399                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4400                    {
 4401                        return;
 4402                    }
 4403
 4404                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4405                    let mut write_ranges = Vec::new();
 4406                    let mut read_ranges = Vec::new();
 4407                    for highlight in highlights {
 4408                        for (excerpt_id, excerpt_range) in
 4409                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4410                        {
 4411                            let start = highlight
 4412                                .range
 4413                                .start
 4414                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4415                            let end = highlight
 4416                                .range
 4417                                .end
 4418                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4419                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4420                                continue;
 4421                            }
 4422
 4423                            let range = Anchor {
 4424                                buffer_id,
 4425                                excerpt_id,
 4426                                text_anchor: start,
 4427                            }..Anchor {
 4428                                buffer_id,
 4429                                excerpt_id,
 4430                                text_anchor: end,
 4431                            };
 4432                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4433                                write_ranges.push(range);
 4434                            } else {
 4435                                read_ranges.push(range);
 4436                            }
 4437                        }
 4438                    }
 4439
 4440                    this.highlight_background::<DocumentHighlightRead>(
 4441                        &read_ranges,
 4442                        |theme| theme.editor_document_highlight_read_background,
 4443                        cx,
 4444                    );
 4445                    this.highlight_background::<DocumentHighlightWrite>(
 4446                        &write_ranges,
 4447                        |theme| theme.editor_document_highlight_write_background,
 4448                        cx,
 4449                    );
 4450                    cx.notify();
 4451                })
 4452                .log_err();
 4453            }
 4454        }));
 4455        None
 4456    }
 4457
 4458    pub fn refresh_inline_completion(
 4459        &mut self,
 4460        debounce: bool,
 4461        user_requested: bool,
 4462        cx: &mut ViewContext<Self>,
 4463    ) -> Option<()> {
 4464        let provider = self.inline_completion_provider()?;
 4465        let cursor = self.selections.newest_anchor().head();
 4466        let (buffer, cursor_buffer_position) =
 4467            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4468
 4469        if !user_requested
 4470            && (!self.enable_inline_completions
 4471                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4472                || !self.is_focused(cx))
 4473        {
 4474            self.discard_inline_completion(false, cx);
 4475            return None;
 4476        }
 4477
 4478        self.update_visible_inline_completion(cx);
 4479        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4480        Some(())
 4481    }
 4482
 4483    fn cycle_inline_completion(
 4484        &mut self,
 4485        direction: Direction,
 4486        cx: &mut ViewContext<Self>,
 4487    ) -> Option<()> {
 4488        let provider = self.inline_completion_provider()?;
 4489        let cursor = self.selections.newest_anchor().head();
 4490        let (buffer, cursor_buffer_position) =
 4491            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4492        if !self.enable_inline_completions
 4493            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4494        {
 4495            return None;
 4496        }
 4497
 4498        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4499        self.update_visible_inline_completion(cx);
 4500
 4501        Some(())
 4502    }
 4503
 4504    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4505        if !self.has_active_inline_completion() {
 4506            self.refresh_inline_completion(false, true, cx);
 4507            return;
 4508        }
 4509
 4510        self.update_visible_inline_completion(cx);
 4511    }
 4512
 4513    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4514        self.show_cursor_names(cx);
 4515    }
 4516
 4517    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4518        self.show_cursor_names = true;
 4519        cx.notify();
 4520        cx.spawn(|this, mut cx| async move {
 4521            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4522            this.update(&mut cx, |this, cx| {
 4523                this.show_cursor_names = false;
 4524                cx.notify()
 4525            })
 4526            .ok()
 4527        })
 4528        .detach();
 4529    }
 4530
 4531    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4532        if self.has_active_inline_completion() {
 4533            self.cycle_inline_completion(Direction::Next, cx);
 4534        } else {
 4535            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4536            if is_copilot_disabled {
 4537                cx.propagate();
 4538            }
 4539        }
 4540    }
 4541
 4542    pub fn previous_inline_completion(
 4543        &mut self,
 4544        _: &PreviousInlineCompletion,
 4545        cx: &mut ViewContext<Self>,
 4546    ) {
 4547        if self.has_active_inline_completion() {
 4548            self.cycle_inline_completion(Direction::Prev, cx);
 4549        } else {
 4550            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4551            if is_copilot_disabled {
 4552                cx.propagate();
 4553            }
 4554        }
 4555    }
 4556
 4557    pub fn accept_inline_completion(
 4558        &mut self,
 4559        _: &AcceptInlineCompletion,
 4560        cx: &mut ViewContext<Self>,
 4561    ) {
 4562        if self.show_inline_completions_in_menu(cx) {
 4563            self.hide_context_menu(cx);
 4564        }
 4565
 4566        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4567            return;
 4568        };
 4569
 4570        self.report_inline_completion_event(true, cx);
 4571
 4572        match &active_inline_completion.completion {
 4573            InlineCompletion::Move(position) => {
 4574                let position = *position;
 4575                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4576                    selections.select_anchor_ranges([position..position]);
 4577                });
 4578            }
 4579            InlineCompletion::Edit(edits) => {
 4580                if let Some(provider) = self.inline_completion_provider() {
 4581                    provider.accept(cx);
 4582                }
 4583
 4584                let snapshot = self.buffer.read(cx).snapshot(cx);
 4585                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4586
 4587                self.buffer.update(cx, |buffer, cx| {
 4588                    buffer.edit(edits.iter().cloned(), None, cx)
 4589                });
 4590
 4591                self.change_selections(None, cx, |s| {
 4592                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4593                });
 4594
 4595                self.update_visible_inline_completion(cx);
 4596                if self.active_inline_completion.is_none() {
 4597                    self.refresh_inline_completion(true, true, cx);
 4598                }
 4599
 4600                cx.notify();
 4601            }
 4602        }
 4603    }
 4604
 4605    pub fn accept_partial_inline_completion(
 4606        &mut self,
 4607        _: &AcceptPartialInlineCompletion,
 4608        cx: &mut ViewContext<Self>,
 4609    ) {
 4610        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4611            return;
 4612        };
 4613        if self.selections.count() != 1 {
 4614            return;
 4615        }
 4616
 4617        self.report_inline_completion_event(true, cx);
 4618
 4619        match &active_inline_completion.completion {
 4620            InlineCompletion::Move(position) => {
 4621                let position = *position;
 4622                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4623                    selections.select_anchor_ranges([position..position]);
 4624                });
 4625            }
 4626            InlineCompletion::Edit(edits) => {
 4627                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4628                    let text = edits[0].1.as_str();
 4629                    let mut partial_completion = text
 4630                        .chars()
 4631                        .by_ref()
 4632                        .take_while(|c| c.is_alphabetic())
 4633                        .collect::<String>();
 4634                    if partial_completion.is_empty() {
 4635                        partial_completion = text
 4636                            .chars()
 4637                            .by_ref()
 4638                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4639                            .collect::<String>();
 4640                    }
 4641
 4642                    cx.emit(EditorEvent::InputHandled {
 4643                        utf16_range_to_replace: None,
 4644                        text: partial_completion.clone().into(),
 4645                    });
 4646
 4647                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4648
 4649                    self.refresh_inline_completion(true, true, cx);
 4650                    cx.notify();
 4651                }
 4652            }
 4653        }
 4654    }
 4655
 4656    fn discard_inline_completion(
 4657        &mut self,
 4658        should_report_inline_completion_event: bool,
 4659        cx: &mut ViewContext<Self>,
 4660    ) -> bool {
 4661        if should_report_inline_completion_event {
 4662            self.report_inline_completion_event(false, cx);
 4663        }
 4664
 4665        if let Some(provider) = self.inline_completion_provider() {
 4666            provider.discard(cx);
 4667        }
 4668
 4669        self.take_active_inline_completion(cx).is_some()
 4670    }
 4671
 4672    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4673        let Some(provider) = self.inline_completion_provider() else {
 4674            return;
 4675        };
 4676        let Some(project) = self.project.as_ref() else {
 4677            return;
 4678        };
 4679        let Some((_, buffer, _)) = self
 4680            .buffer
 4681            .read(cx)
 4682            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4683        else {
 4684            return;
 4685        };
 4686
 4687        let project = project.read(cx);
 4688        let extension = buffer
 4689            .read(cx)
 4690            .file()
 4691            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4692        project.client().telemetry().report_inline_completion_event(
 4693            provider.name().into(),
 4694            accepted,
 4695            extension,
 4696        );
 4697    }
 4698
 4699    pub fn has_active_inline_completion(&self) -> bool {
 4700        self.active_inline_completion.is_some()
 4701    }
 4702
 4703    fn take_active_inline_completion(
 4704        &mut self,
 4705        cx: &mut ViewContext<Self>,
 4706    ) -> Option<InlineCompletion> {
 4707        let active_inline_completion = self.active_inline_completion.take()?;
 4708        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4709        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4710        Some(active_inline_completion.completion)
 4711    }
 4712
 4713    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4714        let selection = self.selections.newest_anchor();
 4715        let cursor = selection.head();
 4716        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4717        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4718        let excerpt_id = cursor.excerpt_id;
 4719
 4720        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 4721            && (self.context_menu.borrow().is_some()
 4722                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 4723        if completions_menu_has_precedence
 4724            || !offset_selection.is_empty()
 4725            || self
 4726                .active_inline_completion
 4727                .as_ref()
 4728                .map_or(false, |completion| {
 4729                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4730                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4731                    !invalidation_range.contains(&offset_selection.head())
 4732                })
 4733        {
 4734            self.discard_inline_completion(false, cx);
 4735            return None;
 4736        }
 4737
 4738        self.take_active_inline_completion(cx);
 4739        let provider = self.inline_completion_provider()?;
 4740
 4741        let (buffer, cursor_buffer_position) =
 4742            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4743
 4744        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4745        let edits = completion
 4746            .edits
 4747            .into_iter()
 4748            .flat_map(|(range, new_text)| {
 4749                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4750                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4751                Some((start..end, new_text))
 4752            })
 4753            .collect::<Vec<_>>();
 4754        if edits.is_empty() {
 4755            return None;
 4756        }
 4757
 4758        let first_edit_start = edits.first().unwrap().0.start;
 4759        let edit_start_row = first_edit_start
 4760            .to_point(&multibuffer)
 4761            .row
 4762            .saturating_sub(2);
 4763
 4764        let last_edit_end = edits.last().unwrap().0.end;
 4765        let edit_end_row = cmp::min(
 4766            multibuffer.max_point().row,
 4767            last_edit_end.to_point(&multibuffer).row + 2,
 4768        );
 4769
 4770        let cursor_row = cursor.to_point(&multibuffer).row;
 4771
 4772        let mut inlay_ids = Vec::new();
 4773        let invalidation_row_range;
 4774        let completion;
 4775        if cursor_row < edit_start_row {
 4776            invalidation_row_range = cursor_row..edit_end_row;
 4777            completion = InlineCompletion::Move(first_edit_start);
 4778        } else if cursor_row > edit_end_row {
 4779            invalidation_row_range = edit_start_row..cursor_row;
 4780            completion = InlineCompletion::Move(first_edit_start);
 4781        } else {
 4782            if edits
 4783                .iter()
 4784                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4785            {
 4786                let mut inlays = Vec::new();
 4787                for (range, new_text) in &edits {
 4788                    let inlay = Inlay::inline_completion(
 4789                        post_inc(&mut self.next_inlay_id),
 4790                        range.start,
 4791                        new_text.as_str(),
 4792                    );
 4793                    inlay_ids.push(inlay.id);
 4794                    inlays.push(inlay);
 4795                }
 4796
 4797                self.splice_inlays(vec![], inlays, cx);
 4798            } else {
 4799                let background_color = cx.theme().status().deleted_background;
 4800                self.highlight_text::<InlineCompletionHighlight>(
 4801                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4802                    HighlightStyle {
 4803                        background_color: Some(background_color),
 4804                        ..Default::default()
 4805                    },
 4806                    cx,
 4807                );
 4808            }
 4809
 4810            invalidation_row_range = edit_start_row..edit_end_row;
 4811            completion = InlineCompletion::Edit(edits);
 4812        };
 4813
 4814        let invalidation_range = multibuffer
 4815            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4816            ..multibuffer.anchor_after(Point::new(
 4817                invalidation_row_range.end,
 4818                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4819            ));
 4820
 4821        self.active_inline_completion = Some(InlineCompletionState {
 4822            inlay_ids,
 4823            completion,
 4824            invalidation_range,
 4825        });
 4826
 4827        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 4828            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4829                match self.context_menu.borrow_mut().as_mut() {
 4830                    Some(CodeContextMenu::Completions(menu)) => {
 4831                        menu.show_inline_completion_hint(hint);
 4832                    }
 4833                    _ => {}
 4834                }
 4835            }
 4836        }
 4837
 4838        cx.notify();
 4839
 4840        Some(())
 4841    }
 4842
 4843    fn inline_completion_menu_hint(
 4844        &mut self,
 4845        cx: &mut ViewContext<Self>,
 4846    ) -> Option<InlineCompletionMenuHint> {
 4847        if self.has_active_inline_completion() {
 4848            let provider_name = self.inline_completion_provider()?.display_name();
 4849            let editor_snapshot = self.snapshot(cx);
 4850
 4851            let text = match &self.active_inline_completion.as_ref()?.completion {
 4852                InlineCompletion::Edit(edits) => {
 4853                    inline_completion_edit_text(&editor_snapshot, edits, true, cx)
 4854                }
 4855                InlineCompletion::Move(target) => {
 4856                    let target_point =
 4857                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4858                    let target_line = target_point.row + 1;
 4859                    InlineCompletionText::Move(
 4860                        format!("Jump to edit in line {}", target_line).into(),
 4861                    )
 4862                }
 4863            };
 4864
 4865            Some(InlineCompletionMenuHint {
 4866                provider_name,
 4867                text,
 4868            })
 4869        } else {
 4870            None
 4871        }
 4872    }
 4873
 4874    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4875        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4876    }
 4877
 4878    fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
 4879        EditorSettings::get_global(cx).show_inline_completions_in_menu
 4880            && self
 4881                .inline_completion_provider()
 4882                .map_or(false, |provider| provider.show_completions_in_menu())
 4883    }
 4884
 4885    fn render_code_actions_indicator(
 4886        &self,
 4887        _style: &EditorStyle,
 4888        row: DisplayRow,
 4889        is_active: bool,
 4890        cx: &mut ViewContext<Self>,
 4891    ) -> Option<IconButton> {
 4892        if self.available_code_actions.is_some() {
 4893            Some(
 4894                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4895                    .shape(ui::IconButtonShape::Square)
 4896                    .icon_size(IconSize::XSmall)
 4897                    .icon_color(Color::Muted)
 4898                    .toggle_state(is_active)
 4899                    .tooltip({
 4900                        let focus_handle = self.focus_handle.clone();
 4901                        move |cx| {
 4902                            Tooltip::for_action_in(
 4903                                "Toggle Code Actions",
 4904                                &ToggleCodeActions {
 4905                                    deployed_from_indicator: None,
 4906                                },
 4907                                &focus_handle,
 4908                                cx,
 4909                            )
 4910                        }
 4911                    })
 4912                    .on_click(cx.listener(move |editor, _e, cx| {
 4913                        editor.focus(cx);
 4914                        editor.toggle_code_actions(
 4915                            &ToggleCodeActions {
 4916                                deployed_from_indicator: Some(row),
 4917                            },
 4918                            cx,
 4919                        );
 4920                    })),
 4921            )
 4922        } else {
 4923            None
 4924        }
 4925    }
 4926
 4927    fn clear_tasks(&mut self) {
 4928        self.tasks.clear()
 4929    }
 4930
 4931    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4932        if self.tasks.insert(key, value).is_some() {
 4933            // This case should hopefully be rare, but just in case...
 4934            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4935        }
 4936    }
 4937
 4938    fn build_tasks_context(
 4939        project: &Model<Project>,
 4940        buffer: &Model<Buffer>,
 4941        buffer_row: u32,
 4942        tasks: &Arc<RunnableTasks>,
 4943        cx: &mut ViewContext<Self>,
 4944    ) -> Task<Option<task::TaskContext>> {
 4945        let position = Point::new(buffer_row, tasks.column);
 4946        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4947        let location = Location {
 4948            buffer: buffer.clone(),
 4949            range: range_start..range_start,
 4950        };
 4951        // Fill in the environmental variables from the tree-sitter captures
 4952        let mut captured_task_variables = TaskVariables::default();
 4953        for (capture_name, value) in tasks.extra_variables.clone() {
 4954            captured_task_variables.insert(
 4955                task::VariableName::Custom(capture_name.into()),
 4956                value.clone(),
 4957            );
 4958        }
 4959        project.update(cx, |project, cx| {
 4960            project.task_store().update(cx, |task_store, cx| {
 4961                task_store.task_context_for_location(captured_task_variables, location, cx)
 4962            })
 4963        })
 4964    }
 4965
 4966    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 4967        let Some((workspace, _)) = self.workspace.clone() else {
 4968            return;
 4969        };
 4970        let Some(project) = self.project.clone() else {
 4971            return;
 4972        };
 4973
 4974        // Try to find a closest, enclosing node using tree-sitter that has a
 4975        // task
 4976        let Some((buffer, buffer_row, tasks)) = self
 4977            .find_enclosing_node_task(cx)
 4978            // Or find the task that's closest in row-distance.
 4979            .or_else(|| self.find_closest_task(cx))
 4980        else {
 4981            return;
 4982        };
 4983
 4984        let reveal_strategy = action.reveal;
 4985        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 4986        cx.spawn(|_, mut cx| async move {
 4987            let context = task_context.await?;
 4988            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 4989
 4990            let resolved = resolved_task.resolved.as_mut()?;
 4991            resolved.reveal = reveal_strategy;
 4992
 4993            workspace
 4994                .update(&mut cx, |workspace, cx| {
 4995                    workspace::tasks::schedule_resolved_task(
 4996                        workspace,
 4997                        task_source_kind,
 4998                        resolved_task,
 4999                        false,
 5000                        cx,
 5001                    );
 5002                })
 5003                .ok()
 5004        })
 5005        .detach();
 5006    }
 5007
 5008    fn find_closest_task(
 5009        &mut self,
 5010        cx: &mut ViewContext<Self>,
 5011    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5012        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5013
 5014        let ((buffer_id, row), tasks) = self
 5015            .tasks
 5016            .iter()
 5017            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5018
 5019        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5020        let tasks = Arc::new(tasks.to_owned());
 5021        Some((buffer, *row, tasks))
 5022    }
 5023
 5024    fn find_enclosing_node_task(
 5025        &mut self,
 5026        cx: &mut ViewContext<Self>,
 5027    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5028        let snapshot = self.buffer.read(cx).snapshot(cx);
 5029        let offset = self.selections.newest::<usize>(cx).head();
 5030        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5031        let buffer_id = excerpt.buffer().remote_id();
 5032
 5033        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5034        let mut cursor = layer.node().walk();
 5035
 5036        while cursor.goto_first_child_for_byte(offset).is_some() {
 5037            if cursor.node().end_byte() == offset {
 5038                cursor.goto_next_sibling();
 5039            }
 5040        }
 5041
 5042        // Ascend to the smallest ancestor that contains the range and has a task.
 5043        loop {
 5044            let node = cursor.node();
 5045            let node_range = node.byte_range();
 5046            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5047
 5048            // Check if this node contains our offset
 5049            if node_range.start <= offset && node_range.end >= offset {
 5050                // If it contains offset, check for task
 5051                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5052                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5053                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5054                }
 5055            }
 5056
 5057            if !cursor.goto_parent() {
 5058                break;
 5059            }
 5060        }
 5061        None
 5062    }
 5063
 5064    fn render_run_indicator(
 5065        &self,
 5066        _style: &EditorStyle,
 5067        is_active: bool,
 5068        row: DisplayRow,
 5069        cx: &mut ViewContext<Self>,
 5070    ) -> IconButton {
 5071        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5072            .shape(ui::IconButtonShape::Square)
 5073            .icon_size(IconSize::XSmall)
 5074            .icon_color(Color::Muted)
 5075            .toggle_state(is_active)
 5076            .on_click(cx.listener(move |editor, _e, cx| {
 5077                editor.focus(cx);
 5078                editor.toggle_code_actions(
 5079                    &ToggleCodeActions {
 5080                        deployed_from_indicator: Some(row),
 5081                    },
 5082                    cx,
 5083                );
 5084            }))
 5085    }
 5086
 5087    #[cfg(feature = "test-support")]
 5088    pub fn context_menu_visible(&self) -> bool {
 5089        self.context_menu
 5090            .borrow()
 5091            .as_ref()
 5092            .map_or(false, |menu| menu.visible())
 5093    }
 5094
 5095    #[cfg(feature = "test-support")]
 5096    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5097        self.context_menu
 5098            .borrow()
 5099            .as_ref()
 5100            .map_or(false, |menu| match menu {
 5101                CodeContextMenu::Completions(menu) => menu.entries.first().map_or(false, |entry| {
 5102                    matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5103                }),
 5104                CodeContextMenu::CodeActions(_) => false,
 5105            })
 5106    }
 5107
 5108    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5109        self.context_menu
 5110            .borrow()
 5111            .as_ref()
 5112            .map(|menu| menu.origin(cursor_position))
 5113    }
 5114
 5115    fn render_context_menu(
 5116        &self,
 5117        style: &EditorStyle,
 5118        max_height_in_lines: u32,
 5119        cx: &mut ViewContext<Editor>,
 5120    ) -> Option<AnyElement> {
 5121        self.context_menu.borrow().as_ref().and_then(|menu| {
 5122            if menu.visible() {
 5123                Some(menu.render(style, max_height_in_lines, cx))
 5124            } else {
 5125                None
 5126            }
 5127        })
 5128    }
 5129
 5130    fn render_context_menu_aside(
 5131        &self,
 5132        style: &EditorStyle,
 5133        max_height: Pixels,
 5134        cx: &mut ViewContext<Editor>,
 5135    ) -> Option<AnyElement> {
 5136        self.context_menu.borrow().as_ref().and_then(|menu| {
 5137            if menu.visible() {
 5138                menu.render_aside(
 5139                    style,
 5140                    max_height,
 5141                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5142                    cx,
 5143                )
 5144            } else {
 5145                None
 5146            }
 5147        })
 5148    }
 5149
 5150    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5151        cx.notify();
 5152        self.completion_tasks.clear();
 5153        let context_menu = self.context_menu.borrow_mut().take();
 5154        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5155            self.update_visible_inline_completion(cx);
 5156        }
 5157        context_menu
 5158    }
 5159
 5160    fn show_snippet_choices(
 5161        &mut self,
 5162        choices: &Vec<String>,
 5163        selection: Range<Anchor>,
 5164        cx: &mut ViewContext<Self>,
 5165    ) {
 5166        if selection.start.buffer_id.is_none() {
 5167            return;
 5168        }
 5169        let buffer_id = selection.start.buffer_id.unwrap();
 5170        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5171        let id = post_inc(&mut self.next_completion_id);
 5172
 5173        if let Some(buffer) = buffer {
 5174            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5175                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5176            ));
 5177        }
 5178    }
 5179
 5180    pub fn insert_snippet(
 5181        &mut self,
 5182        insertion_ranges: &[Range<usize>],
 5183        snippet: Snippet,
 5184        cx: &mut ViewContext<Self>,
 5185    ) -> Result<()> {
 5186        struct Tabstop<T> {
 5187            is_end_tabstop: bool,
 5188            ranges: Vec<Range<T>>,
 5189            choices: Option<Vec<String>>,
 5190        }
 5191
 5192        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5193            let snippet_text: Arc<str> = snippet.text.clone().into();
 5194            buffer.edit(
 5195                insertion_ranges
 5196                    .iter()
 5197                    .cloned()
 5198                    .map(|range| (range, snippet_text.clone())),
 5199                Some(AutoindentMode::EachLine),
 5200                cx,
 5201            );
 5202
 5203            let snapshot = &*buffer.read(cx);
 5204            let snippet = &snippet;
 5205            snippet
 5206                .tabstops
 5207                .iter()
 5208                .map(|tabstop| {
 5209                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5210                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5211                    });
 5212                    let mut tabstop_ranges = tabstop
 5213                        .ranges
 5214                        .iter()
 5215                        .flat_map(|tabstop_range| {
 5216                            let mut delta = 0_isize;
 5217                            insertion_ranges.iter().map(move |insertion_range| {
 5218                                let insertion_start = insertion_range.start as isize + delta;
 5219                                delta +=
 5220                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5221
 5222                                let start = ((insertion_start + tabstop_range.start) as usize)
 5223                                    .min(snapshot.len());
 5224                                let end = ((insertion_start + tabstop_range.end) as usize)
 5225                                    .min(snapshot.len());
 5226                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5227                            })
 5228                        })
 5229                        .collect::<Vec<_>>();
 5230                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5231
 5232                    Tabstop {
 5233                        is_end_tabstop,
 5234                        ranges: tabstop_ranges,
 5235                        choices: tabstop.choices.clone(),
 5236                    }
 5237                })
 5238                .collect::<Vec<_>>()
 5239        });
 5240        if let Some(tabstop) = tabstops.first() {
 5241            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5242                s.select_ranges(tabstop.ranges.iter().cloned());
 5243            });
 5244
 5245            if let Some(choices) = &tabstop.choices {
 5246                if let Some(selection) = tabstop.ranges.first() {
 5247                    self.show_snippet_choices(choices, selection.clone(), cx)
 5248                }
 5249            }
 5250
 5251            // If we're already at the last tabstop and it's at the end of the snippet,
 5252            // we're done, we don't need to keep the state around.
 5253            if !tabstop.is_end_tabstop {
 5254                let choices = tabstops
 5255                    .iter()
 5256                    .map(|tabstop| tabstop.choices.clone())
 5257                    .collect();
 5258
 5259                let ranges = tabstops
 5260                    .into_iter()
 5261                    .map(|tabstop| tabstop.ranges)
 5262                    .collect::<Vec<_>>();
 5263
 5264                self.snippet_stack.push(SnippetState {
 5265                    active_index: 0,
 5266                    ranges,
 5267                    choices,
 5268                });
 5269            }
 5270
 5271            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5272            if self.autoclose_regions.is_empty() {
 5273                let snapshot = self.buffer.read(cx).snapshot(cx);
 5274                for selection in &mut self.selections.all::<Point>(cx) {
 5275                    let selection_head = selection.head();
 5276                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5277                        continue;
 5278                    };
 5279
 5280                    let mut bracket_pair = None;
 5281                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5282                    let prev_chars = snapshot
 5283                        .reversed_chars_at(selection_head)
 5284                        .collect::<String>();
 5285                    for (pair, enabled) in scope.brackets() {
 5286                        if enabled
 5287                            && pair.close
 5288                            && prev_chars.starts_with(pair.start.as_str())
 5289                            && next_chars.starts_with(pair.end.as_str())
 5290                        {
 5291                            bracket_pair = Some(pair.clone());
 5292                            break;
 5293                        }
 5294                    }
 5295                    if let Some(pair) = bracket_pair {
 5296                        let start = snapshot.anchor_after(selection_head);
 5297                        let end = snapshot.anchor_after(selection_head);
 5298                        self.autoclose_regions.push(AutocloseRegion {
 5299                            selection_id: selection.id,
 5300                            range: start..end,
 5301                            pair,
 5302                        });
 5303                    }
 5304                }
 5305            }
 5306        }
 5307        Ok(())
 5308    }
 5309
 5310    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5311        self.move_to_snippet_tabstop(Bias::Right, cx)
 5312    }
 5313
 5314    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5315        self.move_to_snippet_tabstop(Bias::Left, cx)
 5316    }
 5317
 5318    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5319        if let Some(mut snippet) = self.snippet_stack.pop() {
 5320            match bias {
 5321                Bias::Left => {
 5322                    if snippet.active_index > 0 {
 5323                        snippet.active_index -= 1;
 5324                    } else {
 5325                        self.snippet_stack.push(snippet);
 5326                        return false;
 5327                    }
 5328                }
 5329                Bias::Right => {
 5330                    if snippet.active_index + 1 < snippet.ranges.len() {
 5331                        snippet.active_index += 1;
 5332                    } else {
 5333                        self.snippet_stack.push(snippet);
 5334                        return false;
 5335                    }
 5336                }
 5337            }
 5338            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5339                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5340                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5341                });
 5342
 5343                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5344                    if let Some(selection) = current_ranges.first() {
 5345                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5346                    }
 5347                }
 5348
 5349                // If snippet state is not at the last tabstop, push it back on the stack
 5350                if snippet.active_index + 1 < snippet.ranges.len() {
 5351                    self.snippet_stack.push(snippet);
 5352                }
 5353                return true;
 5354            }
 5355        }
 5356
 5357        false
 5358    }
 5359
 5360    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5361        self.transact(cx, |this, cx| {
 5362            this.select_all(&SelectAll, cx);
 5363            this.insert("", cx);
 5364        });
 5365    }
 5366
 5367    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5368        self.transact(cx, |this, cx| {
 5369            this.select_autoclose_pair(cx);
 5370            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5371            if !this.linked_edit_ranges.is_empty() {
 5372                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5373                let snapshot = this.buffer.read(cx).snapshot(cx);
 5374
 5375                for selection in selections.iter() {
 5376                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5377                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5378                    if selection_start.buffer_id != selection_end.buffer_id {
 5379                        continue;
 5380                    }
 5381                    if let Some(ranges) =
 5382                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5383                    {
 5384                        for (buffer, entries) in ranges {
 5385                            linked_ranges.entry(buffer).or_default().extend(entries);
 5386                        }
 5387                    }
 5388                }
 5389            }
 5390
 5391            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5392            if !this.selections.line_mode {
 5393                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5394                for selection in &mut selections {
 5395                    if selection.is_empty() {
 5396                        let old_head = selection.head();
 5397                        let mut new_head =
 5398                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5399                                .to_point(&display_map);
 5400                        if let Some((buffer, line_buffer_range)) = display_map
 5401                            .buffer_snapshot
 5402                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5403                        {
 5404                            let indent_size =
 5405                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5406                            let indent_len = match indent_size.kind {
 5407                                IndentKind::Space => {
 5408                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5409                                }
 5410                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5411                            };
 5412                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5413                                let indent_len = indent_len.get();
 5414                                new_head = cmp::min(
 5415                                    new_head,
 5416                                    MultiBufferPoint::new(
 5417                                        old_head.row,
 5418                                        ((old_head.column - 1) / indent_len) * indent_len,
 5419                                    ),
 5420                                );
 5421                            }
 5422                        }
 5423
 5424                        selection.set_head(new_head, SelectionGoal::None);
 5425                    }
 5426                }
 5427            }
 5428
 5429            this.signature_help_state.set_backspace_pressed(true);
 5430            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5431            this.insert("", cx);
 5432            let empty_str: Arc<str> = Arc::from("");
 5433            for (buffer, edits) in linked_ranges {
 5434                let snapshot = buffer.read(cx).snapshot();
 5435                use text::ToPoint as TP;
 5436
 5437                let edits = edits
 5438                    .into_iter()
 5439                    .map(|range| {
 5440                        let end_point = TP::to_point(&range.end, &snapshot);
 5441                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5442
 5443                        if end_point == start_point {
 5444                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5445                                .saturating_sub(1);
 5446                            start_point =
 5447                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5448                        };
 5449
 5450                        (start_point..end_point, empty_str.clone())
 5451                    })
 5452                    .sorted_by_key(|(range, _)| range.start)
 5453                    .collect::<Vec<_>>();
 5454                buffer.update(cx, |this, cx| {
 5455                    this.edit(edits, None, cx);
 5456                })
 5457            }
 5458            this.refresh_inline_completion(true, false, cx);
 5459            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5460        });
 5461    }
 5462
 5463    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5464        self.transact(cx, |this, cx| {
 5465            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5466                let line_mode = s.line_mode;
 5467                s.move_with(|map, selection| {
 5468                    if selection.is_empty() && !line_mode {
 5469                        let cursor = movement::right(map, selection.head());
 5470                        selection.end = cursor;
 5471                        selection.reversed = true;
 5472                        selection.goal = SelectionGoal::None;
 5473                    }
 5474                })
 5475            });
 5476            this.insert("", cx);
 5477            this.refresh_inline_completion(true, false, cx);
 5478        });
 5479    }
 5480
 5481    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5482        if self.move_to_prev_snippet_tabstop(cx) {
 5483            return;
 5484        }
 5485
 5486        self.outdent(&Outdent, cx);
 5487    }
 5488
 5489    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5490        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5491            return;
 5492        }
 5493
 5494        let mut selections = self.selections.all_adjusted(cx);
 5495        let buffer = self.buffer.read(cx);
 5496        let snapshot = buffer.snapshot(cx);
 5497        let rows_iter = selections.iter().map(|s| s.head().row);
 5498        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5499
 5500        let mut edits = Vec::new();
 5501        let mut prev_edited_row = 0;
 5502        let mut row_delta = 0;
 5503        for selection in &mut selections {
 5504            if selection.start.row != prev_edited_row {
 5505                row_delta = 0;
 5506            }
 5507            prev_edited_row = selection.end.row;
 5508
 5509            // If the selection is non-empty, then increase the indentation of the selected lines.
 5510            if !selection.is_empty() {
 5511                row_delta =
 5512                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5513                continue;
 5514            }
 5515
 5516            // If the selection is empty and the cursor is in the leading whitespace before the
 5517            // suggested indentation, then auto-indent the line.
 5518            let cursor = selection.head();
 5519            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5520            if let Some(suggested_indent) =
 5521                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5522            {
 5523                if cursor.column < suggested_indent.len
 5524                    && cursor.column <= current_indent.len
 5525                    && current_indent.len <= suggested_indent.len
 5526                {
 5527                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5528                    selection.end = selection.start;
 5529                    if row_delta == 0 {
 5530                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5531                            cursor.row,
 5532                            current_indent,
 5533                            suggested_indent,
 5534                        ));
 5535                        row_delta = suggested_indent.len - current_indent.len;
 5536                    }
 5537                    continue;
 5538                }
 5539            }
 5540
 5541            // Otherwise, insert a hard or soft tab.
 5542            let settings = buffer.settings_at(cursor, cx);
 5543            let tab_size = if settings.hard_tabs {
 5544                IndentSize::tab()
 5545            } else {
 5546                let tab_size = settings.tab_size.get();
 5547                let char_column = snapshot
 5548                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5549                    .flat_map(str::chars)
 5550                    .count()
 5551                    + row_delta as usize;
 5552                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5553                IndentSize::spaces(chars_to_next_tab_stop)
 5554            };
 5555            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5556            selection.end = selection.start;
 5557            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5558            row_delta += tab_size.len;
 5559        }
 5560
 5561        self.transact(cx, |this, cx| {
 5562            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5563            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5564            this.refresh_inline_completion(true, false, cx);
 5565        });
 5566    }
 5567
 5568    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5569        if self.read_only(cx) {
 5570            return;
 5571        }
 5572        let mut selections = self.selections.all::<Point>(cx);
 5573        let mut prev_edited_row = 0;
 5574        let mut row_delta = 0;
 5575        let mut edits = Vec::new();
 5576        let buffer = self.buffer.read(cx);
 5577        let snapshot = buffer.snapshot(cx);
 5578        for selection in &mut selections {
 5579            if selection.start.row != prev_edited_row {
 5580                row_delta = 0;
 5581            }
 5582            prev_edited_row = selection.end.row;
 5583
 5584            row_delta =
 5585                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5586        }
 5587
 5588        self.transact(cx, |this, cx| {
 5589            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5590            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5591        });
 5592    }
 5593
 5594    fn indent_selection(
 5595        buffer: &MultiBuffer,
 5596        snapshot: &MultiBufferSnapshot,
 5597        selection: &mut Selection<Point>,
 5598        edits: &mut Vec<(Range<Point>, String)>,
 5599        delta_for_start_row: u32,
 5600        cx: &AppContext,
 5601    ) -> u32 {
 5602        let settings = buffer.settings_at(selection.start, cx);
 5603        let tab_size = settings.tab_size.get();
 5604        let indent_kind = if settings.hard_tabs {
 5605            IndentKind::Tab
 5606        } else {
 5607            IndentKind::Space
 5608        };
 5609        let mut start_row = selection.start.row;
 5610        let mut end_row = selection.end.row + 1;
 5611
 5612        // If a selection ends at the beginning of a line, don't indent
 5613        // that last line.
 5614        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5615            end_row -= 1;
 5616        }
 5617
 5618        // Avoid re-indenting a row that has already been indented by a
 5619        // previous selection, but still update this selection's column
 5620        // to reflect that indentation.
 5621        if delta_for_start_row > 0 {
 5622            start_row += 1;
 5623            selection.start.column += delta_for_start_row;
 5624            if selection.end.row == selection.start.row {
 5625                selection.end.column += delta_for_start_row;
 5626            }
 5627        }
 5628
 5629        let mut delta_for_end_row = 0;
 5630        let has_multiple_rows = start_row + 1 != end_row;
 5631        for row in start_row..end_row {
 5632            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5633            let indent_delta = match (current_indent.kind, indent_kind) {
 5634                (IndentKind::Space, IndentKind::Space) => {
 5635                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5636                    IndentSize::spaces(columns_to_next_tab_stop)
 5637                }
 5638                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5639                (_, IndentKind::Tab) => IndentSize::tab(),
 5640            };
 5641
 5642            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5643                0
 5644            } else {
 5645                selection.start.column
 5646            };
 5647            let row_start = Point::new(row, start);
 5648            edits.push((
 5649                row_start..row_start,
 5650                indent_delta.chars().collect::<String>(),
 5651            ));
 5652
 5653            // Update this selection's endpoints to reflect the indentation.
 5654            if row == selection.start.row {
 5655                selection.start.column += indent_delta.len;
 5656            }
 5657            if row == selection.end.row {
 5658                selection.end.column += indent_delta.len;
 5659                delta_for_end_row = indent_delta.len;
 5660            }
 5661        }
 5662
 5663        if selection.start.row == selection.end.row {
 5664            delta_for_start_row + delta_for_end_row
 5665        } else {
 5666            delta_for_end_row
 5667        }
 5668    }
 5669
 5670    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5671        if self.read_only(cx) {
 5672            return;
 5673        }
 5674        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5675        let selections = self.selections.all::<Point>(cx);
 5676        let mut deletion_ranges = Vec::new();
 5677        let mut last_outdent = None;
 5678        {
 5679            let buffer = self.buffer.read(cx);
 5680            let snapshot = buffer.snapshot(cx);
 5681            for selection in &selections {
 5682                let settings = buffer.settings_at(selection.start, cx);
 5683                let tab_size = settings.tab_size.get();
 5684                let mut rows = selection.spanned_rows(false, &display_map);
 5685
 5686                // Avoid re-outdenting a row that has already been outdented by a
 5687                // previous selection.
 5688                if let Some(last_row) = last_outdent {
 5689                    if last_row == rows.start {
 5690                        rows.start = rows.start.next_row();
 5691                    }
 5692                }
 5693                let has_multiple_rows = rows.len() > 1;
 5694                for row in rows.iter_rows() {
 5695                    let indent_size = snapshot.indent_size_for_line(row);
 5696                    if indent_size.len > 0 {
 5697                        let deletion_len = match indent_size.kind {
 5698                            IndentKind::Space => {
 5699                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5700                                if columns_to_prev_tab_stop == 0 {
 5701                                    tab_size
 5702                                } else {
 5703                                    columns_to_prev_tab_stop
 5704                                }
 5705                            }
 5706                            IndentKind::Tab => 1,
 5707                        };
 5708                        let start = if has_multiple_rows
 5709                            || deletion_len > selection.start.column
 5710                            || indent_size.len < selection.start.column
 5711                        {
 5712                            0
 5713                        } else {
 5714                            selection.start.column - deletion_len
 5715                        };
 5716                        deletion_ranges.push(
 5717                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5718                        );
 5719                        last_outdent = Some(row);
 5720                    }
 5721                }
 5722            }
 5723        }
 5724
 5725        self.transact(cx, |this, cx| {
 5726            this.buffer.update(cx, |buffer, cx| {
 5727                let empty_str: Arc<str> = Arc::default();
 5728                buffer.edit(
 5729                    deletion_ranges
 5730                        .into_iter()
 5731                        .map(|range| (range, empty_str.clone())),
 5732                    None,
 5733                    cx,
 5734                );
 5735            });
 5736            let selections = this.selections.all::<usize>(cx);
 5737            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5738        });
 5739    }
 5740
 5741    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5742        if self.read_only(cx) {
 5743            return;
 5744        }
 5745        let selections = self
 5746            .selections
 5747            .all::<usize>(cx)
 5748            .into_iter()
 5749            .map(|s| s.range());
 5750
 5751        self.transact(cx, |this, cx| {
 5752            this.buffer.update(cx, |buffer, cx| {
 5753                buffer.autoindent_ranges(selections, cx);
 5754            });
 5755            let selections = this.selections.all::<usize>(cx);
 5756            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5757        });
 5758    }
 5759
 5760    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5761        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5762        let selections = self.selections.all::<Point>(cx);
 5763
 5764        let mut new_cursors = Vec::new();
 5765        let mut edit_ranges = Vec::new();
 5766        let mut selections = selections.iter().peekable();
 5767        while let Some(selection) = selections.next() {
 5768            let mut rows = selection.spanned_rows(false, &display_map);
 5769            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5770
 5771            // Accumulate contiguous regions of rows that we want to delete.
 5772            while let Some(next_selection) = selections.peek() {
 5773                let next_rows = next_selection.spanned_rows(false, &display_map);
 5774                if next_rows.start <= rows.end {
 5775                    rows.end = next_rows.end;
 5776                    selections.next().unwrap();
 5777                } else {
 5778                    break;
 5779                }
 5780            }
 5781
 5782            let buffer = &display_map.buffer_snapshot;
 5783            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5784            let edit_end;
 5785            let cursor_buffer_row;
 5786            if buffer.max_point().row >= rows.end.0 {
 5787                // If there's a line after the range, delete the \n from the end of the row range
 5788                // and position the cursor on the next line.
 5789                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5790                cursor_buffer_row = rows.end;
 5791            } else {
 5792                // If there isn't a line after the range, delete the \n from the line before the
 5793                // start of the row range and position the cursor there.
 5794                edit_start = edit_start.saturating_sub(1);
 5795                edit_end = buffer.len();
 5796                cursor_buffer_row = rows.start.previous_row();
 5797            }
 5798
 5799            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5800            *cursor.column_mut() =
 5801                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5802
 5803            new_cursors.push((
 5804                selection.id,
 5805                buffer.anchor_after(cursor.to_point(&display_map)),
 5806            ));
 5807            edit_ranges.push(edit_start..edit_end);
 5808        }
 5809
 5810        self.transact(cx, |this, cx| {
 5811            let buffer = this.buffer.update(cx, |buffer, cx| {
 5812                let empty_str: Arc<str> = Arc::default();
 5813                buffer.edit(
 5814                    edit_ranges
 5815                        .into_iter()
 5816                        .map(|range| (range, empty_str.clone())),
 5817                    None,
 5818                    cx,
 5819                );
 5820                buffer.snapshot(cx)
 5821            });
 5822            let new_selections = new_cursors
 5823                .into_iter()
 5824                .map(|(id, cursor)| {
 5825                    let cursor = cursor.to_point(&buffer);
 5826                    Selection {
 5827                        id,
 5828                        start: cursor,
 5829                        end: cursor,
 5830                        reversed: false,
 5831                        goal: SelectionGoal::None,
 5832                    }
 5833                })
 5834                .collect();
 5835
 5836            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5837                s.select(new_selections);
 5838            });
 5839        });
 5840    }
 5841
 5842    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5843        if self.read_only(cx) {
 5844            return;
 5845        }
 5846        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5847        for selection in self.selections.all::<Point>(cx) {
 5848            let start = MultiBufferRow(selection.start.row);
 5849            // Treat single line selections as if they include the next line. Otherwise this action
 5850            // would do nothing for single line selections individual cursors.
 5851            let end = if selection.start.row == selection.end.row {
 5852                MultiBufferRow(selection.start.row + 1)
 5853            } else {
 5854                MultiBufferRow(selection.end.row)
 5855            };
 5856
 5857            if let Some(last_row_range) = row_ranges.last_mut() {
 5858                if start <= last_row_range.end {
 5859                    last_row_range.end = end;
 5860                    continue;
 5861                }
 5862            }
 5863            row_ranges.push(start..end);
 5864        }
 5865
 5866        let snapshot = self.buffer.read(cx).snapshot(cx);
 5867        let mut cursor_positions = Vec::new();
 5868        for row_range in &row_ranges {
 5869            let anchor = snapshot.anchor_before(Point::new(
 5870                row_range.end.previous_row().0,
 5871                snapshot.line_len(row_range.end.previous_row()),
 5872            ));
 5873            cursor_positions.push(anchor..anchor);
 5874        }
 5875
 5876        self.transact(cx, |this, cx| {
 5877            for row_range in row_ranges.into_iter().rev() {
 5878                for row in row_range.iter_rows().rev() {
 5879                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5880                    let next_line_row = row.next_row();
 5881                    let indent = snapshot.indent_size_for_line(next_line_row);
 5882                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5883
 5884                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5885                        " "
 5886                    } else {
 5887                        ""
 5888                    };
 5889
 5890                    this.buffer.update(cx, |buffer, cx| {
 5891                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5892                    });
 5893                }
 5894            }
 5895
 5896            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5897                s.select_anchor_ranges(cursor_positions)
 5898            });
 5899        });
 5900    }
 5901
 5902    pub fn sort_lines_case_sensitive(
 5903        &mut self,
 5904        _: &SortLinesCaseSensitive,
 5905        cx: &mut ViewContext<Self>,
 5906    ) {
 5907        self.manipulate_lines(cx, |lines| lines.sort())
 5908    }
 5909
 5910    pub fn sort_lines_case_insensitive(
 5911        &mut self,
 5912        _: &SortLinesCaseInsensitive,
 5913        cx: &mut ViewContext<Self>,
 5914    ) {
 5915        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5916    }
 5917
 5918    pub fn unique_lines_case_insensitive(
 5919        &mut self,
 5920        _: &UniqueLinesCaseInsensitive,
 5921        cx: &mut ViewContext<Self>,
 5922    ) {
 5923        self.manipulate_lines(cx, |lines| {
 5924            let mut seen = HashSet::default();
 5925            lines.retain(|line| seen.insert(line.to_lowercase()));
 5926        })
 5927    }
 5928
 5929    pub fn unique_lines_case_sensitive(
 5930        &mut self,
 5931        _: &UniqueLinesCaseSensitive,
 5932        cx: &mut ViewContext<Self>,
 5933    ) {
 5934        self.manipulate_lines(cx, |lines| {
 5935            let mut seen = HashSet::default();
 5936            lines.retain(|line| seen.insert(*line));
 5937        })
 5938    }
 5939
 5940    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 5941        let mut revert_changes = HashMap::default();
 5942        let snapshot = self.snapshot(cx);
 5943        for hunk in hunks_for_ranges(
 5944            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 5945            &snapshot,
 5946        ) {
 5947            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5948        }
 5949        if !revert_changes.is_empty() {
 5950            self.transact(cx, |editor, cx| {
 5951                editor.revert(revert_changes, cx);
 5952            });
 5953        }
 5954    }
 5955
 5956    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 5957        let Some(project) = self.project.clone() else {
 5958            return;
 5959        };
 5960        self.reload(project, cx).detach_and_notify_err(cx);
 5961    }
 5962
 5963    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5964        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 5965        if !revert_changes.is_empty() {
 5966            self.transact(cx, |editor, cx| {
 5967                editor.revert(revert_changes, cx);
 5968            });
 5969        }
 5970    }
 5971
 5972    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 5973        let snapshot = self.buffer.read(cx).read(cx);
 5974        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 5975            drop(snapshot);
 5976            let mut revert_changes = HashMap::default();
 5977            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5978            if !revert_changes.is_empty() {
 5979                self.revert(revert_changes, cx)
 5980            }
 5981        }
 5982    }
 5983
 5984    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5985        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5986            let project_path = buffer.read(cx).project_path(cx)?;
 5987            let project = self.project.as_ref()?.read(cx);
 5988            let entry = project.entry_for_path(&project_path, cx)?;
 5989            let parent = match &entry.canonical_path {
 5990                Some(canonical_path) => canonical_path.to_path_buf(),
 5991                None => project.absolute_path(&project_path, cx)?,
 5992            }
 5993            .parent()?
 5994            .to_path_buf();
 5995            Some(parent)
 5996        }) {
 5997            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5998        }
 5999    }
 6000
 6001    fn gather_revert_changes(
 6002        &mut self,
 6003        selections: &[Selection<Point>],
 6004        cx: &mut ViewContext<'_, Editor>,
 6005    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6006        let mut revert_changes = HashMap::default();
 6007        let snapshot = self.snapshot(cx);
 6008        for hunk in hunks_for_selections(&snapshot, selections) {
 6009            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6010        }
 6011        revert_changes
 6012    }
 6013
 6014    pub fn prepare_revert_change(
 6015        &mut self,
 6016        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6017        hunk: &MultiBufferDiffHunk,
 6018        cx: &AppContext,
 6019    ) -> Option<()> {
 6020        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6021        let buffer = buffer.read(cx);
 6022        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6023        let original_text = change_set
 6024            .read(cx)
 6025            .base_text
 6026            .as_ref()?
 6027            .read(cx)
 6028            .as_rope()
 6029            .slice(hunk.diff_base_byte_range.clone());
 6030        let buffer_snapshot = buffer.snapshot();
 6031        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6032        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6033            probe
 6034                .0
 6035                .start
 6036                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6037                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6038        }) {
 6039            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6040            Some(())
 6041        } else {
 6042            None
 6043        }
 6044    }
 6045
 6046    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6047        self.manipulate_lines(cx, |lines| lines.reverse())
 6048    }
 6049
 6050    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6051        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6052    }
 6053
 6054    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6055    where
 6056        Fn: FnMut(&mut Vec<&str>),
 6057    {
 6058        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6059        let buffer = self.buffer.read(cx).snapshot(cx);
 6060
 6061        let mut edits = Vec::new();
 6062
 6063        let selections = self.selections.all::<Point>(cx);
 6064        let mut selections = selections.iter().peekable();
 6065        let mut contiguous_row_selections = Vec::new();
 6066        let mut new_selections = Vec::new();
 6067        let mut added_lines = 0;
 6068        let mut removed_lines = 0;
 6069
 6070        while let Some(selection) = selections.next() {
 6071            let (start_row, end_row) = consume_contiguous_rows(
 6072                &mut contiguous_row_selections,
 6073                selection,
 6074                &display_map,
 6075                &mut selections,
 6076            );
 6077
 6078            let start_point = Point::new(start_row.0, 0);
 6079            let end_point = Point::new(
 6080                end_row.previous_row().0,
 6081                buffer.line_len(end_row.previous_row()),
 6082            );
 6083            let text = buffer
 6084                .text_for_range(start_point..end_point)
 6085                .collect::<String>();
 6086
 6087            let mut lines = text.split('\n').collect_vec();
 6088
 6089            let lines_before = lines.len();
 6090            callback(&mut lines);
 6091            let lines_after = lines.len();
 6092
 6093            edits.push((start_point..end_point, lines.join("\n")));
 6094
 6095            // Selections must change based on added and removed line count
 6096            let start_row =
 6097                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6098            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6099            new_selections.push(Selection {
 6100                id: selection.id,
 6101                start: start_row,
 6102                end: end_row,
 6103                goal: SelectionGoal::None,
 6104                reversed: selection.reversed,
 6105            });
 6106
 6107            if lines_after > lines_before {
 6108                added_lines += lines_after - lines_before;
 6109            } else if lines_before > lines_after {
 6110                removed_lines += lines_before - lines_after;
 6111            }
 6112        }
 6113
 6114        self.transact(cx, |this, cx| {
 6115            let buffer = this.buffer.update(cx, |buffer, cx| {
 6116                buffer.edit(edits, None, cx);
 6117                buffer.snapshot(cx)
 6118            });
 6119
 6120            // Recalculate offsets on newly edited buffer
 6121            let new_selections = new_selections
 6122                .iter()
 6123                .map(|s| {
 6124                    let start_point = Point::new(s.start.0, 0);
 6125                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6126                    Selection {
 6127                        id: s.id,
 6128                        start: buffer.point_to_offset(start_point),
 6129                        end: buffer.point_to_offset(end_point),
 6130                        goal: s.goal,
 6131                        reversed: s.reversed,
 6132                    }
 6133                })
 6134                .collect();
 6135
 6136            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6137                s.select(new_selections);
 6138            });
 6139
 6140            this.request_autoscroll(Autoscroll::fit(), cx);
 6141        });
 6142    }
 6143
 6144    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6145        self.manipulate_text(cx, |text| text.to_uppercase())
 6146    }
 6147
 6148    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6149        self.manipulate_text(cx, |text| text.to_lowercase())
 6150    }
 6151
 6152    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6153        self.manipulate_text(cx, |text| {
 6154            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6155            // https://github.com/rutrum/convert-case/issues/16
 6156            text.split('\n')
 6157                .map(|line| line.to_case(Case::Title))
 6158                .join("\n")
 6159        })
 6160    }
 6161
 6162    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6163        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6164    }
 6165
 6166    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6167        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6168    }
 6169
 6170    pub fn convert_to_upper_camel_case(
 6171        &mut self,
 6172        _: &ConvertToUpperCamelCase,
 6173        cx: &mut ViewContext<Self>,
 6174    ) {
 6175        self.manipulate_text(cx, |text| {
 6176            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6177            // https://github.com/rutrum/convert-case/issues/16
 6178            text.split('\n')
 6179                .map(|line| line.to_case(Case::UpperCamel))
 6180                .join("\n")
 6181        })
 6182    }
 6183
 6184    pub fn convert_to_lower_camel_case(
 6185        &mut self,
 6186        _: &ConvertToLowerCamelCase,
 6187        cx: &mut ViewContext<Self>,
 6188    ) {
 6189        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6190    }
 6191
 6192    pub fn convert_to_opposite_case(
 6193        &mut self,
 6194        _: &ConvertToOppositeCase,
 6195        cx: &mut ViewContext<Self>,
 6196    ) {
 6197        self.manipulate_text(cx, |text| {
 6198            text.chars()
 6199                .fold(String::with_capacity(text.len()), |mut t, c| {
 6200                    if c.is_uppercase() {
 6201                        t.extend(c.to_lowercase());
 6202                    } else {
 6203                        t.extend(c.to_uppercase());
 6204                    }
 6205                    t
 6206                })
 6207        })
 6208    }
 6209
 6210    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6211    where
 6212        Fn: FnMut(&str) -> String,
 6213    {
 6214        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6215        let buffer = self.buffer.read(cx).snapshot(cx);
 6216
 6217        let mut new_selections = Vec::new();
 6218        let mut edits = Vec::new();
 6219        let mut selection_adjustment = 0i32;
 6220
 6221        for selection in self.selections.all::<usize>(cx) {
 6222            let selection_is_empty = selection.is_empty();
 6223
 6224            let (start, end) = if selection_is_empty {
 6225                let word_range = movement::surrounding_word(
 6226                    &display_map,
 6227                    selection.start.to_display_point(&display_map),
 6228                );
 6229                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6230                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6231                (start, end)
 6232            } else {
 6233                (selection.start, selection.end)
 6234            };
 6235
 6236            let text = buffer.text_for_range(start..end).collect::<String>();
 6237            let old_length = text.len() as i32;
 6238            let text = callback(&text);
 6239
 6240            new_selections.push(Selection {
 6241                start: (start as i32 - selection_adjustment) as usize,
 6242                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6243                goal: SelectionGoal::None,
 6244                ..selection
 6245            });
 6246
 6247            selection_adjustment += old_length - text.len() as i32;
 6248
 6249            edits.push((start..end, text));
 6250        }
 6251
 6252        self.transact(cx, |this, cx| {
 6253            this.buffer.update(cx, |buffer, cx| {
 6254                buffer.edit(edits, None, cx);
 6255            });
 6256
 6257            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6258                s.select(new_selections);
 6259            });
 6260
 6261            this.request_autoscroll(Autoscroll::fit(), cx);
 6262        });
 6263    }
 6264
 6265    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6266        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6267        let buffer = &display_map.buffer_snapshot;
 6268        let selections = self.selections.all::<Point>(cx);
 6269
 6270        let mut edits = Vec::new();
 6271        let mut selections_iter = selections.iter().peekable();
 6272        while let Some(selection) = selections_iter.next() {
 6273            let mut rows = selection.spanned_rows(false, &display_map);
 6274            // duplicate line-wise
 6275            if whole_lines || selection.start == selection.end {
 6276                // Avoid duplicating the same lines twice.
 6277                while let Some(next_selection) = selections_iter.peek() {
 6278                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6279                    if next_rows.start < rows.end {
 6280                        rows.end = next_rows.end;
 6281                        selections_iter.next().unwrap();
 6282                    } else {
 6283                        break;
 6284                    }
 6285                }
 6286
 6287                // Copy the text from the selected row region and splice it either at the start
 6288                // or end of the region.
 6289                let start = Point::new(rows.start.0, 0);
 6290                let end = Point::new(
 6291                    rows.end.previous_row().0,
 6292                    buffer.line_len(rows.end.previous_row()),
 6293                );
 6294                let text = buffer
 6295                    .text_for_range(start..end)
 6296                    .chain(Some("\n"))
 6297                    .collect::<String>();
 6298                let insert_location = if upwards {
 6299                    Point::new(rows.end.0, 0)
 6300                } else {
 6301                    start
 6302                };
 6303                edits.push((insert_location..insert_location, text));
 6304            } else {
 6305                // duplicate character-wise
 6306                let start = selection.start;
 6307                let end = selection.end;
 6308                let text = buffer.text_for_range(start..end).collect::<String>();
 6309                edits.push((selection.end..selection.end, text));
 6310            }
 6311        }
 6312
 6313        self.transact(cx, |this, cx| {
 6314            this.buffer.update(cx, |buffer, cx| {
 6315                buffer.edit(edits, None, cx);
 6316            });
 6317
 6318            this.request_autoscroll(Autoscroll::fit(), cx);
 6319        });
 6320    }
 6321
 6322    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6323        self.duplicate(true, true, cx);
 6324    }
 6325
 6326    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6327        self.duplicate(false, true, cx);
 6328    }
 6329
 6330    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6331        self.duplicate(false, false, cx);
 6332    }
 6333
 6334    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6335        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6336        let buffer = self.buffer.read(cx).snapshot(cx);
 6337
 6338        let mut edits = Vec::new();
 6339        let mut unfold_ranges = Vec::new();
 6340        let mut refold_creases = Vec::new();
 6341
 6342        let selections = self.selections.all::<Point>(cx);
 6343        let mut selections = selections.iter().peekable();
 6344        let mut contiguous_row_selections = Vec::new();
 6345        let mut new_selections = Vec::new();
 6346
 6347        while let Some(selection) = selections.next() {
 6348            // Find all the selections that span a contiguous row range
 6349            let (start_row, end_row) = consume_contiguous_rows(
 6350                &mut contiguous_row_selections,
 6351                selection,
 6352                &display_map,
 6353                &mut selections,
 6354            );
 6355
 6356            // Move the text spanned by the row range to be before the line preceding the row range
 6357            if start_row.0 > 0 {
 6358                let range_to_move = Point::new(
 6359                    start_row.previous_row().0,
 6360                    buffer.line_len(start_row.previous_row()),
 6361                )
 6362                    ..Point::new(
 6363                        end_row.previous_row().0,
 6364                        buffer.line_len(end_row.previous_row()),
 6365                    );
 6366                let insertion_point = display_map
 6367                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6368                    .0;
 6369
 6370                // Don't move lines across excerpts
 6371                if buffer
 6372                    .excerpt_boundaries_in_range((
 6373                        Bound::Excluded(insertion_point),
 6374                        Bound::Included(range_to_move.end),
 6375                    ))
 6376                    .next()
 6377                    .is_none()
 6378                {
 6379                    let text = buffer
 6380                        .text_for_range(range_to_move.clone())
 6381                        .flat_map(|s| s.chars())
 6382                        .skip(1)
 6383                        .chain(['\n'])
 6384                        .collect::<String>();
 6385
 6386                    edits.push((
 6387                        buffer.anchor_after(range_to_move.start)
 6388                            ..buffer.anchor_before(range_to_move.end),
 6389                        String::new(),
 6390                    ));
 6391                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6392                    edits.push((insertion_anchor..insertion_anchor, text));
 6393
 6394                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6395
 6396                    // Move selections up
 6397                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6398                        |mut selection| {
 6399                            selection.start.row -= row_delta;
 6400                            selection.end.row -= row_delta;
 6401                            selection
 6402                        },
 6403                    ));
 6404
 6405                    // Move folds up
 6406                    unfold_ranges.push(range_to_move.clone());
 6407                    for fold in display_map.folds_in_range(
 6408                        buffer.anchor_before(range_to_move.start)
 6409                            ..buffer.anchor_after(range_to_move.end),
 6410                    ) {
 6411                        let mut start = fold.range.start.to_point(&buffer);
 6412                        let mut end = fold.range.end.to_point(&buffer);
 6413                        start.row -= row_delta;
 6414                        end.row -= row_delta;
 6415                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6416                    }
 6417                }
 6418            }
 6419
 6420            // If we didn't move line(s), preserve the existing selections
 6421            new_selections.append(&mut contiguous_row_selections);
 6422        }
 6423
 6424        self.transact(cx, |this, cx| {
 6425            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6426            this.buffer.update(cx, |buffer, cx| {
 6427                for (range, text) in edits {
 6428                    buffer.edit([(range, text)], None, cx);
 6429                }
 6430            });
 6431            this.fold_creases(refold_creases, true, cx);
 6432            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6433                s.select(new_selections);
 6434            })
 6435        });
 6436    }
 6437
 6438    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6439        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6440        let buffer = self.buffer.read(cx).snapshot(cx);
 6441
 6442        let mut edits = Vec::new();
 6443        let mut unfold_ranges = Vec::new();
 6444        let mut refold_creases = Vec::new();
 6445
 6446        let selections = self.selections.all::<Point>(cx);
 6447        let mut selections = selections.iter().peekable();
 6448        let mut contiguous_row_selections = Vec::new();
 6449        let mut new_selections = Vec::new();
 6450
 6451        while let Some(selection) = selections.next() {
 6452            // Find all the selections that span a contiguous row range
 6453            let (start_row, end_row) = consume_contiguous_rows(
 6454                &mut contiguous_row_selections,
 6455                selection,
 6456                &display_map,
 6457                &mut selections,
 6458            );
 6459
 6460            // Move the text spanned by the row range to be after the last line of the row range
 6461            if end_row.0 <= buffer.max_point().row {
 6462                let range_to_move =
 6463                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6464                let insertion_point = display_map
 6465                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6466                    .0;
 6467
 6468                // Don't move lines across excerpt boundaries
 6469                if buffer
 6470                    .excerpt_boundaries_in_range((
 6471                        Bound::Excluded(range_to_move.start),
 6472                        Bound::Included(insertion_point),
 6473                    ))
 6474                    .next()
 6475                    .is_none()
 6476                {
 6477                    let mut text = String::from("\n");
 6478                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6479                    text.pop(); // Drop trailing newline
 6480                    edits.push((
 6481                        buffer.anchor_after(range_to_move.start)
 6482                            ..buffer.anchor_before(range_to_move.end),
 6483                        String::new(),
 6484                    ));
 6485                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6486                    edits.push((insertion_anchor..insertion_anchor, text));
 6487
 6488                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6489
 6490                    // Move selections down
 6491                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6492                        |mut selection| {
 6493                            selection.start.row += row_delta;
 6494                            selection.end.row += row_delta;
 6495                            selection
 6496                        },
 6497                    ));
 6498
 6499                    // Move folds down
 6500                    unfold_ranges.push(range_to_move.clone());
 6501                    for fold in display_map.folds_in_range(
 6502                        buffer.anchor_before(range_to_move.start)
 6503                            ..buffer.anchor_after(range_to_move.end),
 6504                    ) {
 6505                        let mut start = fold.range.start.to_point(&buffer);
 6506                        let mut end = fold.range.end.to_point(&buffer);
 6507                        start.row += row_delta;
 6508                        end.row += row_delta;
 6509                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6510                    }
 6511                }
 6512            }
 6513
 6514            // If we didn't move line(s), preserve the existing selections
 6515            new_selections.append(&mut contiguous_row_selections);
 6516        }
 6517
 6518        self.transact(cx, |this, cx| {
 6519            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6520            this.buffer.update(cx, |buffer, cx| {
 6521                for (range, text) in edits {
 6522                    buffer.edit([(range, text)], None, cx);
 6523                }
 6524            });
 6525            this.fold_creases(refold_creases, true, cx);
 6526            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6527        });
 6528    }
 6529
 6530    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6531        let text_layout_details = &self.text_layout_details(cx);
 6532        self.transact(cx, |this, cx| {
 6533            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6534                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6535                let line_mode = s.line_mode;
 6536                s.move_with(|display_map, selection| {
 6537                    if !selection.is_empty() || line_mode {
 6538                        return;
 6539                    }
 6540
 6541                    let mut head = selection.head();
 6542                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6543                    if head.column() == display_map.line_len(head.row()) {
 6544                        transpose_offset = display_map
 6545                            .buffer_snapshot
 6546                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6547                    }
 6548
 6549                    if transpose_offset == 0 {
 6550                        return;
 6551                    }
 6552
 6553                    *head.column_mut() += 1;
 6554                    head = display_map.clip_point(head, Bias::Right);
 6555                    let goal = SelectionGoal::HorizontalPosition(
 6556                        display_map
 6557                            .x_for_display_point(head, text_layout_details)
 6558                            .into(),
 6559                    );
 6560                    selection.collapse_to(head, goal);
 6561
 6562                    let transpose_start = display_map
 6563                        .buffer_snapshot
 6564                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6565                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6566                        let transpose_end = display_map
 6567                            .buffer_snapshot
 6568                            .clip_offset(transpose_offset + 1, Bias::Right);
 6569                        if let Some(ch) =
 6570                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6571                        {
 6572                            edits.push((transpose_start..transpose_offset, String::new()));
 6573                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6574                        }
 6575                    }
 6576                });
 6577                edits
 6578            });
 6579            this.buffer
 6580                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6581            let selections = this.selections.all::<usize>(cx);
 6582            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6583                s.select(selections);
 6584            });
 6585        });
 6586    }
 6587
 6588    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6589        self.rewrap_impl(IsVimMode::No, cx)
 6590    }
 6591
 6592    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6593        let buffer = self.buffer.read(cx).snapshot(cx);
 6594        let selections = self.selections.all::<Point>(cx);
 6595        let mut selections = selections.iter().peekable();
 6596
 6597        let mut edits = Vec::new();
 6598        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6599
 6600        while let Some(selection) = selections.next() {
 6601            let mut start_row = selection.start.row;
 6602            let mut end_row = selection.end.row;
 6603
 6604            // Skip selections that overlap with a range that has already been rewrapped.
 6605            let selection_range = start_row..end_row;
 6606            if rewrapped_row_ranges
 6607                .iter()
 6608                .any(|range| range.overlaps(&selection_range))
 6609            {
 6610                continue;
 6611            }
 6612
 6613            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6614
 6615            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6616                match language_scope.language_name().0.as_ref() {
 6617                    "Markdown" | "Plain Text" => {
 6618                        should_rewrap = true;
 6619                    }
 6620                    _ => {}
 6621                }
 6622            }
 6623
 6624            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6625
 6626            // Since not all lines in the selection may be at the same indent
 6627            // level, choose the indent size that is the most common between all
 6628            // of the lines.
 6629            //
 6630            // If there is a tie, we use the deepest indent.
 6631            let (indent_size, indent_end) = {
 6632                let mut indent_size_occurrences = HashMap::default();
 6633                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6634
 6635                for row in start_row..=end_row {
 6636                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6637                    rows_by_indent_size.entry(indent).or_default().push(row);
 6638                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6639                }
 6640
 6641                let indent_size = indent_size_occurrences
 6642                    .into_iter()
 6643                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6644                    .map(|(indent, _)| indent)
 6645                    .unwrap_or_default();
 6646                let row = rows_by_indent_size[&indent_size][0];
 6647                let indent_end = Point::new(row, indent_size.len);
 6648
 6649                (indent_size, indent_end)
 6650            };
 6651
 6652            let mut line_prefix = indent_size.chars().collect::<String>();
 6653
 6654            if let Some(comment_prefix) =
 6655                buffer
 6656                    .language_scope_at(selection.head())
 6657                    .and_then(|language| {
 6658                        language
 6659                            .line_comment_prefixes()
 6660                            .iter()
 6661                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6662                            .cloned()
 6663                    })
 6664            {
 6665                line_prefix.push_str(&comment_prefix);
 6666                should_rewrap = true;
 6667            }
 6668
 6669            if !should_rewrap {
 6670                continue;
 6671            }
 6672
 6673            if selection.is_empty() {
 6674                'expand_upwards: while start_row > 0 {
 6675                    let prev_row = start_row - 1;
 6676                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6677                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6678                    {
 6679                        start_row = prev_row;
 6680                    } else {
 6681                        break 'expand_upwards;
 6682                    }
 6683                }
 6684
 6685                'expand_downwards: while end_row < buffer.max_point().row {
 6686                    let next_row = end_row + 1;
 6687                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6688                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6689                    {
 6690                        end_row = next_row;
 6691                    } else {
 6692                        break 'expand_downwards;
 6693                    }
 6694                }
 6695            }
 6696
 6697            let start = Point::new(start_row, 0);
 6698            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6699            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6700            let Some(lines_without_prefixes) = selection_text
 6701                .lines()
 6702                .map(|line| {
 6703                    line.strip_prefix(&line_prefix)
 6704                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6705                        .ok_or_else(|| {
 6706                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6707                        })
 6708                })
 6709                .collect::<Result<Vec<_>, _>>()
 6710                .log_err()
 6711            else {
 6712                continue;
 6713            };
 6714
 6715            let wrap_column = buffer
 6716                .settings_at(Point::new(start_row, 0), cx)
 6717                .preferred_line_length as usize;
 6718            let wrapped_text = wrap_with_prefix(
 6719                line_prefix,
 6720                lines_without_prefixes.join(" "),
 6721                wrap_column,
 6722                tab_size,
 6723            );
 6724
 6725            // TODO: should always use char-based diff while still supporting cursor behavior that
 6726            // matches vim.
 6727            let diff = match is_vim_mode {
 6728                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6729                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6730            };
 6731            let mut offset = start.to_offset(&buffer);
 6732            let mut moved_since_edit = true;
 6733
 6734            for change in diff.iter_all_changes() {
 6735                let value = change.value();
 6736                match change.tag() {
 6737                    ChangeTag::Equal => {
 6738                        offset += value.len();
 6739                        moved_since_edit = true;
 6740                    }
 6741                    ChangeTag::Delete => {
 6742                        let start = buffer.anchor_after(offset);
 6743                        let end = buffer.anchor_before(offset + value.len());
 6744
 6745                        if moved_since_edit {
 6746                            edits.push((start..end, String::new()));
 6747                        } else {
 6748                            edits.last_mut().unwrap().0.end = end;
 6749                        }
 6750
 6751                        offset += value.len();
 6752                        moved_since_edit = false;
 6753                    }
 6754                    ChangeTag::Insert => {
 6755                        if moved_since_edit {
 6756                            let anchor = buffer.anchor_after(offset);
 6757                            edits.push((anchor..anchor, value.to_string()));
 6758                        } else {
 6759                            edits.last_mut().unwrap().1.push_str(value);
 6760                        }
 6761
 6762                        moved_since_edit = false;
 6763                    }
 6764                }
 6765            }
 6766
 6767            rewrapped_row_ranges.push(start_row..=end_row);
 6768        }
 6769
 6770        self.buffer
 6771            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6772    }
 6773
 6774    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6775        let mut text = String::new();
 6776        let buffer = self.buffer.read(cx).snapshot(cx);
 6777        let mut selections = self.selections.all::<Point>(cx);
 6778        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6779        {
 6780            let max_point = buffer.max_point();
 6781            let mut is_first = true;
 6782            for selection in &mut selections {
 6783                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6784                if is_entire_line {
 6785                    selection.start = Point::new(selection.start.row, 0);
 6786                    if !selection.is_empty() && selection.end.column == 0 {
 6787                        selection.end = cmp::min(max_point, selection.end);
 6788                    } else {
 6789                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6790                    }
 6791                    selection.goal = SelectionGoal::None;
 6792                }
 6793                if is_first {
 6794                    is_first = false;
 6795                } else {
 6796                    text += "\n";
 6797                }
 6798                let mut len = 0;
 6799                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6800                    text.push_str(chunk);
 6801                    len += chunk.len();
 6802                }
 6803                clipboard_selections.push(ClipboardSelection {
 6804                    len,
 6805                    is_entire_line,
 6806                    first_line_indent: buffer
 6807                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6808                        .len,
 6809                });
 6810            }
 6811        }
 6812
 6813        self.transact(cx, |this, cx| {
 6814            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6815                s.select(selections);
 6816            });
 6817            this.insert("", cx);
 6818        });
 6819        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6820    }
 6821
 6822    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6823        let item = self.cut_common(cx);
 6824        cx.write_to_clipboard(item);
 6825    }
 6826
 6827    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6828        self.change_selections(None, cx, |s| {
 6829            s.move_with(|snapshot, sel| {
 6830                if sel.is_empty() {
 6831                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6832                }
 6833            });
 6834        });
 6835        let item = self.cut_common(cx);
 6836        cx.set_global(KillRing(item))
 6837    }
 6838
 6839    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6840        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6841            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6842                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6843            } else {
 6844                return;
 6845            }
 6846        } else {
 6847            return;
 6848        };
 6849        self.do_paste(&text, metadata, false, cx);
 6850    }
 6851
 6852    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6853        let selections = self.selections.all::<Point>(cx);
 6854        let buffer = self.buffer.read(cx).read(cx);
 6855        let mut text = String::new();
 6856
 6857        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6858        {
 6859            let max_point = buffer.max_point();
 6860            let mut is_first = true;
 6861            for selection in selections.iter() {
 6862                let mut start = selection.start;
 6863                let mut end = selection.end;
 6864                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6865                if is_entire_line {
 6866                    start = Point::new(start.row, 0);
 6867                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6868                }
 6869                if is_first {
 6870                    is_first = false;
 6871                } else {
 6872                    text += "\n";
 6873                }
 6874                let mut len = 0;
 6875                for chunk in buffer.text_for_range(start..end) {
 6876                    text.push_str(chunk);
 6877                    len += chunk.len();
 6878                }
 6879                clipboard_selections.push(ClipboardSelection {
 6880                    len,
 6881                    is_entire_line,
 6882                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6883                });
 6884            }
 6885        }
 6886
 6887        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6888            text,
 6889            clipboard_selections,
 6890        ));
 6891    }
 6892
 6893    pub fn do_paste(
 6894        &mut self,
 6895        text: &String,
 6896        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6897        handle_entire_lines: bool,
 6898        cx: &mut ViewContext<Self>,
 6899    ) {
 6900        if self.read_only(cx) {
 6901            return;
 6902        }
 6903
 6904        let clipboard_text = Cow::Borrowed(text);
 6905
 6906        self.transact(cx, |this, cx| {
 6907            if let Some(mut clipboard_selections) = clipboard_selections {
 6908                let old_selections = this.selections.all::<usize>(cx);
 6909                let all_selections_were_entire_line =
 6910                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6911                let first_selection_indent_column =
 6912                    clipboard_selections.first().map(|s| s.first_line_indent);
 6913                if clipboard_selections.len() != old_selections.len() {
 6914                    clipboard_selections.drain(..);
 6915                }
 6916                let cursor_offset = this.selections.last::<usize>(cx).head();
 6917                let mut auto_indent_on_paste = true;
 6918
 6919                this.buffer.update(cx, |buffer, cx| {
 6920                    let snapshot = buffer.read(cx);
 6921                    auto_indent_on_paste =
 6922                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6923
 6924                    let mut start_offset = 0;
 6925                    let mut edits = Vec::new();
 6926                    let mut original_indent_columns = Vec::new();
 6927                    for (ix, selection) in old_selections.iter().enumerate() {
 6928                        let to_insert;
 6929                        let entire_line;
 6930                        let original_indent_column;
 6931                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6932                            let end_offset = start_offset + clipboard_selection.len;
 6933                            to_insert = &clipboard_text[start_offset..end_offset];
 6934                            entire_line = clipboard_selection.is_entire_line;
 6935                            start_offset = end_offset + 1;
 6936                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6937                        } else {
 6938                            to_insert = clipboard_text.as_str();
 6939                            entire_line = all_selections_were_entire_line;
 6940                            original_indent_column = first_selection_indent_column
 6941                        }
 6942
 6943                        // If the corresponding selection was empty when this slice of the
 6944                        // clipboard text was written, then the entire line containing the
 6945                        // selection was copied. If this selection is also currently empty,
 6946                        // then paste the line before the current line of the buffer.
 6947                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6948                            let column = selection.start.to_point(&snapshot).column as usize;
 6949                            let line_start = selection.start - column;
 6950                            line_start..line_start
 6951                        } else {
 6952                            selection.range()
 6953                        };
 6954
 6955                        edits.push((range, to_insert));
 6956                        original_indent_columns.extend(original_indent_column);
 6957                    }
 6958                    drop(snapshot);
 6959
 6960                    buffer.edit(
 6961                        edits,
 6962                        if auto_indent_on_paste {
 6963                            Some(AutoindentMode::Block {
 6964                                original_indent_columns,
 6965                            })
 6966                        } else {
 6967                            None
 6968                        },
 6969                        cx,
 6970                    );
 6971                });
 6972
 6973                let selections = this.selections.all::<usize>(cx);
 6974                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6975            } else {
 6976                this.insert(&clipboard_text, cx);
 6977            }
 6978        });
 6979    }
 6980
 6981    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6982        if let Some(item) = cx.read_from_clipboard() {
 6983            let entries = item.entries();
 6984
 6985            match entries.first() {
 6986                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 6987                // of all the pasted entries.
 6988                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 6989                    .do_paste(
 6990                        clipboard_string.text(),
 6991                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 6992                        true,
 6993                        cx,
 6994                    ),
 6995                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 6996            }
 6997        }
 6998    }
 6999
 7000    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7001        if self.read_only(cx) {
 7002            return;
 7003        }
 7004
 7005        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7006            if let Some((selections, _)) =
 7007                self.selection_history.transaction(transaction_id).cloned()
 7008            {
 7009                self.change_selections(None, cx, |s| {
 7010                    s.select_anchors(selections.to_vec());
 7011                });
 7012            }
 7013            self.request_autoscroll(Autoscroll::fit(), cx);
 7014            self.unmark_text(cx);
 7015            self.refresh_inline_completion(true, false, cx);
 7016            cx.emit(EditorEvent::Edited { transaction_id });
 7017            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7018        }
 7019    }
 7020
 7021    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7022        if self.read_only(cx) {
 7023            return;
 7024        }
 7025
 7026        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7027            if let Some((_, Some(selections))) =
 7028                self.selection_history.transaction(transaction_id).cloned()
 7029            {
 7030                self.change_selections(None, cx, |s| {
 7031                    s.select_anchors(selections.to_vec());
 7032                });
 7033            }
 7034            self.request_autoscroll(Autoscroll::fit(), cx);
 7035            self.unmark_text(cx);
 7036            self.refresh_inline_completion(true, false, cx);
 7037            cx.emit(EditorEvent::Edited { transaction_id });
 7038        }
 7039    }
 7040
 7041    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7042        self.buffer
 7043            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7044    }
 7045
 7046    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7047        self.buffer
 7048            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7049    }
 7050
 7051    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7052        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7053            let line_mode = s.line_mode;
 7054            s.move_with(|map, selection| {
 7055                let cursor = if selection.is_empty() && !line_mode {
 7056                    movement::left(map, selection.start)
 7057                } else {
 7058                    selection.start
 7059                };
 7060                selection.collapse_to(cursor, SelectionGoal::None);
 7061            });
 7062        })
 7063    }
 7064
 7065    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7066        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7067            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7068        })
 7069    }
 7070
 7071    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7072        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7073            let line_mode = s.line_mode;
 7074            s.move_with(|map, selection| {
 7075                let cursor = if selection.is_empty() && !line_mode {
 7076                    movement::right(map, selection.end)
 7077                } else {
 7078                    selection.end
 7079                };
 7080                selection.collapse_to(cursor, SelectionGoal::None)
 7081            });
 7082        })
 7083    }
 7084
 7085    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7086        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7087            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7088        })
 7089    }
 7090
 7091    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7092        if self.take_rename(true, cx).is_some() {
 7093            return;
 7094        }
 7095
 7096        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7097            cx.propagate();
 7098            return;
 7099        }
 7100
 7101        let text_layout_details = &self.text_layout_details(cx);
 7102        let selection_count = self.selections.count();
 7103        let first_selection = self.selections.first_anchor();
 7104
 7105        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7106            let line_mode = s.line_mode;
 7107            s.move_with(|map, selection| {
 7108                if !selection.is_empty() && !line_mode {
 7109                    selection.goal = SelectionGoal::None;
 7110                }
 7111                let (cursor, goal) = movement::up(
 7112                    map,
 7113                    selection.start,
 7114                    selection.goal,
 7115                    false,
 7116                    text_layout_details,
 7117                );
 7118                selection.collapse_to(cursor, goal);
 7119            });
 7120        });
 7121
 7122        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7123        {
 7124            cx.propagate();
 7125        }
 7126    }
 7127
 7128    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7129        if self.take_rename(true, cx).is_some() {
 7130            return;
 7131        }
 7132
 7133        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7134            cx.propagate();
 7135            return;
 7136        }
 7137
 7138        let text_layout_details = &self.text_layout_details(cx);
 7139
 7140        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7141            let line_mode = s.line_mode;
 7142            s.move_with(|map, selection| {
 7143                if !selection.is_empty() && !line_mode {
 7144                    selection.goal = SelectionGoal::None;
 7145                }
 7146                let (cursor, goal) = movement::up_by_rows(
 7147                    map,
 7148                    selection.start,
 7149                    action.lines,
 7150                    selection.goal,
 7151                    false,
 7152                    text_layout_details,
 7153                );
 7154                selection.collapse_to(cursor, goal);
 7155            });
 7156        })
 7157    }
 7158
 7159    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7160        if self.take_rename(true, cx).is_some() {
 7161            return;
 7162        }
 7163
 7164        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7165            cx.propagate();
 7166            return;
 7167        }
 7168
 7169        let text_layout_details = &self.text_layout_details(cx);
 7170
 7171        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7172            let line_mode = s.line_mode;
 7173            s.move_with(|map, selection| {
 7174                if !selection.is_empty() && !line_mode {
 7175                    selection.goal = SelectionGoal::None;
 7176                }
 7177                let (cursor, goal) = movement::down_by_rows(
 7178                    map,
 7179                    selection.start,
 7180                    action.lines,
 7181                    selection.goal,
 7182                    false,
 7183                    text_layout_details,
 7184                );
 7185                selection.collapse_to(cursor, goal);
 7186            });
 7187        })
 7188    }
 7189
 7190    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7191        let text_layout_details = &self.text_layout_details(cx);
 7192        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7193            s.move_heads_with(|map, head, goal| {
 7194                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7195            })
 7196        })
 7197    }
 7198
 7199    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7200        let text_layout_details = &self.text_layout_details(cx);
 7201        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7202            s.move_heads_with(|map, head, goal| {
 7203                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7204            })
 7205        })
 7206    }
 7207
 7208    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7209        let Some(row_count) = self.visible_row_count() else {
 7210            return;
 7211        };
 7212
 7213        let text_layout_details = &self.text_layout_details(cx);
 7214
 7215        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7216            s.move_heads_with(|map, head, goal| {
 7217                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7218            })
 7219        })
 7220    }
 7221
 7222    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7223        if self.take_rename(true, cx).is_some() {
 7224            return;
 7225        }
 7226
 7227        if self
 7228            .context_menu
 7229            .borrow_mut()
 7230            .as_mut()
 7231            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7232            .unwrap_or(false)
 7233        {
 7234            return;
 7235        }
 7236
 7237        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7238            cx.propagate();
 7239            return;
 7240        }
 7241
 7242        let Some(row_count) = self.visible_row_count() else {
 7243            return;
 7244        };
 7245
 7246        let autoscroll = if action.center_cursor {
 7247            Autoscroll::center()
 7248        } else {
 7249            Autoscroll::fit()
 7250        };
 7251
 7252        let text_layout_details = &self.text_layout_details(cx);
 7253
 7254        self.change_selections(Some(autoscroll), cx, |s| {
 7255            let line_mode = s.line_mode;
 7256            s.move_with(|map, selection| {
 7257                if !selection.is_empty() && !line_mode {
 7258                    selection.goal = SelectionGoal::None;
 7259                }
 7260                let (cursor, goal) = movement::up_by_rows(
 7261                    map,
 7262                    selection.end,
 7263                    row_count,
 7264                    selection.goal,
 7265                    false,
 7266                    text_layout_details,
 7267                );
 7268                selection.collapse_to(cursor, goal);
 7269            });
 7270        });
 7271    }
 7272
 7273    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7274        let text_layout_details = &self.text_layout_details(cx);
 7275        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7276            s.move_heads_with(|map, head, goal| {
 7277                movement::up(map, head, goal, false, text_layout_details)
 7278            })
 7279        })
 7280    }
 7281
 7282    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7283        self.take_rename(true, cx);
 7284
 7285        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7286            cx.propagate();
 7287            return;
 7288        }
 7289
 7290        let text_layout_details = &self.text_layout_details(cx);
 7291        let selection_count = self.selections.count();
 7292        let first_selection = self.selections.first_anchor();
 7293
 7294        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7295            let line_mode = s.line_mode;
 7296            s.move_with(|map, selection| {
 7297                if !selection.is_empty() && !line_mode {
 7298                    selection.goal = SelectionGoal::None;
 7299                }
 7300                let (cursor, goal) = movement::down(
 7301                    map,
 7302                    selection.end,
 7303                    selection.goal,
 7304                    false,
 7305                    text_layout_details,
 7306                );
 7307                selection.collapse_to(cursor, goal);
 7308            });
 7309        });
 7310
 7311        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7312        {
 7313            cx.propagate();
 7314        }
 7315    }
 7316
 7317    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7318        let Some(row_count) = self.visible_row_count() else {
 7319            return;
 7320        };
 7321
 7322        let text_layout_details = &self.text_layout_details(cx);
 7323
 7324        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7325            s.move_heads_with(|map, head, goal| {
 7326                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7327            })
 7328        })
 7329    }
 7330
 7331    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7332        if self.take_rename(true, cx).is_some() {
 7333            return;
 7334        }
 7335
 7336        if self
 7337            .context_menu
 7338            .borrow_mut()
 7339            .as_mut()
 7340            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7341            .unwrap_or(false)
 7342        {
 7343            return;
 7344        }
 7345
 7346        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7347            cx.propagate();
 7348            return;
 7349        }
 7350
 7351        let Some(row_count) = self.visible_row_count() else {
 7352            return;
 7353        };
 7354
 7355        let autoscroll = if action.center_cursor {
 7356            Autoscroll::center()
 7357        } else {
 7358            Autoscroll::fit()
 7359        };
 7360
 7361        let text_layout_details = &self.text_layout_details(cx);
 7362        self.change_selections(Some(autoscroll), cx, |s| {
 7363            let line_mode = s.line_mode;
 7364            s.move_with(|map, selection| {
 7365                if !selection.is_empty() && !line_mode {
 7366                    selection.goal = SelectionGoal::None;
 7367                }
 7368                let (cursor, goal) = movement::down_by_rows(
 7369                    map,
 7370                    selection.end,
 7371                    row_count,
 7372                    selection.goal,
 7373                    false,
 7374                    text_layout_details,
 7375                );
 7376                selection.collapse_to(cursor, goal);
 7377            });
 7378        });
 7379    }
 7380
 7381    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7382        let text_layout_details = &self.text_layout_details(cx);
 7383        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7384            s.move_heads_with(|map, head, goal| {
 7385                movement::down(map, head, goal, false, text_layout_details)
 7386            })
 7387        });
 7388    }
 7389
 7390    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7391        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7392            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7393        }
 7394    }
 7395
 7396    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7397        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7398            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7399        }
 7400    }
 7401
 7402    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7403        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7404            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7405        }
 7406    }
 7407
 7408    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7409        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7410            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7411        }
 7412    }
 7413
 7414    pub fn move_to_previous_word_start(
 7415        &mut self,
 7416        _: &MoveToPreviousWordStart,
 7417        cx: &mut ViewContext<Self>,
 7418    ) {
 7419        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7420            s.move_cursors_with(|map, head, _| {
 7421                (
 7422                    movement::previous_word_start(map, head),
 7423                    SelectionGoal::None,
 7424                )
 7425            });
 7426        })
 7427    }
 7428
 7429    pub fn move_to_previous_subword_start(
 7430        &mut self,
 7431        _: &MoveToPreviousSubwordStart,
 7432        cx: &mut ViewContext<Self>,
 7433    ) {
 7434        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7435            s.move_cursors_with(|map, head, _| {
 7436                (
 7437                    movement::previous_subword_start(map, head),
 7438                    SelectionGoal::None,
 7439                )
 7440            });
 7441        })
 7442    }
 7443
 7444    pub fn select_to_previous_word_start(
 7445        &mut self,
 7446        _: &SelectToPreviousWordStart,
 7447        cx: &mut ViewContext<Self>,
 7448    ) {
 7449        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7450            s.move_heads_with(|map, head, _| {
 7451                (
 7452                    movement::previous_word_start(map, head),
 7453                    SelectionGoal::None,
 7454                )
 7455            });
 7456        })
 7457    }
 7458
 7459    pub fn select_to_previous_subword_start(
 7460        &mut self,
 7461        _: &SelectToPreviousSubwordStart,
 7462        cx: &mut ViewContext<Self>,
 7463    ) {
 7464        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7465            s.move_heads_with(|map, head, _| {
 7466                (
 7467                    movement::previous_subword_start(map, head),
 7468                    SelectionGoal::None,
 7469                )
 7470            });
 7471        })
 7472    }
 7473
 7474    pub fn delete_to_previous_word_start(
 7475        &mut self,
 7476        action: &DeleteToPreviousWordStart,
 7477        cx: &mut ViewContext<Self>,
 7478    ) {
 7479        self.transact(cx, |this, cx| {
 7480            this.select_autoclose_pair(cx);
 7481            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7482                let line_mode = s.line_mode;
 7483                s.move_with(|map, selection| {
 7484                    if selection.is_empty() && !line_mode {
 7485                        let cursor = if action.ignore_newlines {
 7486                            movement::previous_word_start(map, selection.head())
 7487                        } else {
 7488                            movement::previous_word_start_or_newline(map, selection.head())
 7489                        };
 7490                        selection.set_head(cursor, SelectionGoal::None);
 7491                    }
 7492                });
 7493            });
 7494            this.insert("", cx);
 7495        });
 7496    }
 7497
 7498    pub fn delete_to_previous_subword_start(
 7499        &mut self,
 7500        _: &DeleteToPreviousSubwordStart,
 7501        cx: &mut ViewContext<Self>,
 7502    ) {
 7503        self.transact(cx, |this, cx| {
 7504            this.select_autoclose_pair(cx);
 7505            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7506                let line_mode = s.line_mode;
 7507                s.move_with(|map, selection| {
 7508                    if selection.is_empty() && !line_mode {
 7509                        let cursor = movement::previous_subword_start(map, selection.head());
 7510                        selection.set_head(cursor, SelectionGoal::None);
 7511                    }
 7512                });
 7513            });
 7514            this.insert("", cx);
 7515        });
 7516    }
 7517
 7518    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7519        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7520            s.move_cursors_with(|map, head, _| {
 7521                (movement::next_word_end(map, head), SelectionGoal::None)
 7522            });
 7523        })
 7524    }
 7525
 7526    pub fn move_to_next_subword_end(
 7527        &mut self,
 7528        _: &MoveToNextSubwordEnd,
 7529        cx: &mut ViewContext<Self>,
 7530    ) {
 7531        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7532            s.move_cursors_with(|map, head, _| {
 7533                (movement::next_subword_end(map, head), SelectionGoal::None)
 7534            });
 7535        })
 7536    }
 7537
 7538    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7539        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7540            s.move_heads_with(|map, head, _| {
 7541                (movement::next_word_end(map, head), SelectionGoal::None)
 7542            });
 7543        })
 7544    }
 7545
 7546    pub fn select_to_next_subword_end(
 7547        &mut self,
 7548        _: &SelectToNextSubwordEnd,
 7549        cx: &mut ViewContext<Self>,
 7550    ) {
 7551        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7552            s.move_heads_with(|map, head, _| {
 7553                (movement::next_subword_end(map, head), SelectionGoal::None)
 7554            });
 7555        })
 7556    }
 7557
 7558    pub fn delete_to_next_word_end(
 7559        &mut self,
 7560        action: &DeleteToNextWordEnd,
 7561        cx: &mut ViewContext<Self>,
 7562    ) {
 7563        self.transact(cx, |this, cx| {
 7564            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7565                let line_mode = s.line_mode;
 7566                s.move_with(|map, selection| {
 7567                    if selection.is_empty() && !line_mode {
 7568                        let cursor = if action.ignore_newlines {
 7569                            movement::next_word_end(map, selection.head())
 7570                        } else {
 7571                            movement::next_word_end_or_newline(map, selection.head())
 7572                        };
 7573                        selection.set_head(cursor, SelectionGoal::None);
 7574                    }
 7575                });
 7576            });
 7577            this.insert("", cx);
 7578        });
 7579    }
 7580
 7581    pub fn delete_to_next_subword_end(
 7582        &mut self,
 7583        _: &DeleteToNextSubwordEnd,
 7584        cx: &mut ViewContext<Self>,
 7585    ) {
 7586        self.transact(cx, |this, cx| {
 7587            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7588                s.move_with(|map, selection| {
 7589                    if selection.is_empty() {
 7590                        let cursor = movement::next_subword_end(map, selection.head());
 7591                        selection.set_head(cursor, SelectionGoal::None);
 7592                    }
 7593                });
 7594            });
 7595            this.insert("", cx);
 7596        });
 7597    }
 7598
 7599    pub fn move_to_beginning_of_line(
 7600        &mut self,
 7601        action: &MoveToBeginningOfLine,
 7602        cx: &mut ViewContext<Self>,
 7603    ) {
 7604        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7605            s.move_cursors_with(|map, head, _| {
 7606                (
 7607                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7608                    SelectionGoal::None,
 7609                )
 7610            });
 7611        })
 7612    }
 7613
 7614    pub fn select_to_beginning_of_line(
 7615        &mut self,
 7616        action: &SelectToBeginningOfLine,
 7617        cx: &mut ViewContext<Self>,
 7618    ) {
 7619        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7620            s.move_heads_with(|map, head, _| {
 7621                (
 7622                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7623                    SelectionGoal::None,
 7624                )
 7625            });
 7626        });
 7627    }
 7628
 7629    pub fn delete_to_beginning_of_line(
 7630        &mut self,
 7631        _: &DeleteToBeginningOfLine,
 7632        cx: &mut ViewContext<Self>,
 7633    ) {
 7634        self.transact(cx, |this, cx| {
 7635            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7636                s.move_with(|_, selection| {
 7637                    selection.reversed = true;
 7638                });
 7639            });
 7640
 7641            this.select_to_beginning_of_line(
 7642                &SelectToBeginningOfLine {
 7643                    stop_at_soft_wraps: false,
 7644                },
 7645                cx,
 7646            );
 7647            this.backspace(&Backspace, cx);
 7648        });
 7649    }
 7650
 7651    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7652        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7653            s.move_cursors_with(|map, head, _| {
 7654                (
 7655                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7656                    SelectionGoal::None,
 7657                )
 7658            });
 7659        })
 7660    }
 7661
 7662    pub fn select_to_end_of_line(
 7663        &mut self,
 7664        action: &SelectToEndOfLine,
 7665        cx: &mut ViewContext<Self>,
 7666    ) {
 7667        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7668            s.move_heads_with(|map, head, _| {
 7669                (
 7670                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7671                    SelectionGoal::None,
 7672                )
 7673            });
 7674        })
 7675    }
 7676
 7677    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7678        self.transact(cx, |this, cx| {
 7679            this.select_to_end_of_line(
 7680                &SelectToEndOfLine {
 7681                    stop_at_soft_wraps: false,
 7682                },
 7683                cx,
 7684            );
 7685            this.delete(&Delete, cx);
 7686        });
 7687    }
 7688
 7689    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7690        self.transact(cx, |this, cx| {
 7691            this.select_to_end_of_line(
 7692                &SelectToEndOfLine {
 7693                    stop_at_soft_wraps: false,
 7694                },
 7695                cx,
 7696            );
 7697            this.cut(&Cut, cx);
 7698        });
 7699    }
 7700
 7701    pub fn move_to_start_of_paragraph(
 7702        &mut self,
 7703        _: &MoveToStartOfParagraph,
 7704        cx: &mut ViewContext<Self>,
 7705    ) {
 7706        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7707            cx.propagate();
 7708            return;
 7709        }
 7710
 7711        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7712            s.move_with(|map, selection| {
 7713                selection.collapse_to(
 7714                    movement::start_of_paragraph(map, selection.head(), 1),
 7715                    SelectionGoal::None,
 7716                )
 7717            });
 7718        })
 7719    }
 7720
 7721    pub fn move_to_end_of_paragraph(
 7722        &mut self,
 7723        _: &MoveToEndOfParagraph,
 7724        cx: &mut ViewContext<Self>,
 7725    ) {
 7726        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7727            cx.propagate();
 7728            return;
 7729        }
 7730
 7731        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7732            s.move_with(|map, selection| {
 7733                selection.collapse_to(
 7734                    movement::end_of_paragraph(map, selection.head(), 1),
 7735                    SelectionGoal::None,
 7736                )
 7737            });
 7738        })
 7739    }
 7740
 7741    pub fn select_to_start_of_paragraph(
 7742        &mut self,
 7743        _: &SelectToStartOfParagraph,
 7744        cx: &mut ViewContext<Self>,
 7745    ) {
 7746        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7747            cx.propagate();
 7748            return;
 7749        }
 7750
 7751        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7752            s.move_heads_with(|map, head, _| {
 7753                (
 7754                    movement::start_of_paragraph(map, head, 1),
 7755                    SelectionGoal::None,
 7756                )
 7757            });
 7758        })
 7759    }
 7760
 7761    pub fn select_to_end_of_paragraph(
 7762        &mut self,
 7763        _: &SelectToEndOfParagraph,
 7764        cx: &mut ViewContext<Self>,
 7765    ) {
 7766        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7767            cx.propagate();
 7768            return;
 7769        }
 7770
 7771        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7772            s.move_heads_with(|map, head, _| {
 7773                (
 7774                    movement::end_of_paragraph(map, head, 1),
 7775                    SelectionGoal::None,
 7776                )
 7777            });
 7778        })
 7779    }
 7780
 7781    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7782        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7783            cx.propagate();
 7784            return;
 7785        }
 7786
 7787        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7788            s.select_ranges(vec![0..0]);
 7789        });
 7790    }
 7791
 7792    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7793        let mut selection = self.selections.last::<Point>(cx);
 7794        selection.set_head(Point::zero(), SelectionGoal::None);
 7795
 7796        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7797            s.select(vec![selection]);
 7798        });
 7799    }
 7800
 7801    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7802        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7803            cx.propagate();
 7804            return;
 7805        }
 7806
 7807        let cursor = self.buffer.read(cx).read(cx).len();
 7808        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7809            s.select_ranges(vec![cursor..cursor])
 7810        });
 7811    }
 7812
 7813    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7814        self.nav_history = nav_history;
 7815    }
 7816
 7817    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7818        self.nav_history.as_ref()
 7819    }
 7820
 7821    fn push_to_nav_history(
 7822        &mut self,
 7823        cursor_anchor: Anchor,
 7824        new_position: Option<Point>,
 7825        cx: &mut ViewContext<Self>,
 7826    ) {
 7827        if let Some(nav_history) = self.nav_history.as_mut() {
 7828            let buffer = self.buffer.read(cx).read(cx);
 7829            let cursor_position = cursor_anchor.to_point(&buffer);
 7830            let scroll_state = self.scroll_manager.anchor();
 7831            let scroll_top_row = scroll_state.top_row(&buffer);
 7832            drop(buffer);
 7833
 7834            if let Some(new_position) = new_position {
 7835                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7836                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7837                    return;
 7838                }
 7839            }
 7840
 7841            nav_history.push(
 7842                Some(NavigationData {
 7843                    cursor_anchor,
 7844                    cursor_position,
 7845                    scroll_anchor: scroll_state,
 7846                    scroll_top_row,
 7847                }),
 7848                cx,
 7849            );
 7850        }
 7851    }
 7852
 7853    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7854        let buffer = self.buffer.read(cx).snapshot(cx);
 7855        let mut selection = self.selections.first::<usize>(cx);
 7856        selection.set_head(buffer.len(), SelectionGoal::None);
 7857        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7858            s.select(vec![selection]);
 7859        });
 7860    }
 7861
 7862    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7863        let end = self.buffer.read(cx).read(cx).len();
 7864        self.change_selections(None, cx, |s| {
 7865            s.select_ranges(vec![0..end]);
 7866        });
 7867    }
 7868
 7869    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7870        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7871        let mut selections = self.selections.all::<Point>(cx);
 7872        let max_point = display_map.buffer_snapshot.max_point();
 7873        for selection in &mut selections {
 7874            let rows = selection.spanned_rows(true, &display_map);
 7875            selection.start = Point::new(rows.start.0, 0);
 7876            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7877            selection.reversed = false;
 7878        }
 7879        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7880            s.select(selections);
 7881        });
 7882    }
 7883
 7884    pub fn split_selection_into_lines(
 7885        &mut self,
 7886        _: &SplitSelectionIntoLines,
 7887        cx: &mut ViewContext<Self>,
 7888    ) {
 7889        let mut to_unfold = Vec::new();
 7890        let mut new_selection_ranges = Vec::new();
 7891        {
 7892            let selections = self.selections.all::<Point>(cx);
 7893            let buffer = self.buffer.read(cx).read(cx);
 7894            for selection in selections {
 7895                for row in selection.start.row..selection.end.row {
 7896                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7897                    new_selection_ranges.push(cursor..cursor);
 7898                }
 7899                new_selection_ranges.push(selection.end..selection.end);
 7900                to_unfold.push(selection.start..selection.end);
 7901            }
 7902        }
 7903        self.unfold_ranges(&to_unfold, true, true, cx);
 7904        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7905            s.select_ranges(new_selection_ranges);
 7906        });
 7907    }
 7908
 7909    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7910        self.add_selection(true, cx);
 7911    }
 7912
 7913    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7914        self.add_selection(false, cx);
 7915    }
 7916
 7917    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7918        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7919        let mut selections = self.selections.all::<Point>(cx);
 7920        let text_layout_details = self.text_layout_details(cx);
 7921        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7922            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7923            let range = oldest_selection.display_range(&display_map).sorted();
 7924
 7925            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7926            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7927            let positions = start_x.min(end_x)..start_x.max(end_x);
 7928
 7929            selections.clear();
 7930            let mut stack = Vec::new();
 7931            for row in range.start.row().0..=range.end.row().0 {
 7932                if let Some(selection) = self.selections.build_columnar_selection(
 7933                    &display_map,
 7934                    DisplayRow(row),
 7935                    &positions,
 7936                    oldest_selection.reversed,
 7937                    &text_layout_details,
 7938                ) {
 7939                    stack.push(selection.id);
 7940                    selections.push(selection);
 7941                }
 7942            }
 7943
 7944            if above {
 7945                stack.reverse();
 7946            }
 7947
 7948            AddSelectionsState { above, stack }
 7949        });
 7950
 7951        let last_added_selection = *state.stack.last().unwrap();
 7952        let mut new_selections = Vec::new();
 7953        if above == state.above {
 7954            let end_row = if above {
 7955                DisplayRow(0)
 7956            } else {
 7957                display_map.max_point().row()
 7958            };
 7959
 7960            'outer: for selection in selections {
 7961                if selection.id == last_added_selection {
 7962                    let range = selection.display_range(&display_map).sorted();
 7963                    debug_assert_eq!(range.start.row(), range.end.row());
 7964                    let mut row = range.start.row();
 7965                    let positions =
 7966                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7967                            px(start)..px(end)
 7968                        } else {
 7969                            let start_x =
 7970                                display_map.x_for_display_point(range.start, &text_layout_details);
 7971                            let end_x =
 7972                                display_map.x_for_display_point(range.end, &text_layout_details);
 7973                            start_x.min(end_x)..start_x.max(end_x)
 7974                        };
 7975
 7976                    while row != end_row {
 7977                        if above {
 7978                            row.0 -= 1;
 7979                        } else {
 7980                            row.0 += 1;
 7981                        }
 7982
 7983                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7984                            &display_map,
 7985                            row,
 7986                            &positions,
 7987                            selection.reversed,
 7988                            &text_layout_details,
 7989                        ) {
 7990                            state.stack.push(new_selection.id);
 7991                            if above {
 7992                                new_selections.push(new_selection);
 7993                                new_selections.push(selection);
 7994                            } else {
 7995                                new_selections.push(selection);
 7996                                new_selections.push(new_selection);
 7997                            }
 7998
 7999                            continue 'outer;
 8000                        }
 8001                    }
 8002                }
 8003
 8004                new_selections.push(selection);
 8005            }
 8006        } else {
 8007            new_selections = selections;
 8008            new_selections.retain(|s| s.id != last_added_selection);
 8009            state.stack.pop();
 8010        }
 8011
 8012        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8013            s.select(new_selections);
 8014        });
 8015        if state.stack.len() > 1 {
 8016            self.add_selections_state = Some(state);
 8017        }
 8018    }
 8019
 8020    pub fn select_next_match_internal(
 8021        &mut self,
 8022        display_map: &DisplaySnapshot,
 8023        replace_newest: bool,
 8024        autoscroll: Option<Autoscroll>,
 8025        cx: &mut ViewContext<Self>,
 8026    ) -> Result<()> {
 8027        fn select_next_match_ranges(
 8028            this: &mut Editor,
 8029            range: Range<usize>,
 8030            replace_newest: bool,
 8031            auto_scroll: Option<Autoscroll>,
 8032            cx: &mut ViewContext<Editor>,
 8033        ) {
 8034            this.unfold_ranges(&[range.clone()], false, true, cx);
 8035            this.change_selections(auto_scroll, cx, |s| {
 8036                if replace_newest {
 8037                    s.delete(s.newest_anchor().id);
 8038                }
 8039                s.insert_range(range.clone());
 8040            });
 8041        }
 8042
 8043        let buffer = &display_map.buffer_snapshot;
 8044        let mut selections = self.selections.all::<usize>(cx);
 8045        if let Some(mut select_next_state) = self.select_next_state.take() {
 8046            let query = &select_next_state.query;
 8047            if !select_next_state.done {
 8048                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8049                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8050                let mut next_selected_range = None;
 8051
 8052                let bytes_after_last_selection =
 8053                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8054                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8055                let query_matches = query
 8056                    .stream_find_iter(bytes_after_last_selection)
 8057                    .map(|result| (last_selection.end, result))
 8058                    .chain(
 8059                        query
 8060                            .stream_find_iter(bytes_before_first_selection)
 8061                            .map(|result| (0, result)),
 8062                    );
 8063
 8064                for (start_offset, query_match) in query_matches {
 8065                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8066                    let offset_range =
 8067                        start_offset + query_match.start()..start_offset + query_match.end();
 8068                    let display_range = offset_range.start.to_display_point(display_map)
 8069                        ..offset_range.end.to_display_point(display_map);
 8070
 8071                    if !select_next_state.wordwise
 8072                        || (!movement::is_inside_word(display_map, display_range.start)
 8073                            && !movement::is_inside_word(display_map, display_range.end))
 8074                    {
 8075                        // TODO: This is n^2, because we might check all the selections
 8076                        if !selections
 8077                            .iter()
 8078                            .any(|selection| selection.range().overlaps(&offset_range))
 8079                        {
 8080                            next_selected_range = Some(offset_range);
 8081                            break;
 8082                        }
 8083                    }
 8084                }
 8085
 8086                if let Some(next_selected_range) = next_selected_range {
 8087                    select_next_match_ranges(
 8088                        self,
 8089                        next_selected_range,
 8090                        replace_newest,
 8091                        autoscroll,
 8092                        cx,
 8093                    );
 8094                } else {
 8095                    select_next_state.done = true;
 8096                }
 8097            }
 8098
 8099            self.select_next_state = Some(select_next_state);
 8100        } else {
 8101            let mut only_carets = true;
 8102            let mut same_text_selected = true;
 8103            let mut selected_text = None;
 8104
 8105            let mut selections_iter = selections.iter().peekable();
 8106            while let Some(selection) = selections_iter.next() {
 8107                if selection.start != selection.end {
 8108                    only_carets = false;
 8109                }
 8110
 8111                if same_text_selected {
 8112                    if selected_text.is_none() {
 8113                        selected_text =
 8114                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8115                    }
 8116
 8117                    if let Some(next_selection) = selections_iter.peek() {
 8118                        if next_selection.range().len() == selection.range().len() {
 8119                            let next_selected_text = buffer
 8120                                .text_for_range(next_selection.range())
 8121                                .collect::<String>();
 8122                            if Some(next_selected_text) != selected_text {
 8123                                same_text_selected = false;
 8124                                selected_text = None;
 8125                            }
 8126                        } else {
 8127                            same_text_selected = false;
 8128                            selected_text = None;
 8129                        }
 8130                    }
 8131                }
 8132            }
 8133
 8134            if only_carets {
 8135                for selection in &mut selections {
 8136                    let word_range = movement::surrounding_word(
 8137                        display_map,
 8138                        selection.start.to_display_point(display_map),
 8139                    );
 8140                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8141                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8142                    selection.goal = SelectionGoal::None;
 8143                    selection.reversed = false;
 8144                    select_next_match_ranges(
 8145                        self,
 8146                        selection.start..selection.end,
 8147                        replace_newest,
 8148                        autoscroll,
 8149                        cx,
 8150                    );
 8151                }
 8152
 8153                if selections.len() == 1 {
 8154                    let selection = selections
 8155                        .last()
 8156                        .expect("ensured that there's only one selection");
 8157                    let query = buffer
 8158                        .text_for_range(selection.start..selection.end)
 8159                        .collect::<String>();
 8160                    let is_empty = query.is_empty();
 8161                    let select_state = SelectNextState {
 8162                        query: AhoCorasick::new(&[query])?,
 8163                        wordwise: true,
 8164                        done: is_empty,
 8165                    };
 8166                    self.select_next_state = Some(select_state);
 8167                } else {
 8168                    self.select_next_state = None;
 8169                }
 8170            } else if let Some(selected_text) = selected_text {
 8171                self.select_next_state = Some(SelectNextState {
 8172                    query: AhoCorasick::new(&[selected_text])?,
 8173                    wordwise: false,
 8174                    done: false,
 8175                });
 8176                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8177            }
 8178        }
 8179        Ok(())
 8180    }
 8181
 8182    pub fn select_all_matches(
 8183        &mut self,
 8184        _action: &SelectAllMatches,
 8185        cx: &mut ViewContext<Self>,
 8186    ) -> Result<()> {
 8187        self.push_to_selection_history();
 8188        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8189
 8190        self.select_next_match_internal(&display_map, false, None, cx)?;
 8191        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8192            return Ok(());
 8193        };
 8194        if select_next_state.done {
 8195            return Ok(());
 8196        }
 8197
 8198        let mut new_selections = self.selections.all::<usize>(cx);
 8199
 8200        let buffer = &display_map.buffer_snapshot;
 8201        let query_matches = select_next_state
 8202            .query
 8203            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8204
 8205        for query_match in query_matches {
 8206            let query_match = query_match.unwrap(); // can only fail due to I/O
 8207            let offset_range = query_match.start()..query_match.end();
 8208            let display_range = offset_range.start.to_display_point(&display_map)
 8209                ..offset_range.end.to_display_point(&display_map);
 8210
 8211            if !select_next_state.wordwise
 8212                || (!movement::is_inside_word(&display_map, display_range.start)
 8213                    && !movement::is_inside_word(&display_map, display_range.end))
 8214            {
 8215                self.selections.change_with(cx, |selections| {
 8216                    new_selections.push(Selection {
 8217                        id: selections.new_selection_id(),
 8218                        start: offset_range.start,
 8219                        end: offset_range.end,
 8220                        reversed: false,
 8221                        goal: SelectionGoal::None,
 8222                    });
 8223                });
 8224            }
 8225        }
 8226
 8227        new_selections.sort_by_key(|selection| selection.start);
 8228        let mut ix = 0;
 8229        while ix + 1 < new_selections.len() {
 8230            let current_selection = &new_selections[ix];
 8231            let next_selection = &new_selections[ix + 1];
 8232            if current_selection.range().overlaps(&next_selection.range()) {
 8233                if current_selection.id < next_selection.id {
 8234                    new_selections.remove(ix + 1);
 8235                } else {
 8236                    new_selections.remove(ix);
 8237                }
 8238            } else {
 8239                ix += 1;
 8240            }
 8241        }
 8242
 8243        select_next_state.done = true;
 8244        self.unfold_ranges(
 8245            &new_selections
 8246                .iter()
 8247                .map(|selection| selection.range())
 8248                .collect::<Vec<_>>(),
 8249            false,
 8250            false,
 8251            cx,
 8252        );
 8253        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8254            selections.select(new_selections)
 8255        });
 8256
 8257        Ok(())
 8258    }
 8259
 8260    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8261        self.push_to_selection_history();
 8262        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8263        self.select_next_match_internal(
 8264            &display_map,
 8265            action.replace_newest,
 8266            Some(Autoscroll::newest()),
 8267            cx,
 8268        )?;
 8269        Ok(())
 8270    }
 8271
 8272    pub fn select_previous(
 8273        &mut self,
 8274        action: &SelectPrevious,
 8275        cx: &mut ViewContext<Self>,
 8276    ) -> Result<()> {
 8277        self.push_to_selection_history();
 8278        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8279        let buffer = &display_map.buffer_snapshot;
 8280        let mut selections = self.selections.all::<usize>(cx);
 8281        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8282            let query = &select_prev_state.query;
 8283            if !select_prev_state.done {
 8284                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8285                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8286                let mut next_selected_range = None;
 8287                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8288                let bytes_before_last_selection =
 8289                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8290                let bytes_after_first_selection =
 8291                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8292                let query_matches = query
 8293                    .stream_find_iter(bytes_before_last_selection)
 8294                    .map(|result| (last_selection.start, result))
 8295                    .chain(
 8296                        query
 8297                            .stream_find_iter(bytes_after_first_selection)
 8298                            .map(|result| (buffer.len(), result)),
 8299                    );
 8300                for (end_offset, query_match) in query_matches {
 8301                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8302                    let offset_range =
 8303                        end_offset - query_match.end()..end_offset - query_match.start();
 8304                    let display_range = offset_range.start.to_display_point(&display_map)
 8305                        ..offset_range.end.to_display_point(&display_map);
 8306
 8307                    if !select_prev_state.wordwise
 8308                        || (!movement::is_inside_word(&display_map, display_range.start)
 8309                            && !movement::is_inside_word(&display_map, display_range.end))
 8310                    {
 8311                        next_selected_range = Some(offset_range);
 8312                        break;
 8313                    }
 8314                }
 8315
 8316                if let Some(next_selected_range) = next_selected_range {
 8317                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8318                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8319                        if action.replace_newest {
 8320                            s.delete(s.newest_anchor().id);
 8321                        }
 8322                        s.insert_range(next_selected_range);
 8323                    });
 8324                } else {
 8325                    select_prev_state.done = true;
 8326                }
 8327            }
 8328
 8329            self.select_prev_state = Some(select_prev_state);
 8330        } else {
 8331            let mut only_carets = true;
 8332            let mut same_text_selected = true;
 8333            let mut selected_text = None;
 8334
 8335            let mut selections_iter = selections.iter().peekable();
 8336            while let Some(selection) = selections_iter.next() {
 8337                if selection.start != selection.end {
 8338                    only_carets = false;
 8339                }
 8340
 8341                if same_text_selected {
 8342                    if selected_text.is_none() {
 8343                        selected_text =
 8344                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8345                    }
 8346
 8347                    if let Some(next_selection) = selections_iter.peek() {
 8348                        if next_selection.range().len() == selection.range().len() {
 8349                            let next_selected_text = buffer
 8350                                .text_for_range(next_selection.range())
 8351                                .collect::<String>();
 8352                            if Some(next_selected_text) != selected_text {
 8353                                same_text_selected = false;
 8354                                selected_text = None;
 8355                            }
 8356                        } else {
 8357                            same_text_selected = false;
 8358                            selected_text = None;
 8359                        }
 8360                    }
 8361                }
 8362            }
 8363
 8364            if only_carets {
 8365                for selection in &mut selections {
 8366                    let word_range = movement::surrounding_word(
 8367                        &display_map,
 8368                        selection.start.to_display_point(&display_map),
 8369                    );
 8370                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8371                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8372                    selection.goal = SelectionGoal::None;
 8373                    selection.reversed = false;
 8374                }
 8375                if selections.len() == 1 {
 8376                    let selection = selections
 8377                        .last()
 8378                        .expect("ensured that there's only one selection");
 8379                    let query = buffer
 8380                        .text_for_range(selection.start..selection.end)
 8381                        .collect::<String>();
 8382                    let is_empty = query.is_empty();
 8383                    let select_state = SelectNextState {
 8384                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8385                        wordwise: true,
 8386                        done: is_empty,
 8387                    };
 8388                    self.select_prev_state = Some(select_state);
 8389                } else {
 8390                    self.select_prev_state = None;
 8391                }
 8392
 8393                self.unfold_ranges(
 8394                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8395                    false,
 8396                    true,
 8397                    cx,
 8398                );
 8399                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8400                    s.select(selections);
 8401                });
 8402            } else if let Some(selected_text) = selected_text {
 8403                self.select_prev_state = Some(SelectNextState {
 8404                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8405                    wordwise: false,
 8406                    done: false,
 8407                });
 8408                self.select_previous(action, cx)?;
 8409            }
 8410        }
 8411        Ok(())
 8412    }
 8413
 8414    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8415        if self.read_only(cx) {
 8416            return;
 8417        }
 8418        let text_layout_details = &self.text_layout_details(cx);
 8419        self.transact(cx, |this, cx| {
 8420            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8421            let mut edits = Vec::new();
 8422            let mut selection_edit_ranges = Vec::new();
 8423            let mut last_toggled_row = None;
 8424            let snapshot = this.buffer.read(cx).read(cx);
 8425            let empty_str: Arc<str> = Arc::default();
 8426            let mut suffixes_inserted = Vec::new();
 8427            let ignore_indent = action.ignore_indent;
 8428
 8429            fn comment_prefix_range(
 8430                snapshot: &MultiBufferSnapshot,
 8431                row: MultiBufferRow,
 8432                comment_prefix: &str,
 8433                comment_prefix_whitespace: &str,
 8434                ignore_indent: bool,
 8435            ) -> Range<Point> {
 8436                let indent_size = if ignore_indent {
 8437                    0
 8438                } else {
 8439                    snapshot.indent_size_for_line(row).len
 8440                };
 8441
 8442                let start = Point::new(row.0, indent_size);
 8443
 8444                let mut line_bytes = snapshot
 8445                    .bytes_in_range(start..snapshot.max_point())
 8446                    .flatten()
 8447                    .copied();
 8448
 8449                // If this line currently begins with the line comment prefix, then record
 8450                // the range containing the prefix.
 8451                if line_bytes
 8452                    .by_ref()
 8453                    .take(comment_prefix.len())
 8454                    .eq(comment_prefix.bytes())
 8455                {
 8456                    // Include any whitespace that matches the comment prefix.
 8457                    let matching_whitespace_len = line_bytes
 8458                        .zip(comment_prefix_whitespace.bytes())
 8459                        .take_while(|(a, b)| a == b)
 8460                        .count() as u32;
 8461                    let end = Point::new(
 8462                        start.row,
 8463                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8464                    );
 8465                    start..end
 8466                } else {
 8467                    start..start
 8468                }
 8469            }
 8470
 8471            fn comment_suffix_range(
 8472                snapshot: &MultiBufferSnapshot,
 8473                row: MultiBufferRow,
 8474                comment_suffix: &str,
 8475                comment_suffix_has_leading_space: bool,
 8476            ) -> Range<Point> {
 8477                let end = Point::new(row.0, snapshot.line_len(row));
 8478                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8479
 8480                let mut line_end_bytes = snapshot
 8481                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8482                    .flatten()
 8483                    .copied();
 8484
 8485                let leading_space_len = if suffix_start_column > 0
 8486                    && line_end_bytes.next() == Some(b' ')
 8487                    && comment_suffix_has_leading_space
 8488                {
 8489                    1
 8490                } else {
 8491                    0
 8492                };
 8493
 8494                // If this line currently begins with the line comment prefix, then record
 8495                // the range containing the prefix.
 8496                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8497                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8498                    start..end
 8499                } else {
 8500                    end..end
 8501                }
 8502            }
 8503
 8504            // TODO: Handle selections that cross excerpts
 8505            for selection in &mut selections {
 8506                let start_column = snapshot
 8507                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8508                    .len;
 8509                let language = if let Some(language) =
 8510                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8511                {
 8512                    language
 8513                } else {
 8514                    continue;
 8515                };
 8516
 8517                selection_edit_ranges.clear();
 8518
 8519                // If multiple selections contain a given row, avoid processing that
 8520                // row more than once.
 8521                let mut start_row = MultiBufferRow(selection.start.row);
 8522                if last_toggled_row == Some(start_row) {
 8523                    start_row = start_row.next_row();
 8524                }
 8525                let end_row =
 8526                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8527                        MultiBufferRow(selection.end.row - 1)
 8528                    } else {
 8529                        MultiBufferRow(selection.end.row)
 8530                    };
 8531                last_toggled_row = Some(end_row);
 8532
 8533                if start_row > end_row {
 8534                    continue;
 8535                }
 8536
 8537                // If the language has line comments, toggle those.
 8538                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8539
 8540                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8541                if ignore_indent {
 8542                    full_comment_prefixes = full_comment_prefixes
 8543                        .into_iter()
 8544                        .map(|s| Arc::from(s.trim_end()))
 8545                        .collect();
 8546                }
 8547
 8548                if !full_comment_prefixes.is_empty() {
 8549                    let first_prefix = full_comment_prefixes
 8550                        .first()
 8551                        .expect("prefixes is non-empty");
 8552                    let prefix_trimmed_lengths = full_comment_prefixes
 8553                        .iter()
 8554                        .map(|p| p.trim_end_matches(' ').len())
 8555                        .collect::<SmallVec<[usize; 4]>>();
 8556
 8557                    let mut all_selection_lines_are_comments = true;
 8558
 8559                    for row in start_row.0..=end_row.0 {
 8560                        let row = MultiBufferRow(row);
 8561                        if start_row < end_row && snapshot.is_line_blank(row) {
 8562                            continue;
 8563                        }
 8564
 8565                        let prefix_range = full_comment_prefixes
 8566                            .iter()
 8567                            .zip(prefix_trimmed_lengths.iter().copied())
 8568                            .map(|(prefix, trimmed_prefix_len)| {
 8569                                comment_prefix_range(
 8570                                    snapshot.deref(),
 8571                                    row,
 8572                                    &prefix[..trimmed_prefix_len],
 8573                                    &prefix[trimmed_prefix_len..],
 8574                                    ignore_indent,
 8575                                )
 8576                            })
 8577                            .max_by_key(|range| range.end.column - range.start.column)
 8578                            .expect("prefixes is non-empty");
 8579
 8580                        if prefix_range.is_empty() {
 8581                            all_selection_lines_are_comments = false;
 8582                        }
 8583
 8584                        selection_edit_ranges.push(prefix_range);
 8585                    }
 8586
 8587                    if all_selection_lines_are_comments {
 8588                        edits.extend(
 8589                            selection_edit_ranges
 8590                                .iter()
 8591                                .cloned()
 8592                                .map(|range| (range, empty_str.clone())),
 8593                        );
 8594                    } else {
 8595                        let min_column = selection_edit_ranges
 8596                            .iter()
 8597                            .map(|range| range.start.column)
 8598                            .min()
 8599                            .unwrap_or(0);
 8600                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8601                            let position = Point::new(range.start.row, min_column);
 8602                            (position..position, first_prefix.clone())
 8603                        }));
 8604                    }
 8605                } else if let Some((full_comment_prefix, comment_suffix)) =
 8606                    language.block_comment_delimiters()
 8607                {
 8608                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8609                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8610                    let prefix_range = comment_prefix_range(
 8611                        snapshot.deref(),
 8612                        start_row,
 8613                        comment_prefix,
 8614                        comment_prefix_whitespace,
 8615                        ignore_indent,
 8616                    );
 8617                    let suffix_range = comment_suffix_range(
 8618                        snapshot.deref(),
 8619                        end_row,
 8620                        comment_suffix.trim_start_matches(' '),
 8621                        comment_suffix.starts_with(' '),
 8622                    );
 8623
 8624                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8625                        edits.push((
 8626                            prefix_range.start..prefix_range.start,
 8627                            full_comment_prefix.clone(),
 8628                        ));
 8629                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8630                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8631                    } else {
 8632                        edits.push((prefix_range, empty_str.clone()));
 8633                        edits.push((suffix_range, empty_str.clone()));
 8634                    }
 8635                } else {
 8636                    continue;
 8637                }
 8638            }
 8639
 8640            drop(snapshot);
 8641            this.buffer.update(cx, |buffer, cx| {
 8642                buffer.edit(edits, None, cx);
 8643            });
 8644
 8645            // Adjust selections so that they end before any comment suffixes that
 8646            // were inserted.
 8647            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8648            let mut selections = this.selections.all::<Point>(cx);
 8649            let snapshot = this.buffer.read(cx).read(cx);
 8650            for selection in &mut selections {
 8651                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8652                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8653                        Ordering::Less => {
 8654                            suffixes_inserted.next();
 8655                            continue;
 8656                        }
 8657                        Ordering::Greater => break,
 8658                        Ordering::Equal => {
 8659                            if selection.end.column == snapshot.line_len(row) {
 8660                                if selection.is_empty() {
 8661                                    selection.start.column -= suffix_len as u32;
 8662                                }
 8663                                selection.end.column -= suffix_len as u32;
 8664                            }
 8665                            break;
 8666                        }
 8667                    }
 8668                }
 8669            }
 8670
 8671            drop(snapshot);
 8672            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8673
 8674            let selections = this.selections.all::<Point>(cx);
 8675            let selections_on_single_row = selections.windows(2).all(|selections| {
 8676                selections[0].start.row == selections[1].start.row
 8677                    && selections[0].end.row == selections[1].end.row
 8678                    && selections[0].start.row == selections[0].end.row
 8679            });
 8680            let selections_selecting = selections
 8681                .iter()
 8682                .any(|selection| selection.start != selection.end);
 8683            let advance_downwards = action.advance_downwards
 8684                && selections_on_single_row
 8685                && !selections_selecting
 8686                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8687
 8688            if advance_downwards {
 8689                let snapshot = this.buffer.read(cx).snapshot(cx);
 8690
 8691                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8692                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8693                        let mut point = display_point.to_point(display_snapshot);
 8694                        point.row += 1;
 8695                        point = snapshot.clip_point(point, Bias::Left);
 8696                        let display_point = point.to_display_point(display_snapshot);
 8697                        let goal = SelectionGoal::HorizontalPosition(
 8698                            display_snapshot
 8699                                .x_for_display_point(display_point, text_layout_details)
 8700                                .into(),
 8701                        );
 8702                        (display_point, goal)
 8703                    })
 8704                });
 8705            }
 8706        });
 8707    }
 8708
 8709    pub fn select_enclosing_symbol(
 8710        &mut self,
 8711        _: &SelectEnclosingSymbol,
 8712        cx: &mut ViewContext<Self>,
 8713    ) {
 8714        let buffer = self.buffer.read(cx).snapshot(cx);
 8715        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8716
 8717        fn update_selection(
 8718            selection: &Selection<usize>,
 8719            buffer_snap: &MultiBufferSnapshot,
 8720        ) -> Option<Selection<usize>> {
 8721            let cursor = selection.head();
 8722            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8723            for symbol in symbols.iter().rev() {
 8724                let start = symbol.range.start.to_offset(buffer_snap);
 8725                let end = symbol.range.end.to_offset(buffer_snap);
 8726                let new_range = start..end;
 8727                if start < selection.start || end > selection.end {
 8728                    return Some(Selection {
 8729                        id: selection.id,
 8730                        start: new_range.start,
 8731                        end: new_range.end,
 8732                        goal: SelectionGoal::None,
 8733                        reversed: selection.reversed,
 8734                    });
 8735                }
 8736            }
 8737            None
 8738        }
 8739
 8740        let mut selected_larger_symbol = false;
 8741        let new_selections = old_selections
 8742            .iter()
 8743            .map(|selection| match update_selection(selection, &buffer) {
 8744                Some(new_selection) => {
 8745                    if new_selection.range() != selection.range() {
 8746                        selected_larger_symbol = true;
 8747                    }
 8748                    new_selection
 8749                }
 8750                None => selection.clone(),
 8751            })
 8752            .collect::<Vec<_>>();
 8753
 8754        if selected_larger_symbol {
 8755            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8756                s.select(new_selections);
 8757            });
 8758        }
 8759    }
 8760
 8761    pub fn select_larger_syntax_node(
 8762        &mut self,
 8763        _: &SelectLargerSyntaxNode,
 8764        cx: &mut ViewContext<Self>,
 8765    ) {
 8766        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8767        let buffer = self.buffer.read(cx).snapshot(cx);
 8768        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8769
 8770        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8771        let mut selected_larger_node = false;
 8772        let new_selections = old_selections
 8773            .iter()
 8774            .map(|selection| {
 8775                let old_range = selection.start..selection.end;
 8776                let mut new_range = old_range.clone();
 8777                let mut new_node = None;
 8778                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 8779                {
 8780                    new_node = Some(node);
 8781                    new_range = containing_range;
 8782                    if !display_map.intersects_fold(new_range.start)
 8783                        && !display_map.intersects_fold(new_range.end)
 8784                    {
 8785                        break;
 8786                    }
 8787                }
 8788
 8789                if let Some(node) = new_node {
 8790                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 8791                    // nodes. Parent and grandparent are also logged because this operation will not
 8792                    // visit nodes that have the same range as their parent.
 8793                    log::info!("Node: {node:?}");
 8794                    let parent = node.parent();
 8795                    log::info!("Parent: {parent:?}");
 8796                    let grandparent = parent.and_then(|x| x.parent());
 8797                    log::info!("Grandparent: {grandparent:?}");
 8798                }
 8799
 8800                selected_larger_node |= new_range != old_range;
 8801                Selection {
 8802                    id: selection.id,
 8803                    start: new_range.start,
 8804                    end: new_range.end,
 8805                    goal: SelectionGoal::None,
 8806                    reversed: selection.reversed,
 8807                }
 8808            })
 8809            .collect::<Vec<_>>();
 8810
 8811        if selected_larger_node {
 8812            stack.push(old_selections);
 8813            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8814                s.select(new_selections);
 8815            });
 8816        }
 8817        self.select_larger_syntax_node_stack = stack;
 8818    }
 8819
 8820    pub fn select_smaller_syntax_node(
 8821        &mut self,
 8822        _: &SelectSmallerSyntaxNode,
 8823        cx: &mut ViewContext<Self>,
 8824    ) {
 8825        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8826        if let Some(selections) = stack.pop() {
 8827            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8828                s.select(selections.to_vec());
 8829            });
 8830        }
 8831        self.select_larger_syntax_node_stack = stack;
 8832    }
 8833
 8834    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8835        if !EditorSettings::get_global(cx).gutter.runnables {
 8836            self.clear_tasks();
 8837            return Task::ready(());
 8838        }
 8839        let project = self.project.as_ref().map(Model::downgrade);
 8840        cx.spawn(|this, mut cx| async move {
 8841            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8842            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8843                return;
 8844            };
 8845            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8846                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8847            }) else {
 8848                return;
 8849            };
 8850
 8851            let hide_runnables = project
 8852                .update(&mut cx, |project, cx| {
 8853                    // Do not display any test indicators in non-dev server remote projects.
 8854                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8855                })
 8856                .unwrap_or(true);
 8857            if hide_runnables {
 8858                return;
 8859            }
 8860            let new_rows =
 8861                cx.background_executor()
 8862                    .spawn({
 8863                        let snapshot = display_snapshot.clone();
 8864                        async move {
 8865                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8866                        }
 8867                    })
 8868                    .await;
 8869            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8870
 8871            this.update(&mut cx, |this, _| {
 8872                this.clear_tasks();
 8873                for (key, value) in rows {
 8874                    this.insert_tasks(key, value);
 8875                }
 8876            })
 8877            .ok();
 8878        })
 8879    }
 8880    fn fetch_runnable_ranges(
 8881        snapshot: &DisplaySnapshot,
 8882        range: Range<Anchor>,
 8883    ) -> Vec<language::RunnableRange> {
 8884        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8885    }
 8886
 8887    fn runnable_rows(
 8888        project: Model<Project>,
 8889        snapshot: DisplaySnapshot,
 8890        runnable_ranges: Vec<RunnableRange>,
 8891        mut cx: AsyncWindowContext,
 8892    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8893        runnable_ranges
 8894            .into_iter()
 8895            .filter_map(|mut runnable| {
 8896                let tasks = cx
 8897                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8898                    .ok()?;
 8899                if tasks.is_empty() {
 8900                    return None;
 8901                }
 8902
 8903                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8904
 8905                let row = snapshot
 8906                    .buffer_snapshot
 8907                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8908                    .1
 8909                    .start
 8910                    .row;
 8911
 8912                let context_range =
 8913                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8914                Some((
 8915                    (runnable.buffer_id, row),
 8916                    RunnableTasks {
 8917                        templates: tasks,
 8918                        offset: MultiBufferOffset(runnable.run_range.start),
 8919                        context_range,
 8920                        column: point.column,
 8921                        extra_variables: runnable.extra_captures,
 8922                    },
 8923                ))
 8924            })
 8925            .collect()
 8926    }
 8927
 8928    fn templates_with_tags(
 8929        project: &Model<Project>,
 8930        runnable: &mut Runnable,
 8931        cx: &WindowContext<'_>,
 8932    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8933        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8934            let (worktree_id, file) = project
 8935                .buffer_for_id(runnable.buffer, cx)
 8936                .and_then(|buffer| buffer.read(cx).file())
 8937                .map(|file| (file.worktree_id(cx), file.clone()))
 8938                .unzip();
 8939
 8940            (
 8941                project.task_store().read(cx).task_inventory().cloned(),
 8942                worktree_id,
 8943                file,
 8944            )
 8945        });
 8946
 8947        let tags = mem::take(&mut runnable.tags);
 8948        let mut tags: Vec<_> = tags
 8949            .into_iter()
 8950            .flat_map(|tag| {
 8951                let tag = tag.0.clone();
 8952                inventory
 8953                    .as_ref()
 8954                    .into_iter()
 8955                    .flat_map(|inventory| {
 8956                        inventory.read(cx).list_tasks(
 8957                            file.clone(),
 8958                            Some(runnable.language.clone()),
 8959                            worktree_id,
 8960                            cx,
 8961                        )
 8962                    })
 8963                    .filter(move |(_, template)| {
 8964                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8965                    })
 8966            })
 8967            .sorted_by_key(|(kind, _)| kind.to_owned())
 8968            .collect();
 8969        if let Some((leading_tag_source, _)) = tags.first() {
 8970            // Strongest source wins; if we have worktree tag binding, prefer that to
 8971            // global and language bindings;
 8972            // if we have a global binding, prefer that to language binding.
 8973            let first_mismatch = tags
 8974                .iter()
 8975                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8976            if let Some(index) = first_mismatch {
 8977                tags.truncate(index);
 8978            }
 8979        }
 8980
 8981        tags
 8982    }
 8983
 8984    pub fn move_to_enclosing_bracket(
 8985        &mut self,
 8986        _: &MoveToEnclosingBracket,
 8987        cx: &mut ViewContext<Self>,
 8988    ) {
 8989        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8990            s.move_offsets_with(|snapshot, selection| {
 8991                let Some(enclosing_bracket_ranges) =
 8992                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8993                else {
 8994                    return;
 8995                };
 8996
 8997                let mut best_length = usize::MAX;
 8998                let mut best_inside = false;
 8999                let mut best_in_bracket_range = false;
 9000                let mut best_destination = None;
 9001                for (open, close) in enclosing_bracket_ranges {
 9002                    let close = close.to_inclusive();
 9003                    let length = close.end() - open.start;
 9004                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9005                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9006                        || close.contains(&selection.head());
 9007
 9008                    // If best is next to a bracket and current isn't, skip
 9009                    if !in_bracket_range && best_in_bracket_range {
 9010                        continue;
 9011                    }
 9012
 9013                    // Prefer smaller lengths unless best is inside and current isn't
 9014                    if length > best_length && (best_inside || !inside) {
 9015                        continue;
 9016                    }
 9017
 9018                    best_length = length;
 9019                    best_inside = inside;
 9020                    best_in_bracket_range = in_bracket_range;
 9021                    best_destination = Some(
 9022                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9023                            if inside {
 9024                                open.end
 9025                            } else {
 9026                                open.start
 9027                            }
 9028                        } else if inside {
 9029                            *close.start()
 9030                        } else {
 9031                            *close.end()
 9032                        },
 9033                    );
 9034                }
 9035
 9036                if let Some(destination) = best_destination {
 9037                    selection.collapse_to(destination, SelectionGoal::None);
 9038                }
 9039            })
 9040        });
 9041    }
 9042
 9043    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9044        self.end_selection(cx);
 9045        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9046        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9047            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9048            self.select_next_state = entry.select_next_state;
 9049            self.select_prev_state = entry.select_prev_state;
 9050            self.add_selections_state = entry.add_selections_state;
 9051            self.request_autoscroll(Autoscroll::newest(), cx);
 9052        }
 9053        self.selection_history.mode = SelectionHistoryMode::Normal;
 9054    }
 9055
 9056    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9057        self.end_selection(cx);
 9058        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9059        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9060            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9061            self.select_next_state = entry.select_next_state;
 9062            self.select_prev_state = entry.select_prev_state;
 9063            self.add_selections_state = entry.add_selections_state;
 9064            self.request_autoscroll(Autoscroll::newest(), cx);
 9065        }
 9066        self.selection_history.mode = SelectionHistoryMode::Normal;
 9067    }
 9068
 9069    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9070        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9071    }
 9072
 9073    pub fn expand_excerpts_down(
 9074        &mut self,
 9075        action: &ExpandExcerptsDown,
 9076        cx: &mut ViewContext<Self>,
 9077    ) {
 9078        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9079    }
 9080
 9081    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9082        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9083    }
 9084
 9085    pub fn expand_excerpts_for_direction(
 9086        &mut self,
 9087        lines: u32,
 9088        direction: ExpandExcerptDirection,
 9089        cx: &mut ViewContext<Self>,
 9090    ) {
 9091        let selections = self.selections.disjoint_anchors();
 9092
 9093        let lines = if lines == 0 {
 9094            EditorSettings::get_global(cx).expand_excerpt_lines
 9095        } else {
 9096            lines
 9097        };
 9098
 9099        self.buffer.update(cx, |buffer, cx| {
 9100            buffer.expand_excerpts(
 9101                selections
 9102                    .iter()
 9103                    .map(|selection| selection.head().excerpt_id)
 9104                    .dedup(),
 9105                lines,
 9106                direction,
 9107                cx,
 9108            )
 9109        })
 9110    }
 9111
 9112    pub fn expand_excerpt(
 9113        &mut self,
 9114        excerpt: ExcerptId,
 9115        direction: ExpandExcerptDirection,
 9116        cx: &mut ViewContext<Self>,
 9117    ) {
 9118        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9119        self.buffer.update(cx, |buffer, cx| {
 9120            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9121        })
 9122    }
 9123
 9124    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9125        self.go_to_diagnostic_impl(Direction::Next, cx)
 9126    }
 9127
 9128    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9129        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9130    }
 9131
 9132    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9133        let buffer = self.buffer.read(cx).snapshot(cx);
 9134        let selection = self.selections.newest::<usize>(cx);
 9135
 9136        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9137        if direction == Direction::Next {
 9138            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9139                let (group_id, jump_to) = popover.activation_info();
 9140                if self.activate_diagnostics(group_id, cx) {
 9141                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9142                        let mut new_selection = s.newest_anchor().clone();
 9143                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9144                        s.select_anchors(vec![new_selection.clone()]);
 9145                    });
 9146                }
 9147                return;
 9148            }
 9149        }
 9150
 9151        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9152            active_diagnostics
 9153                .primary_range
 9154                .to_offset(&buffer)
 9155                .to_inclusive()
 9156        });
 9157        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9158            if active_primary_range.contains(&selection.head()) {
 9159                *active_primary_range.start()
 9160            } else {
 9161                selection.head()
 9162            }
 9163        } else {
 9164            selection.head()
 9165        };
 9166        let snapshot = self.snapshot(cx);
 9167        loop {
 9168            let diagnostics = if direction == Direction::Prev {
 9169                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9170            } else {
 9171                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9172            }
 9173            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9174            let group = diagnostics
 9175                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9176                // be sorted in a stable way
 9177                // skip until we are at current active diagnostic, if it exists
 9178                .skip_while(|entry| {
 9179                    (match direction {
 9180                        Direction::Prev => entry.range.start >= search_start,
 9181                        Direction::Next => entry.range.start <= search_start,
 9182                    }) && self
 9183                        .active_diagnostics
 9184                        .as_ref()
 9185                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9186                })
 9187                .find_map(|entry| {
 9188                    if entry.diagnostic.is_primary
 9189                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9190                        && !entry.range.is_empty()
 9191                        // if we match with the active diagnostic, skip it
 9192                        && Some(entry.diagnostic.group_id)
 9193                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9194                    {
 9195                        Some((entry.range, entry.diagnostic.group_id))
 9196                    } else {
 9197                        None
 9198                    }
 9199                });
 9200
 9201            if let Some((primary_range, group_id)) = group {
 9202                if self.activate_diagnostics(group_id, cx) {
 9203                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9204                        s.select(vec![Selection {
 9205                            id: selection.id,
 9206                            start: primary_range.start,
 9207                            end: primary_range.start,
 9208                            reversed: false,
 9209                            goal: SelectionGoal::None,
 9210                        }]);
 9211                    });
 9212                }
 9213                break;
 9214            } else {
 9215                // Cycle around to the start of the buffer, potentially moving back to the start of
 9216                // the currently active diagnostic.
 9217                active_primary_range.take();
 9218                if direction == Direction::Prev {
 9219                    if search_start == buffer.len() {
 9220                        break;
 9221                    } else {
 9222                        search_start = buffer.len();
 9223                    }
 9224                } else if search_start == 0 {
 9225                    break;
 9226                } else {
 9227                    search_start = 0;
 9228                }
 9229            }
 9230        }
 9231    }
 9232
 9233    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9234        let snapshot = self.snapshot(cx);
 9235        let selection = self.selections.newest::<Point>(cx);
 9236        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9237    }
 9238
 9239    fn go_to_hunk_after_position(
 9240        &mut self,
 9241        snapshot: &EditorSnapshot,
 9242        position: Point,
 9243        cx: &mut ViewContext<'_, Editor>,
 9244    ) -> Option<MultiBufferDiffHunk> {
 9245        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9246            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9247                snapshot,
 9248                position,
 9249                ix > 0,
 9250                snapshot.diff_map.diff_hunks_in_range(
 9251                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9252                    &snapshot.buffer_snapshot,
 9253                ),
 9254                cx,
 9255            ) {
 9256                return Some(hunk);
 9257            }
 9258        }
 9259        None
 9260    }
 9261
 9262    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9263        let snapshot = self.snapshot(cx);
 9264        let selection = self.selections.newest::<Point>(cx);
 9265        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9266    }
 9267
 9268    fn go_to_hunk_before_position(
 9269        &mut self,
 9270        snapshot: &EditorSnapshot,
 9271        position: Point,
 9272        cx: &mut ViewContext<'_, Editor>,
 9273    ) -> Option<MultiBufferDiffHunk> {
 9274        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9275            .into_iter()
 9276            .enumerate()
 9277        {
 9278            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9279                snapshot,
 9280                position,
 9281                ix > 0,
 9282                snapshot
 9283                    .diff_map
 9284                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9285                cx,
 9286            ) {
 9287                return Some(hunk);
 9288            }
 9289        }
 9290        None
 9291    }
 9292
 9293    fn go_to_next_hunk_in_direction(
 9294        &mut self,
 9295        snapshot: &DisplaySnapshot,
 9296        initial_point: Point,
 9297        is_wrapped: bool,
 9298        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9299        cx: &mut ViewContext<Editor>,
 9300    ) -> Option<MultiBufferDiffHunk> {
 9301        let display_point = initial_point.to_display_point(snapshot);
 9302        let mut hunks = hunks
 9303            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9304            .filter(|(display_hunk, _)| {
 9305                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9306            })
 9307            .dedup();
 9308
 9309        if let Some((display_hunk, hunk)) = hunks.next() {
 9310            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9311                let row = display_hunk.start_display_row();
 9312                let point = DisplayPoint::new(row, 0);
 9313                s.select_display_ranges([point..point]);
 9314            });
 9315
 9316            Some(hunk)
 9317        } else {
 9318            None
 9319        }
 9320    }
 9321
 9322    pub fn go_to_definition(
 9323        &mut self,
 9324        _: &GoToDefinition,
 9325        cx: &mut ViewContext<Self>,
 9326    ) -> Task<Result<Navigated>> {
 9327        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9328        cx.spawn(|editor, mut cx| async move {
 9329            if definition.await? == Navigated::Yes {
 9330                return Ok(Navigated::Yes);
 9331            }
 9332            match editor.update(&mut cx, |editor, cx| {
 9333                editor.find_all_references(&FindAllReferences, cx)
 9334            })? {
 9335                Some(references) => references.await,
 9336                None => Ok(Navigated::No),
 9337            }
 9338        })
 9339    }
 9340
 9341    pub fn go_to_declaration(
 9342        &mut self,
 9343        _: &GoToDeclaration,
 9344        cx: &mut ViewContext<Self>,
 9345    ) -> Task<Result<Navigated>> {
 9346        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9347    }
 9348
 9349    pub fn go_to_declaration_split(
 9350        &mut self,
 9351        _: &GoToDeclaration,
 9352        cx: &mut ViewContext<Self>,
 9353    ) -> Task<Result<Navigated>> {
 9354        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9355    }
 9356
 9357    pub fn go_to_implementation(
 9358        &mut self,
 9359        _: &GoToImplementation,
 9360        cx: &mut ViewContext<Self>,
 9361    ) -> Task<Result<Navigated>> {
 9362        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9363    }
 9364
 9365    pub fn go_to_implementation_split(
 9366        &mut self,
 9367        _: &GoToImplementationSplit,
 9368        cx: &mut ViewContext<Self>,
 9369    ) -> Task<Result<Navigated>> {
 9370        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9371    }
 9372
 9373    pub fn go_to_type_definition(
 9374        &mut self,
 9375        _: &GoToTypeDefinition,
 9376        cx: &mut ViewContext<Self>,
 9377    ) -> Task<Result<Navigated>> {
 9378        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9379    }
 9380
 9381    pub fn go_to_definition_split(
 9382        &mut self,
 9383        _: &GoToDefinitionSplit,
 9384        cx: &mut ViewContext<Self>,
 9385    ) -> Task<Result<Navigated>> {
 9386        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9387    }
 9388
 9389    pub fn go_to_type_definition_split(
 9390        &mut self,
 9391        _: &GoToTypeDefinitionSplit,
 9392        cx: &mut ViewContext<Self>,
 9393    ) -> Task<Result<Navigated>> {
 9394        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9395    }
 9396
 9397    fn go_to_definition_of_kind(
 9398        &mut self,
 9399        kind: GotoDefinitionKind,
 9400        split: bool,
 9401        cx: &mut ViewContext<Self>,
 9402    ) -> Task<Result<Navigated>> {
 9403        let Some(provider) = self.semantics_provider.clone() else {
 9404            return Task::ready(Ok(Navigated::No));
 9405        };
 9406        let head = self.selections.newest::<usize>(cx).head();
 9407        let buffer = self.buffer.read(cx);
 9408        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9409            text_anchor
 9410        } else {
 9411            return Task::ready(Ok(Navigated::No));
 9412        };
 9413
 9414        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9415            return Task::ready(Ok(Navigated::No));
 9416        };
 9417
 9418        cx.spawn(|editor, mut cx| async move {
 9419            let definitions = definitions.await?;
 9420            let navigated = editor
 9421                .update(&mut cx, |editor, cx| {
 9422                    editor.navigate_to_hover_links(
 9423                        Some(kind),
 9424                        definitions
 9425                            .into_iter()
 9426                            .filter(|location| {
 9427                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9428                            })
 9429                            .map(HoverLink::Text)
 9430                            .collect::<Vec<_>>(),
 9431                        split,
 9432                        cx,
 9433                    )
 9434                })?
 9435                .await?;
 9436            anyhow::Ok(navigated)
 9437        })
 9438    }
 9439
 9440    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9441        let selection = self.selections.newest_anchor();
 9442        let head = selection.head();
 9443        let tail = selection.tail();
 9444
 9445        let Some((buffer, start_position)) =
 9446            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9447        else {
 9448            return;
 9449        };
 9450
 9451        let end_position = if head != tail {
 9452            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9453                return;
 9454            };
 9455            Some(pos)
 9456        } else {
 9457            None
 9458        };
 9459
 9460        let url_finder = cx.spawn(|editor, mut cx| async move {
 9461            let url = if let Some(end_pos) = end_position {
 9462                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9463            } else {
 9464                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9465            };
 9466
 9467            if let Some(url) = url {
 9468                editor.update(&mut cx, |_, cx| {
 9469                    cx.open_url(&url);
 9470                })
 9471            } else {
 9472                Ok(())
 9473            }
 9474        });
 9475
 9476        url_finder.detach();
 9477    }
 9478
 9479    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9480        let Some(workspace) = self.workspace() else {
 9481            return;
 9482        };
 9483
 9484        let position = self.selections.newest_anchor().head();
 9485
 9486        let Some((buffer, buffer_position)) =
 9487            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9488        else {
 9489            return;
 9490        };
 9491
 9492        let project = self.project.clone();
 9493
 9494        cx.spawn(|_, mut cx| async move {
 9495            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9496
 9497            if let Some((_, path)) = result {
 9498                workspace
 9499                    .update(&mut cx, |workspace, cx| {
 9500                        workspace.open_resolved_path(path, cx)
 9501                    })?
 9502                    .await?;
 9503            }
 9504            anyhow::Ok(())
 9505        })
 9506        .detach();
 9507    }
 9508
 9509    pub(crate) fn navigate_to_hover_links(
 9510        &mut self,
 9511        kind: Option<GotoDefinitionKind>,
 9512        mut definitions: Vec<HoverLink>,
 9513        split: bool,
 9514        cx: &mut ViewContext<Editor>,
 9515    ) -> Task<Result<Navigated>> {
 9516        // If there is one definition, just open it directly
 9517        if definitions.len() == 1 {
 9518            let definition = definitions.pop().unwrap();
 9519
 9520            enum TargetTaskResult {
 9521                Location(Option<Location>),
 9522                AlreadyNavigated,
 9523            }
 9524
 9525            let target_task = match definition {
 9526                HoverLink::Text(link) => {
 9527                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9528                }
 9529                HoverLink::InlayHint(lsp_location, server_id) => {
 9530                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9531                    cx.background_executor().spawn(async move {
 9532                        let location = computation.await?;
 9533                        Ok(TargetTaskResult::Location(location))
 9534                    })
 9535                }
 9536                HoverLink::Url(url) => {
 9537                    cx.open_url(&url);
 9538                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9539                }
 9540                HoverLink::File(path) => {
 9541                    if let Some(workspace) = self.workspace() {
 9542                        cx.spawn(|_, mut cx| async move {
 9543                            workspace
 9544                                .update(&mut cx, |workspace, cx| {
 9545                                    workspace.open_resolved_path(path, cx)
 9546                                })?
 9547                                .await
 9548                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9549                        })
 9550                    } else {
 9551                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9552                    }
 9553                }
 9554            };
 9555            cx.spawn(|editor, mut cx| async move {
 9556                let target = match target_task.await.context("target resolution task")? {
 9557                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9558                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9559                    TargetTaskResult::Location(Some(target)) => target,
 9560                };
 9561
 9562                editor.update(&mut cx, |editor, cx| {
 9563                    let Some(workspace) = editor.workspace() else {
 9564                        return Navigated::No;
 9565                    };
 9566                    let pane = workspace.read(cx).active_pane().clone();
 9567
 9568                    let range = target.range.to_offset(target.buffer.read(cx));
 9569                    let range = editor.range_for_match(&range);
 9570
 9571                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9572                        let buffer = target.buffer.read(cx);
 9573                        let range = check_multiline_range(buffer, range);
 9574                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9575                            s.select_ranges([range]);
 9576                        });
 9577                    } else {
 9578                        cx.window_context().defer(move |cx| {
 9579                            let target_editor: View<Self> =
 9580                                workspace.update(cx, |workspace, cx| {
 9581                                    let pane = if split {
 9582                                        workspace.adjacent_pane(cx)
 9583                                    } else {
 9584                                        workspace.active_pane().clone()
 9585                                    };
 9586
 9587                                    workspace.open_project_item(
 9588                                        pane,
 9589                                        target.buffer.clone(),
 9590                                        true,
 9591                                        true,
 9592                                        cx,
 9593                                    )
 9594                                });
 9595                            target_editor.update(cx, |target_editor, cx| {
 9596                                // When selecting a definition in a different buffer, disable the nav history
 9597                                // to avoid creating a history entry at the previous cursor location.
 9598                                pane.update(cx, |pane, _| pane.disable_history());
 9599                                let buffer = target.buffer.read(cx);
 9600                                let range = check_multiline_range(buffer, range);
 9601                                target_editor.change_selections(
 9602                                    Some(Autoscroll::focused()),
 9603                                    cx,
 9604                                    |s| {
 9605                                        s.select_ranges([range]);
 9606                                    },
 9607                                );
 9608                                pane.update(cx, |pane, _| pane.enable_history());
 9609                            });
 9610                        });
 9611                    }
 9612                    Navigated::Yes
 9613                })
 9614            })
 9615        } else if !definitions.is_empty() {
 9616            cx.spawn(|editor, mut cx| async move {
 9617                let (title, location_tasks, workspace) = editor
 9618                    .update(&mut cx, |editor, cx| {
 9619                        let tab_kind = match kind {
 9620                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9621                            _ => "Definitions",
 9622                        };
 9623                        let title = definitions
 9624                            .iter()
 9625                            .find_map(|definition| match definition {
 9626                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9627                                    let buffer = origin.buffer.read(cx);
 9628                                    format!(
 9629                                        "{} for {}",
 9630                                        tab_kind,
 9631                                        buffer
 9632                                            .text_for_range(origin.range.clone())
 9633                                            .collect::<String>()
 9634                                    )
 9635                                }),
 9636                                HoverLink::InlayHint(_, _) => None,
 9637                                HoverLink::Url(_) => None,
 9638                                HoverLink::File(_) => None,
 9639                            })
 9640                            .unwrap_or(tab_kind.to_string());
 9641                        let location_tasks = definitions
 9642                            .into_iter()
 9643                            .map(|definition| match definition {
 9644                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9645                                HoverLink::InlayHint(lsp_location, server_id) => {
 9646                                    editor.compute_target_location(lsp_location, server_id, cx)
 9647                                }
 9648                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9649                                HoverLink::File(_) => Task::ready(Ok(None)),
 9650                            })
 9651                            .collect::<Vec<_>>();
 9652                        (title, location_tasks, editor.workspace().clone())
 9653                    })
 9654                    .context("location tasks preparation")?;
 9655
 9656                let locations = future::join_all(location_tasks)
 9657                    .await
 9658                    .into_iter()
 9659                    .filter_map(|location| location.transpose())
 9660                    .collect::<Result<_>>()
 9661                    .context("location tasks")?;
 9662
 9663                let Some(workspace) = workspace else {
 9664                    return Ok(Navigated::No);
 9665                };
 9666                let opened = workspace
 9667                    .update(&mut cx, |workspace, cx| {
 9668                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9669                    })
 9670                    .ok();
 9671
 9672                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9673            })
 9674        } else {
 9675            Task::ready(Ok(Navigated::No))
 9676        }
 9677    }
 9678
 9679    fn compute_target_location(
 9680        &self,
 9681        lsp_location: lsp::Location,
 9682        server_id: LanguageServerId,
 9683        cx: &mut ViewContext<Self>,
 9684    ) -> Task<anyhow::Result<Option<Location>>> {
 9685        let Some(project) = self.project.clone() else {
 9686            return Task::ready(Ok(None));
 9687        };
 9688
 9689        cx.spawn(move |editor, mut cx| async move {
 9690            let location_task = editor.update(&mut cx, |_, cx| {
 9691                project.update(cx, |project, cx| {
 9692                    let language_server_name = project
 9693                        .language_server_statuses(cx)
 9694                        .find(|(id, _)| server_id == *id)
 9695                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9696                    language_server_name.map(|language_server_name| {
 9697                        project.open_local_buffer_via_lsp(
 9698                            lsp_location.uri.clone(),
 9699                            server_id,
 9700                            language_server_name,
 9701                            cx,
 9702                        )
 9703                    })
 9704                })
 9705            })?;
 9706            let location = match location_task {
 9707                Some(task) => Some({
 9708                    let target_buffer_handle = task.await.context("open local buffer")?;
 9709                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9710                        let target_start = target_buffer
 9711                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9712                        let target_end = target_buffer
 9713                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9714                        target_buffer.anchor_after(target_start)
 9715                            ..target_buffer.anchor_before(target_end)
 9716                    })?;
 9717                    Location {
 9718                        buffer: target_buffer_handle,
 9719                        range,
 9720                    }
 9721                }),
 9722                None => None,
 9723            };
 9724            Ok(location)
 9725        })
 9726    }
 9727
 9728    pub fn find_all_references(
 9729        &mut self,
 9730        _: &FindAllReferences,
 9731        cx: &mut ViewContext<Self>,
 9732    ) -> Option<Task<Result<Navigated>>> {
 9733        let selection = self.selections.newest::<usize>(cx);
 9734        let multi_buffer = self.buffer.read(cx);
 9735        let head = selection.head();
 9736
 9737        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9738        let head_anchor = multi_buffer_snapshot.anchor_at(
 9739            head,
 9740            if head < selection.tail() {
 9741                Bias::Right
 9742            } else {
 9743                Bias::Left
 9744            },
 9745        );
 9746
 9747        match self
 9748            .find_all_references_task_sources
 9749            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9750        {
 9751            Ok(_) => {
 9752                log::info!(
 9753                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9754                );
 9755                return None;
 9756            }
 9757            Err(i) => {
 9758                self.find_all_references_task_sources.insert(i, head_anchor);
 9759            }
 9760        }
 9761
 9762        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9763        let workspace = self.workspace()?;
 9764        let project = workspace.read(cx).project().clone();
 9765        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9766        Some(cx.spawn(|editor, mut cx| async move {
 9767            let _cleanup = defer({
 9768                let mut cx = cx.clone();
 9769                move || {
 9770                    let _ = editor.update(&mut cx, |editor, _| {
 9771                        if let Ok(i) =
 9772                            editor
 9773                                .find_all_references_task_sources
 9774                                .binary_search_by(|anchor| {
 9775                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9776                                })
 9777                        {
 9778                            editor.find_all_references_task_sources.remove(i);
 9779                        }
 9780                    });
 9781                }
 9782            });
 9783
 9784            let locations = references.await?;
 9785            if locations.is_empty() {
 9786                return anyhow::Ok(Navigated::No);
 9787            }
 9788
 9789            workspace.update(&mut cx, |workspace, cx| {
 9790                let title = locations
 9791                    .first()
 9792                    .as_ref()
 9793                    .map(|location| {
 9794                        let buffer = location.buffer.read(cx);
 9795                        format!(
 9796                            "References to `{}`",
 9797                            buffer
 9798                                .text_for_range(location.range.clone())
 9799                                .collect::<String>()
 9800                        )
 9801                    })
 9802                    .unwrap();
 9803                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9804                Navigated::Yes
 9805            })
 9806        }))
 9807    }
 9808
 9809    /// Opens a multibuffer with the given project locations in it
 9810    pub fn open_locations_in_multibuffer(
 9811        workspace: &mut Workspace,
 9812        mut locations: Vec<Location>,
 9813        title: String,
 9814        split: bool,
 9815        cx: &mut ViewContext<Workspace>,
 9816    ) {
 9817        // If there are multiple definitions, open them in a multibuffer
 9818        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9819        let mut locations = locations.into_iter().peekable();
 9820        let mut ranges_to_highlight = Vec::new();
 9821        let capability = workspace.project().read(cx).capability();
 9822
 9823        let excerpt_buffer = cx.new_model(|cx| {
 9824            let mut multibuffer = MultiBuffer::new(capability);
 9825            while let Some(location) = locations.next() {
 9826                let buffer = location.buffer.read(cx);
 9827                let mut ranges_for_buffer = Vec::new();
 9828                let range = location.range.to_offset(buffer);
 9829                ranges_for_buffer.push(range.clone());
 9830
 9831                while let Some(next_location) = locations.peek() {
 9832                    if next_location.buffer == location.buffer {
 9833                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9834                        locations.next();
 9835                    } else {
 9836                        break;
 9837                    }
 9838                }
 9839
 9840                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9841                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9842                    location.buffer.clone(),
 9843                    ranges_for_buffer,
 9844                    DEFAULT_MULTIBUFFER_CONTEXT,
 9845                    cx,
 9846                ))
 9847            }
 9848
 9849            multibuffer.with_title(title)
 9850        });
 9851
 9852        let editor = cx.new_view(|cx| {
 9853            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9854        });
 9855        editor.update(cx, |editor, cx| {
 9856            if let Some(first_range) = ranges_to_highlight.first() {
 9857                editor.change_selections(None, cx, |selections| {
 9858                    selections.clear_disjoint();
 9859                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9860                });
 9861            }
 9862            editor.highlight_background::<Self>(
 9863                &ranges_to_highlight,
 9864                |theme| theme.editor_highlighted_line_background,
 9865                cx,
 9866            );
 9867            editor.register_buffers_with_language_servers(cx);
 9868        });
 9869
 9870        let item = Box::new(editor);
 9871        let item_id = item.item_id();
 9872
 9873        if split {
 9874            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9875        } else {
 9876            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9877                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9878                    pane.close_current_preview_item(cx)
 9879                } else {
 9880                    None
 9881                }
 9882            });
 9883            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9884        }
 9885        workspace.active_pane().update(cx, |pane, cx| {
 9886            pane.set_preview_item_id(Some(item_id), cx);
 9887        });
 9888    }
 9889
 9890    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9891        use language::ToOffset as _;
 9892
 9893        let provider = self.semantics_provider.clone()?;
 9894        let selection = self.selections.newest_anchor().clone();
 9895        let (cursor_buffer, cursor_buffer_position) = self
 9896            .buffer
 9897            .read(cx)
 9898            .text_anchor_for_position(selection.head(), cx)?;
 9899        let (tail_buffer, cursor_buffer_position_end) = self
 9900            .buffer
 9901            .read(cx)
 9902            .text_anchor_for_position(selection.tail(), cx)?;
 9903        if tail_buffer != cursor_buffer {
 9904            return None;
 9905        }
 9906
 9907        let snapshot = cursor_buffer.read(cx).snapshot();
 9908        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9909        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9910        let prepare_rename = provider
 9911            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9912            .unwrap_or_else(|| Task::ready(Ok(None)));
 9913        drop(snapshot);
 9914
 9915        Some(cx.spawn(|this, mut cx| async move {
 9916            let rename_range = if let Some(range) = prepare_rename.await? {
 9917                Some(range)
 9918            } else {
 9919                this.update(&mut cx, |this, cx| {
 9920                    let buffer = this.buffer.read(cx).snapshot(cx);
 9921                    let mut buffer_highlights = this
 9922                        .document_highlights_for_position(selection.head(), &buffer)
 9923                        .filter(|highlight| {
 9924                            highlight.start.excerpt_id == selection.head().excerpt_id
 9925                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9926                        });
 9927                    buffer_highlights
 9928                        .next()
 9929                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9930                })?
 9931            };
 9932            if let Some(rename_range) = rename_range {
 9933                this.update(&mut cx, |this, cx| {
 9934                    let snapshot = cursor_buffer.read(cx).snapshot();
 9935                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9936                    let cursor_offset_in_rename_range =
 9937                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9938                    let cursor_offset_in_rename_range_end =
 9939                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9940
 9941                    this.take_rename(false, cx);
 9942                    let buffer = this.buffer.read(cx).read(cx);
 9943                    let cursor_offset = selection.head().to_offset(&buffer);
 9944                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9945                    let rename_end = rename_start + rename_buffer_range.len();
 9946                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9947                    let mut old_highlight_id = None;
 9948                    let old_name: Arc<str> = buffer
 9949                        .chunks(rename_start..rename_end, true)
 9950                        .map(|chunk| {
 9951                            if old_highlight_id.is_none() {
 9952                                old_highlight_id = chunk.syntax_highlight_id;
 9953                            }
 9954                            chunk.text
 9955                        })
 9956                        .collect::<String>()
 9957                        .into();
 9958
 9959                    drop(buffer);
 9960
 9961                    // Position the selection in the rename editor so that it matches the current selection.
 9962                    this.show_local_selections = false;
 9963                    let rename_editor = cx.new_view(|cx| {
 9964                        let mut editor = Editor::single_line(cx);
 9965                        editor.buffer.update(cx, |buffer, cx| {
 9966                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9967                        });
 9968                        let rename_selection_range = match cursor_offset_in_rename_range
 9969                            .cmp(&cursor_offset_in_rename_range_end)
 9970                        {
 9971                            Ordering::Equal => {
 9972                                editor.select_all(&SelectAll, cx);
 9973                                return editor;
 9974                            }
 9975                            Ordering::Less => {
 9976                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9977                            }
 9978                            Ordering::Greater => {
 9979                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9980                            }
 9981                        };
 9982                        if rename_selection_range.end > old_name.len() {
 9983                            editor.select_all(&SelectAll, cx);
 9984                        } else {
 9985                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9986                                s.select_ranges([rename_selection_range]);
 9987                            });
 9988                        }
 9989                        editor
 9990                    });
 9991                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
 9992                        if e == &EditorEvent::Focused {
 9993                            cx.emit(EditorEvent::FocusedIn)
 9994                        }
 9995                    })
 9996                    .detach();
 9997
 9998                    let write_highlights =
 9999                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10000                    let read_highlights =
10001                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10002                    let ranges = write_highlights
10003                        .iter()
10004                        .flat_map(|(_, ranges)| ranges.iter())
10005                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10006                        .cloned()
10007                        .collect();
10008
10009                    this.highlight_text::<Rename>(
10010                        ranges,
10011                        HighlightStyle {
10012                            fade_out: Some(0.6),
10013                            ..Default::default()
10014                        },
10015                        cx,
10016                    );
10017                    let rename_focus_handle = rename_editor.focus_handle(cx);
10018                    cx.focus(&rename_focus_handle);
10019                    let block_id = this.insert_blocks(
10020                        [BlockProperties {
10021                            style: BlockStyle::Flex,
10022                            placement: BlockPlacement::Below(range.start),
10023                            height: 1,
10024                            render: Arc::new({
10025                                let rename_editor = rename_editor.clone();
10026                                move |cx: &mut BlockContext| {
10027                                    let mut text_style = cx.editor_style.text.clone();
10028                                    if let Some(highlight_style) = old_highlight_id
10029                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10030                                    {
10031                                        text_style = text_style.highlight(highlight_style);
10032                                    }
10033                                    div()
10034                                        .block_mouse_down()
10035                                        .pl(cx.anchor_x)
10036                                        .child(EditorElement::new(
10037                                            &rename_editor,
10038                                            EditorStyle {
10039                                                background: cx.theme().system().transparent,
10040                                                local_player: cx.editor_style.local_player,
10041                                                text: text_style,
10042                                                scrollbar_width: cx.editor_style.scrollbar_width,
10043                                                syntax: cx.editor_style.syntax.clone(),
10044                                                status: cx.editor_style.status.clone(),
10045                                                inlay_hints_style: HighlightStyle {
10046                                                    font_weight: Some(FontWeight::BOLD),
10047                                                    ..make_inlay_hints_style(cx)
10048                                                },
10049                                                inline_completion_styles: make_suggestion_styles(
10050                                                    cx,
10051                                                ),
10052                                                ..EditorStyle::default()
10053                                            },
10054                                        ))
10055                                        .into_any_element()
10056                                }
10057                            }),
10058                            priority: 0,
10059                        }],
10060                        Some(Autoscroll::fit()),
10061                        cx,
10062                    )[0];
10063                    this.pending_rename = Some(RenameState {
10064                        range,
10065                        old_name,
10066                        editor: rename_editor,
10067                        block_id,
10068                    });
10069                })?;
10070            }
10071
10072            Ok(())
10073        }))
10074    }
10075
10076    pub fn confirm_rename(
10077        &mut self,
10078        _: &ConfirmRename,
10079        cx: &mut ViewContext<Self>,
10080    ) -> Option<Task<Result<()>>> {
10081        let rename = self.take_rename(false, cx)?;
10082        let workspace = self.workspace()?.downgrade();
10083        let (buffer, start) = self
10084            .buffer
10085            .read(cx)
10086            .text_anchor_for_position(rename.range.start, cx)?;
10087        let (end_buffer, _) = self
10088            .buffer
10089            .read(cx)
10090            .text_anchor_for_position(rename.range.end, cx)?;
10091        if buffer != end_buffer {
10092            return None;
10093        }
10094
10095        let old_name = rename.old_name;
10096        let new_name = rename.editor.read(cx).text(cx);
10097
10098        let rename = self.semantics_provider.as_ref()?.perform_rename(
10099            &buffer,
10100            start,
10101            new_name.clone(),
10102            cx,
10103        )?;
10104
10105        Some(cx.spawn(|editor, mut cx| async move {
10106            let project_transaction = rename.await?;
10107            Self::open_project_transaction(
10108                &editor,
10109                workspace,
10110                project_transaction,
10111                format!("Rename: {}{}", old_name, new_name),
10112                cx.clone(),
10113            )
10114            .await?;
10115
10116            editor.update(&mut cx, |editor, cx| {
10117                editor.refresh_document_highlights(cx);
10118            })?;
10119            Ok(())
10120        }))
10121    }
10122
10123    fn take_rename(
10124        &mut self,
10125        moving_cursor: bool,
10126        cx: &mut ViewContext<Self>,
10127    ) -> Option<RenameState> {
10128        let rename = self.pending_rename.take()?;
10129        if rename.editor.focus_handle(cx).is_focused(cx) {
10130            cx.focus(&self.focus_handle);
10131        }
10132
10133        self.remove_blocks(
10134            [rename.block_id].into_iter().collect(),
10135            Some(Autoscroll::fit()),
10136            cx,
10137        );
10138        self.clear_highlights::<Rename>(cx);
10139        self.show_local_selections = true;
10140
10141        if moving_cursor {
10142            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10143                editor.selections.newest::<usize>(cx).head()
10144            });
10145
10146            // Update the selection to match the position of the selection inside
10147            // the rename editor.
10148            let snapshot = self.buffer.read(cx).read(cx);
10149            let rename_range = rename.range.to_offset(&snapshot);
10150            let cursor_in_editor = snapshot
10151                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10152                .min(rename_range.end);
10153            drop(snapshot);
10154
10155            self.change_selections(None, cx, |s| {
10156                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10157            });
10158        } else {
10159            self.refresh_document_highlights(cx);
10160        }
10161
10162        Some(rename)
10163    }
10164
10165    pub fn pending_rename(&self) -> Option<&RenameState> {
10166        self.pending_rename.as_ref()
10167    }
10168
10169    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10170        let project = match &self.project {
10171            Some(project) => project.clone(),
10172            None => return None,
10173        };
10174
10175        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10176    }
10177
10178    fn format_selections(
10179        &mut self,
10180        _: &FormatSelections,
10181        cx: &mut ViewContext<Self>,
10182    ) -> Option<Task<Result<()>>> {
10183        let project = match &self.project {
10184            Some(project) => project.clone(),
10185            None => return None,
10186        };
10187
10188        let selections = self
10189            .selections
10190            .all_adjusted(cx)
10191            .into_iter()
10192            .filter(|s| !s.is_empty())
10193            .collect_vec();
10194
10195        Some(self.perform_format(
10196            project,
10197            FormatTrigger::Manual,
10198            FormatTarget::Ranges(selections),
10199            cx,
10200        ))
10201    }
10202
10203    fn perform_format(
10204        &mut self,
10205        project: Model<Project>,
10206        trigger: FormatTrigger,
10207        target: FormatTarget,
10208        cx: &mut ViewContext<Self>,
10209    ) -> Task<Result<()>> {
10210        let buffer = self.buffer().clone();
10211        let mut buffers = buffer.read(cx).all_buffers();
10212        if trigger == FormatTrigger::Save {
10213            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10214        }
10215
10216        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10217        let format = project.update(cx, |project, cx| {
10218            project.format(buffers, true, trigger, target, cx)
10219        });
10220
10221        cx.spawn(|_, mut cx| async move {
10222            let transaction = futures::select_biased! {
10223                () = timeout => {
10224                    log::warn!("timed out waiting for formatting");
10225                    None
10226                }
10227                transaction = format.log_err().fuse() => transaction,
10228            };
10229
10230            buffer
10231                .update(&mut cx, |buffer, cx| {
10232                    if let Some(transaction) = transaction {
10233                        if !buffer.is_singleton() {
10234                            buffer.push_transaction(&transaction.0, cx);
10235                        }
10236                    }
10237
10238                    cx.notify();
10239                })
10240                .ok();
10241
10242            Ok(())
10243        })
10244    }
10245
10246    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10247        if let Some(project) = self.project.clone() {
10248            self.buffer.update(cx, |multi_buffer, cx| {
10249                project.update(cx, |project, cx| {
10250                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10251                });
10252            })
10253        }
10254    }
10255
10256    fn cancel_language_server_work(
10257        &mut self,
10258        _: &actions::CancelLanguageServerWork,
10259        cx: &mut ViewContext<Self>,
10260    ) {
10261        if let Some(project) = self.project.clone() {
10262            self.buffer.update(cx, |multi_buffer, cx| {
10263                project.update(cx, |project, cx| {
10264                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10265                });
10266            })
10267        }
10268    }
10269
10270    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10271        cx.show_character_palette();
10272    }
10273
10274    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10275        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10276            let buffer = self.buffer.read(cx).snapshot(cx);
10277            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10278            let is_valid = buffer
10279                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10280                .any(|entry| {
10281                    entry.diagnostic.is_primary
10282                        && !entry.range.is_empty()
10283                        && entry.range.start == primary_range_start
10284                        && entry.diagnostic.message == active_diagnostics.primary_message
10285                });
10286
10287            if is_valid != active_diagnostics.is_valid {
10288                active_diagnostics.is_valid = is_valid;
10289                let mut new_styles = HashMap::default();
10290                for (block_id, diagnostic) in &active_diagnostics.blocks {
10291                    new_styles.insert(
10292                        *block_id,
10293                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10294                    );
10295                }
10296                self.display_map.update(cx, |display_map, _cx| {
10297                    display_map.replace_blocks(new_styles)
10298                });
10299            }
10300        }
10301    }
10302
10303    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10304        self.dismiss_diagnostics(cx);
10305        let snapshot = self.snapshot(cx);
10306        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10307            let buffer = self.buffer.read(cx).snapshot(cx);
10308
10309            let mut primary_range = None;
10310            let mut primary_message = None;
10311            let mut group_end = Point::zero();
10312            let diagnostic_group = buffer
10313                .diagnostic_group::<MultiBufferPoint>(group_id)
10314                .filter_map(|entry| {
10315                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10316                        && (entry.range.start.row == entry.range.end.row
10317                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10318                    {
10319                        return None;
10320                    }
10321                    if entry.range.end > group_end {
10322                        group_end = entry.range.end;
10323                    }
10324                    if entry.diagnostic.is_primary {
10325                        primary_range = Some(entry.range.clone());
10326                        primary_message = Some(entry.diagnostic.message.clone());
10327                    }
10328                    Some(entry)
10329                })
10330                .collect::<Vec<_>>();
10331            let primary_range = primary_range?;
10332            let primary_message = primary_message?;
10333            let primary_range =
10334                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10335
10336            let blocks = display_map
10337                .insert_blocks(
10338                    diagnostic_group.iter().map(|entry| {
10339                        let diagnostic = entry.diagnostic.clone();
10340                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10341                        BlockProperties {
10342                            style: BlockStyle::Fixed,
10343                            placement: BlockPlacement::Below(
10344                                buffer.anchor_after(entry.range.start),
10345                            ),
10346                            height: message_height,
10347                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10348                            priority: 0,
10349                        }
10350                    }),
10351                    cx,
10352                )
10353                .into_iter()
10354                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10355                .collect();
10356
10357            Some(ActiveDiagnosticGroup {
10358                primary_range,
10359                primary_message,
10360                group_id,
10361                blocks,
10362                is_valid: true,
10363            })
10364        });
10365        self.active_diagnostics.is_some()
10366    }
10367
10368    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10369        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10370            self.display_map.update(cx, |display_map, cx| {
10371                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10372            });
10373            cx.notify();
10374        }
10375    }
10376
10377    pub fn set_selections_from_remote(
10378        &mut self,
10379        selections: Vec<Selection<Anchor>>,
10380        pending_selection: Option<Selection<Anchor>>,
10381        cx: &mut ViewContext<Self>,
10382    ) {
10383        let old_cursor_position = self.selections.newest_anchor().head();
10384        self.selections.change_with(cx, |s| {
10385            s.select_anchors(selections);
10386            if let Some(pending_selection) = pending_selection {
10387                s.set_pending(pending_selection, SelectMode::Character);
10388            } else {
10389                s.clear_pending();
10390            }
10391        });
10392        self.selections_did_change(false, &old_cursor_position, true, cx);
10393    }
10394
10395    fn push_to_selection_history(&mut self) {
10396        self.selection_history.push(SelectionHistoryEntry {
10397            selections: self.selections.disjoint_anchors(),
10398            select_next_state: self.select_next_state.clone(),
10399            select_prev_state: self.select_prev_state.clone(),
10400            add_selections_state: self.add_selections_state.clone(),
10401        });
10402    }
10403
10404    pub fn transact(
10405        &mut self,
10406        cx: &mut ViewContext<Self>,
10407        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10408    ) -> Option<TransactionId> {
10409        self.start_transaction_at(Instant::now(), cx);
10410        update(self, cx);
10411        self.end_transaction_at(Instant::now(), cx)
10412    }
10413
10414    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10415        self.end_selection(cx);
10416        if let Some(tx_id) = self
10417            .buffer
10418            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10419        {
10420            self.selection_history
10421                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10422            cx.emit(EditorEvent::TransactionBegun {
10423                transaction_id: tx_id,
10424            })
10425        }
10426    }
10427
10428    pub fn end_transaction_at(
10429        &mut self,
10430        now: Instant,
10431        cx: &mut ViewContext<Self>,
10432    ) -> Option<TransactionId> {
10433        if let Some(transaction_id) = self
10434            .buffer
10435            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10436        {
10437            if let Some((_, end_selections)) =
10438                self.selection_history.transaction_mut(transaction_id)
10439            {
10440                *end_selections = Some(self.selections.disjoint_anchors());
10441            } else {
10442                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10443            }
10444
10445            cx.emit(EditorEvent::Edited { transaction_id });
10446            Some(transaction_id)
10447        } else {
10448            None
10449        }
10450    }
10451
10452    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10453        if self.is_singleton(cx) {
10454            let selection = self.selections.newest::<Point>(cx);
10455
10456            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10457            let range = if selection.is_empty() {
10458                let point = selection.head().to_display_point(&display_map);
10459                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10460                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10461                    .to_point(&display_map);
10462                start..end
10463            } else {
10464                selection.range()
10465            };
10466            if display_map.folds_in_range(range).next().is_some() {
10467                self.unfold_lines(&Default::default(), cx)
10468            } else {
10469                self.fold(&Default::default(), cx)
10470            }
10471        } else {
10472            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10473            let mut toggled_buffers = HashSet::default();
10474            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10475                self.selections
10476                    .disjoint_anchors()
10477                    .into_iter()
10478                    .map(|selection| selection.range()),
10479            ) {
10480                let buffer_id = buffer_snapshot.remote_id();
10481                if toggled_buffers.insert(buffer_id) {
10482                    if self.buffer_folded(buffer_id, cx) {
10483                        self.unfold_buffer(buffer_id, cx);
10484                    } else {
10485                        self.fold_buffer(buffer_id, cx);
10486                    }
10487                }
10488            }
10489        }
10490    }
10491
10492    pub fn toggle_fold_recursive(
10493        &mut self,
10494        _: &actions::ToggleFoldRecursive,
10495        cx: &mut ViewContext<Self>,
10496    ) {
10497        let selection = self.selections.newest::<Point>(cx);
10498
10499        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10500        let range = if selection.is_empty() {
10501            let point = selection.head().to_display_point(&display_map);
10502            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10503            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10504                .to_point(&display_map);
10505            start..end
10506        } else {
10507            selection.range()
10508        };
10509        if display_map.folds_in_range(range).next().is_some() {
10510            self.unfold_recursive(&Default::default(), cx)
10511        } else {
10512            self.fold_recursive(&Default::default(), cx)
10513        }
10514    }
10515
10516    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10517        if self.is_singleton(cx) {
10518            let mut to_fold = Vec::new();
10519            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10520            let selections = self.selections.all_adjusted(cx);
10521
10522            for selection in selections {
10523                let range = selection.range().sorted();
10524                let buffer_start_row = range.start.row;
10525
10526                if range.start.row != range.end.row {
10527                    let mut found = false;
10528                    let mut row = range.start.row;
10529                    while row <= range.end.row {
10530                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10531                        {
10532                            found = true;
10533                            row = crease.range().end.row + 1;
10534                            to_fold.push(crease);
10535                        } else {
10536                            row += 1
10537                        }
10538                    }
10539                    if found {
10540                        continue;
10541                    }
10542                }
10543
10544                for row in (0..=range.start.row).rev() {
10545                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10546                        if crease.range().end.row >= buffer_start_row {
10547                            to_fold.push(crease);
10548                            if row <= range.start.row {
10549                                break;
10550                            }
10551                        }
10552                    }
10553                }
10554            }
10555
10556            self.fold_creases(to_fold, true, cx);
10557        } else {
10558            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10559            let mut folded_buffers = HashSet::default();
10560            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10561                self.selections
10562                    .disjoint_anchors()
10563                    .into_iter()
10564                    .map(|selection| selection.range()),
10565            ) {
10566                let buffer_id = buffer_snapshot.remote_id();
10567                if folded_buffers.insert(buffer_id) {
10568                    self.fold_buffer(buffer_id, cx);
10569                }
10570            }
10571        }
10572    }
10573
10574    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10575        if !self.buffer.read(cx).is_singleton() {
10576            return;
10577        }
10578
10579        let fold_at_level = fold_at.level;
10580        let snapshot = self.buffer.read(cx).snapshot(cx);
10581        let mut to_fold = Vec::new();
10582        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10583
10584        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10585            while start_row < end_row {
10586                match self
10587                    .snapshot(cx)
10588                    .crease_for_buffer_row(MultiBufferRow(start_row))
10589                {
10590                    Some(crease) => {
10591                        let nested_start_row = crease.range().start.row + 1;
10592                        let nested_end_row = crease.range().end.row;
10593
10594                        if current_level < fold_at_level {
10595                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10596                        } else if current_level == fold_at_level {
10597                            to_fold.push(crease);
10598                        }
10599
10600                        start_row = nested_end_row + 1;
10601                    }
10602                    None => start_row += 1,
10603                }
10604            }
10605        }
10606
10607        self.fold_creases(to_fold, true, cx);
10608    }
10609
10610    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10611        if self.buffer.read(cx).is_singleton() {
10612            let mut fold_ranges = Vec::new();
10613            let snapshot = self.buffer.read(cx).snapshot(cx);
10614
10615            for row in 0..snapshot.max_row().0 {
10616                if let Some(foldable_range) =
10617                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10618                {
10619                    fold_ranges.push(foldable_range);
10620                }
10621            }
10622
10623            self.fold_creases(fold_ranges, true, cx);
10624        } else {
10625            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10626                editor
10627                    .update(&mut cx, |editor, cx| {
10628                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10629                            editor.fold_buffer(buffer_id, cx);
10630                        }
10631                    })
10632                    .ok();
10633            });
10634        }
10635    }
10636
10637    pub fn fold_function_bodies(
10638        &mut self,
10639        _: &actions::FoldFunctionBodies,
10640        cx: &mut ViewContext<Self>,
10641    ) {
10642        let snapshot = self.buffer.read(cx).snapshot(cx);
10643        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10644            return;
10645        };
10646        let creases = buffer
10647            .function_body_fold_ranges(0..buffer.len())
10648            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10649            .collect();
10650
10651        self.fold_creases(creases, true, cx);
10652    }
10653
10654    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10655        let mut to_fold = Vec::new();
10656        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10657        let selections = self.selections.all_adjusted(cx);
10658
10659        for selection in selections {
10660            let range = selection.range().sorted();
10661            let buffer_start_row = range.start.row;
10662
10663            if range.start.row != range.end.row {
10664                let mut found = false;
10665                for row in range.start.row..=range.end.row {
10666                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10667                        found = true;
10668                        to_fold.push(crease);
10669                    }
10670                }
10671                if found {
10672                    continue;
10673                }
10674            }
10675
10676            for row in (0..=range.start.row).rev() {
10677                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10678                    if crease.range().end.row >= buffer_start_row {
10679                        to_fold.push(crease);
10680                    } else {
10681                        break;
10682                    }
10683                }
10684            }
10685        }
10686
10687        self.fold_creases(to_fold, true, cx);
10688    }
10689
10690    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10691        let buffer_row = fold_at.buffer_row;
10692        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10693
10694        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10695            let autoscroll = self
10696                .selections
10697                .all::<Point>(cx)
10698                .iter()
10699                .any(|selection| crease.range().overlaps(&selection.range()));
10700
10701            self.fold_creases(vec![crease], autoscroll, cx);
10702        }
10703    }
10704
10705    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10706        if self.is_singleton(cx) {
10707            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10708            let buffer = &display_map.buffer_snapshot;
10709            let selections = self.selections.all::<Point>(cx);
10710            let ranges = selections
10711                .iter()
10712                .map(|s| {
10713                    let range = s.display_range(&display_map).sorted();
10714                    let mut start = range.start.to_point(&display_map);
10715                    let mut end = range.end.to_point(&display_map);
10716                    start.column = 0;
10717                    end.column = buffer.line_len(MultiBufferRow(end.row));
10718                    start..end
10719                })
10720                .collect::<Vec<_>>();
10721
10722            self.unfold_ranges(&ranges, true, true, cx);
10723        } else {
10724            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10725            let mut unfolded_buffers = HashSet::default();
10726            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10727                self.selections
10728                    .disjoint_anchors()
10729                    .into_iter()
10730                    .map(|selection| selection.range()),
10731            ) {
10732                let buffer_id = buffer_snapshot.remote_id();
10733                if unfolded_buffers.insert(buffer_id) {
10734                    self.unfold_buffer(buffer_id, cx);
10735                }
10736            }
10737        }
10738    }
10739
10740    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10741        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10742        let selections = self.selections.all::<Point>(cx);
10743        let ranges = selections
10744            .iter()
10745            .map(|s| {
10746                let mut range = s.display_range(&display_map).sorted();
10747                *range.start.column_mut() = 0;
10748                *range.end.column_mut() = display_map.line_len(range.end.row());
10749                let start = range.start.to_point(&display_map);
10750                let end = range.end.to_point(&display_map);
10751                start..end
10752            })
10753            .collect::<Vec<_>>();
10754
10755        self.unfold_ranges(&ranges, true, true, cx);
10756    }
10757
10758    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10759        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10760
10761        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10762            ..Point::new(
10763                unfold_at.buffer_row.0,
10764                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10765            );
10766
10767        let autoscroll = self
10768            .selections
10769            .all::<Point>(cx)
10770            .iter()
10771            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10772
10773        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10774    }
10775
10776    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10777        if self.buffer.read(cx).is_singleton() {
10778            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10779            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10780        } else {
10781            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10782                editor
10783                    .update(&mut cx, |editor, cx| {
10784                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10785                            editor.unfold_buffer(buffer_id, cx);
10786                        }
10787                    })
10788                    .ok();
10789            });
10790        }
10791    }
10792
10793    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10794        let selections = self.selections.all::<Point>(cx);
10795        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10796        let line_mode = self.selections.line_mode;
10797        let ranges = selections
10798            .into_iter()
10799            .map(|s| {
10800                if line_mode {
10801                    let start = Point::new(s.start.row, 0);
10802                    let end = Point::new(
10803                        s.end.row,
10804                        display_map
10805                            .buffer_snapshot
10806                            .line_len(MultiBufferRow(s.end.row)),
10807                    );
10808                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10809                } else {
10810                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10811                }
10812            })
10813            .collect::<Vec<_>>();
10814        self.fold_creases(ranges, true, cx);
10815    }
10816
10817    pub fn fold_creases<T: ToOffset + Clone>(
10818        &mut self,
10819        creases: Vec<Crease<T>>,
10820        auto_scroll: bool,
10821        cx: &mut ViewContext<Self>,
10822    ) {
10823        if creases.is_empty() {
10824            return;
10825        }
10826
10827        let mut buffers_affected = HashSet::default();
10828        let multi_buffer = self.buffer().read(cx);
10829        for crease in &creases {
10830            if let Some((_, buffer, _)) =
10831                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10832            {
10833                buffers_affected.insert(buffer.read(cx).remote_id());
10834            };
10835        }
10836
10837        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10838
10839        if auto_scroll {
10840            self.request_autoscroll(Autoscroll::fit(), cx);
10841        }
10842
10843        for buffer_id in buffers_affected {
10844            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10845        }
10846
10847        cx.notify();
10848
10849        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10850            // Clear diagnostics block when folding a range that contains it.
10851            let snapshot = self.snapshot(cx);
10852            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10853                drop(snapshot);
10854                self.active_diagnostics = Some(active_diagnostics);
10855                self.dismiss_diagnostics(cx);
10856            } else {
10857                self.active_diagnostics = Some(active_diagnostics);
10858            }
10859        }
10860
10861        self.scrollbar_marker_state.dirty = true;
10862    }
10863
10864    /// Removes any folds whose ranges intersect any of the given ranges.
10865    pub fn unfold_ranges<T: ToOffset + Clone>(
10866        &mut self,
10867        ranges: &[Range<T>],
10868        inclusive: bool,
10869        auto_scroll: bool,
10870        cx: &mut ViewContext<Self>,
10871    ) {
10872        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10873            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10874        });
10875    }
10876
10877    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10878        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10879            return;
10880        }
10881        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10882            return;
10883        };
10884        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10885        self.display_map
10886            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10887        cx.emit(EditorEvent::BufferFoldToggled {
10888            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10889            folded: true,
10890        });
10891        cx.notify();
10892    }
10893
10894    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10895        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10896            return;
10897        }
10898        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10899            return;
10900        };
10901        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10902        self.display_map.update(cx, |display_map, cx| {
10903            display_map.unfold_buffer(buffer_id, cx);
10904        });
10905        cx.emit(EditorEvent::BufferFoldToggled {
10906            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10907            folded: false,
10908        });
10909        cx.notify();
10910    }
10911
10912    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10913        self.display_map.read(cx).buffer_folded(buffer)
10914    }
10915
10916    /// Removes any folds with the given ranges.
10917    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10918        &mut self,
10919        ranges: &[Range<T>],
10920        type_id: TypeId,
10921        auto_scroll: bool,
10922        cx: &mut ViewContext<Self>,
10923    ) {
10924        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10925            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10926        });
10927    }
10928
10929    fn remove_folds_with<T: ToOffset + Clone>(
10930        &mut self,
10931        ranges: &[Range<T>],
10932        auto_scroll: bool,
10933        cx: &mut ViewContext<Self>,
10934        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10935    ) {
10936        if ranges.is_empty() {
10937            return;
10938        }
10939
10940        let mut buffers_affected = HashSet::default();
10941        let multi_buffer = self.buffer().read(cx);
10942        for range in ranges {
10943            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10944                buffers_affected.insert(buffer.read(cx).remote_id());
10945            };
10946        }
10947
10948        self.display_map.update(cx, update);
10949
10950        if auto_scroll {
10951            self.request_autoscroll(Autoscroll::fit(), cx);
10952        }
10953
10954        for buffer_id in buffers_affected {
10955            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10956        }
10957
10958        cx.notify();
10959        self.scrollbar_marker_state.dirty = true;
10960        self.active_indent_guides_state.dirty = true;
10961    }
10962
10963    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10964        self.display_map.read(cx).fold_placeholder.clone()
10965    }
10966
10967    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10968        if hovered != self.gutter_hovered {
10969            self.gutter_hovered = hovered;
10970            cx.notify();
10971        }
10972    }
10973
10974    pub fn insert_blocks(
10975        &mut self,
10976        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10977        autoscroll: Option<Autoscroll>,
10978        cx: &mut ViewContext<Self>,
10979    ) -> Vec<CustomBlockId> {
10980        let blocks = self
10981            .display_map
10982            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10983        if let Some(autoscroll) = autoscroll {
10984            self.request_autoscroll(autoscroll, cx);
10985        }
10986        cx.notify();
10987        blocks
10988    }
10989
10990    pub fn resize_blocks(
10991        &mut self,
10992        heights: HashMap<CustomBlockId, u32>,
10993        autoscroll: Option<Autoscroll>,
10994        cx: &mut ViewContext<Self>,
10995    ) {
10996        self.display_map
10997            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10998        if let Some(autoscroll) = autoscroll {
10999            self.request_autoscroll(autoscroll, cx);
11000        }
11001        cx.notify();
11002    }
11003
11004    pub fn replace_blocks(
11005        &mut self,
11006        renderers: HashMap<CustomBlockId, RenderBlock>,
11007        autoscroll: Option<Autoscroll>,
11008        cx: &mut ViewContext<Self>,
11009    ) {
11010        self.display_map
11011            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11012        if let Some(autoscroll) = autoscroll {
11013            self.request_autoscroll(autoscroll, cx);
11014        }
11015        cx.notify();
11016    }
11017
11018    pub fn remove_blocks(
11019        &mut self,
11020        block_ids: HashSet<CustomBlockId>,
11021        autoscroll: Option<Autoscroll>,
11022        cx: &mut ViewContext<Self>,
11023    ) {
11024        self.display_map.update(cx, |display_map, cx| {
11025            display_map.remove_blocks(block_ids, cx)
11026        });
11027        if let Some(autoscroll) = autoscroll {
11028            self.request_autoscroll(autoscroll, cx);
11029        }
11030        cx.notify();
11031    }
11032
11033    pub fn row_for_block(
11034        &self,
11035        block_id: CustomBlockId,
11036        cx: &mut ViewContext<Self>,
11037    ) -> Option<DisplayRow> {
11038        self.display_map
11039            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11040    }
11041
11042    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11043        self.focused_block = Some(focused_block);
11044    }
11045
11046    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11047        self.focused_block.take()
11048    }
11049
11050    pub fn insert_creases(
11051        &mut self,
11052        creases: impl IntoIterator<Item = Crease<Anchor>>,
11053        cx: &mut ViewContext<Self>,
11054    ) -> Vec<CreaseId> {
11055        self.display_map
11056            .update(cx, |map, cx| map.insert_creases(creases, cx))
11057    }
11058
11059    pub fn remove_creases(
11060        &mut self,
11061        ids: impl IntoIterator<Item = CreaseId>,
11062        cx: &mut ViewContext<Self>,
11063    ) {
11064        self.display_map
11065            .update(cx, |map, cx| map.remove_creases(ids, cx));
11066    }
11067
11068    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11069        self.display_map
11070            .update(cx, |map, cx| map.snapshot(cx))
11071            .longest_row()
11072    }
11073
11074    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11075        self.display_map
11076            .update(cx, |map, cx| map.snapshot(cx))
11077            .max_point()
11078    }
11079
11080    pub fn text(&self, cx: &AppContext) -> String {
11081        self.buffer.read(cx).read(cx).text()
11082    }
11083
11084    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11085        let text = self.text(cx);
11086        let text = text.trim();
11087
11088        if text.is_empty() {
11089            return None;
11090        }
11091
11092        Some(text.to_string())
11093    }
11094
11095    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11096        self.transact(cx, |this, cx| {
11097            this.buffer
11098                .read(cx)
11099                .as_singleton()
11100                .expect("you can only call set_text on editors for singleton buffers")
11101                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11102        });
11103    }
11104
11105    pub fn display_text(&self, cx: &mut AppContext) -> String {
11106        self.display_map
11107            .update(cx, |map, cx| map.snapshot(cx))
11108            .text()
11109    }
11110
11111    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11112        let mut wrap_guides = smallvec::smallvec![];
11113
11114        if self.show_wrap_guides == Some(false) {
11115            return wrap_guides;
11116        }
11117
11118        let settings = self.buffer.read(cx).settings_at(0, cx);
11119        if settings.show_wrap_guides {
11120            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11121                wrap_guides.push((soft_wrap as usize, true));
11122            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11123                wrap_guides.push((soft_wrap as usize, true));
11124            }
11125            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11126        }
11127
11128        wrap_guides
11129    }
11130
11131    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11132        let settings = self.buffer.read(cx).settings_at(0, cx);
11133        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11134        match mode {
11135            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11136                SoftWrap::None
11137            }
11138            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11139            language_settings::SoftWrap::PreferredLineLength => {
11140                SoftWrap::Column(settings.preferred_line_length)
11141            }
11142            language_settings::SoftWrap::Bounded => {
11143                SoftWrap::Bounded(settings.preferred_line_length)
11144            }
11145        }
11146    }
11147
11148    pub fn set_soft_wrap_mode(
11149        &mut self,
11150        mode: language_settings::SoftWrap,
11151        cx: &mut ViewContext<Self>,
11152    ) {
11153        self.soft_wrap_mode_override = Some(mode);
11154        cx.notify();
11155    }
11156
11157    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11158        self.text_style_refinement = Some(style);
11159    }
11160
11161    /// called by the Element so we know what style we were most recently rendered with.
11162    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11163        let rem_size = cx.rem_size();
11164        self.display_map.update(cx, |map, cx| {
11165            map.set_font(
11166                style.text.font(),
11167                style.text.font_size.to_pixels(rem_size),
11168                cx,
11169            )
11170        });
11171        self.style = Some(style);
11172    }
11173
11174    pub fn style(&self) -> Option<&EditorStyle> {
11175        self.style.as_ref()
11176    }
11177
11178    // Called by the element. This method is not designed to be called outside of the editor
11179    // element's layout code because it does not notify when rewrapping is computed synchronously.
11180    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11181        self.display_map
11182            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11183    }
11184
11185    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11186        if self.soft_wrap_mode_override.is_some() {
11187            self.soft_wrap_mode_override.take();
11188        } else {
11189            let soft_wrap = match self.soft_wrap_mode(cx) {
11190                SoftWrap::GitDiff => return,
11191                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11192                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11193                    language_settings::SoftWrap::None
11194                }
11195            };
11196            self.soft_wrap_mode_override = Some(soft_wrap);
11197        }
11198        cx.notify();
11199    }
11200
11201    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11202        let Some(workspace) = self.workspace() else {
11203            return;
11204        };
11205        let fs = workspace.read(cx).app_state().fs.clone();
11206        let current_show = TabBarSettings::get_global(cx).show;
11207        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11208            setting.show = Some(!current_show);
11209        });
11210    }
11211
11212    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11213        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11214            self.buffer
11215                .read(cx)
11216                .settings_at(0, cx)
11217                .indent_guides
11218                .enabled
11219        });
11220        self.show_indent_guides = Some(!currently_enabled);
11221        cx.notify();
11222    }
11223
11224    fn should_show_indent_guides(&self) -> Option<bool> {
11225        self.show_indent_guides
11226    }
11227
11228    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11229        let mut editor_settings = EditorSettings::get_global(cx).clone();
11230        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11231        EditorSettings::override_global(editor_settings, cx);
11232    }
11233
11234    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11235        self.use_relative_line_numbers
11236            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11237    }
11238
11239    pub fn toggle_relative_line_numbers(
11240        &mut self,
11241        _: &ToggleRelativeLineNumbers,
11242        cx: &mut ViewContext<Self>,
11243    ) {
11244        let is_relative = self.should_use_relative_line_numbers(cx);
11245        self.set_relative_line_number(Some(!is_relative), cx)
11246    }
11247
11248    pub fn set_relative_line_number(
11249        &mut self,
11250        is_relative: Option<bool>,
11251        cx: &mut ViewContext<Self>,
11252    ) {
11253        self.use_relative_line_numbers = is_relative;
11254        cx.notify();
11255    }
11256
11257    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11258        self.show_gutter = show_gutter;
11259        cx.notify();
11260    }
11261
11262    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11263        self.show_line_numbers = Some(show_line_numbers);
11264        cx.notify();
11265    }
11266
11267    pub fn set_show_git_diff_gutter(
11268        &mut self,
11269        show_git_diff_gutter: bool,
11270        cx: &mut ViewContext<Self>,
11271    ) {
11272        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11273        cx.notify();
11274    }
11275
11276    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11277        self.show_code_actions = Some(show_code_actions);
11278        cx.notify();
11279    }
11280
11281    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11282        self.show_runnables = Some(show_runnables);
11283        cx.notify();
11284    }
11285
11286    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11287        if self.display_map.read(cx).masked != masked {
11288            self.display_map.update(cx, |map, _| map.masked = masked);
11289        }
11290        cx.notify()
11291    }
11292
11293    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11294        self.show_wrap_guides = Some(show_wrap_guides);
11295        cx.notify();
11296    }
11297
11298    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11299        self.show_indent_guides = Some(show_indent_guides);
11300        cx.notify();
11301    }
11302
11303    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11304        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11305            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11306                if let Some(dir) = file.abs_path(cx).parent() {
11307                    return Some(dir.to_owned());
11308                }
11309            }
11310
11311            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11312                return Some(project_path.path.to_path_buf());
11313            }
11314        }
11315
11316        None
11317    }
11318
11319    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11320        self.active_excerpt(cx)?
11321            .1
11322            .read(cx)
11323            .file()
11324            .and_then(|f| f.as_local())
11325    }
11326
11327    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11328        if let Some(target) = self.target_file(cx) {
11329            cx.reveal_path(&target.abs_path(cx));
11330        }
11331    }
11332
11333    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11334        if let Some(file) = self.target_file(cx) {
11335            if let Some(path) = file.abs_path(cx).to_str() {
11336                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11337            }
11338        }
11339    }
11340
11341    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11342        if let Some(file) = self.target_file(cx) {
11343            if let Some(path) = file.path().to_str() {
11344                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11345            }
11346        }
11347    }
11348
11349    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11350        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11351
11352        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11353            self.start_git_blame(true, cx);
11354        }
11355
11356        cx.notify();
11357    }
11358
11359    pub fn toggle_git_blame_inline(
11360        &mut self,
11361        _: &ToggleGitBlameInline,
11362        cx: &mut ViewContext<Self>,
11363    ) {
11364        self.toggle_git_blame_inline_internal(true, cx);
11365        cx.notify();
11366    }
11367
11368    pub fn git_blame_inline_enabled(&self) -> bool {
11369        self.git_blame_inline_enabled
11370    }
11371
11372    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11373        self.show_selection_menu = self
11374            .show_selection_menu
11375            .map(|show_selections_menu| !show_selections_menu)
11376            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11377
11378        cx.notify();
11379    }
11380
11381    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11382        self.show_selection_menu
11383            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11384    }
11385
11386    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11387        if let Some(project) = self.project.as_ref() {
11388            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11389                return;
11390            };
11391
11392            if buffer.read(cx).file().is_none() {
11393                return;
11394            }
11395
11396            let focused = self.focus_handle(cx).contains_focused(cx);
11397
11398            let project = project.clone();
11399            let blame =
11400                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11401            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11402            self.blame = Some(blame);
11403        }
11404    }
11405
11406    fn toggle_git_blame_inline_internal(
11407        &mut self,
11408        user_triggered: bool,
11409        cx: &mut ViewContext<Self>,
11410    ) {
11411        if self.git_blame_inline_enabled {
11412            self.git_blame_inline_enabled = false;
11413            self.show_git_blame_inline = false;
11414            self.show_git_blame_inline_delay_task.take();
11415        } else {
11416            self.git_blame_inline_enabled = true;
11417            self.start_git_blame_inline(user_triggered, cx);
11418        }
11419
11420        cx.notify();
11421    }
11422
11423    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11424        self.start_git_blame(user_triggered, cx);
11425
11426        if ProjectSettings::get_global(cx)
11427            .git
11428            .inline_blame_delay()
11429            .is_some()
11430        {
11431            self.start_inline_blame_timer(cx);
11432        } else {
11433            self.show_git_blame_inline = true
11434        }
11435    }
11436
11437    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11438        self.blame.as_ref()
11439    }
11440
11441    pub fn show_git_blame_gutter(&self) -> bool {
11442        self.show_git_blame_gutter
11443    }
11444
11445    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11446        self.show_git_blame_gutter && self.has_blame_entries(cx)
11447    }
11448
11449    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11450        self.show_git_blame_inline
11451            && self.focus_handle.is_focused(cx)
11452            && !self.newest_selection_head_on_empty_line(cx)
11453            && self.has_blame_entries(cx)
11454    }
11455
11456    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11457        self.blame()
11458            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11459    }
11460
11461    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11462        let cursor_anchor = self.selections.newest_anchor().head();
11463
11464        let snapshot = self.buffer.read(cx).snapshot(cx);
11465        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11466
11467        snapshot.line_len(buffer_row) == 0
11468    }
11469
11470    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11471        let buffer_and_selection = maybe!({
11472            let selection = self.selections.newest::<Point>(cx);
11473            let selection_range = selection.range();
11474
11475            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11476                (buffer, selection_range.start.row..selection_range.end.row)
11477            } else {
11478                let buffer_ranges = self
11479                    .buffer()
11480                    .read(cx)
11481                    .range_to_buffer_ranges(selection_range, cx);
11482
11483                let (buffer, range, _) = if selection.reversed {
11484                    buffer_ranges.first()
11485                } else {
11486                    buffer_ranges.last()
11487                }?;
11488
11489                let snapshot = buffer.read(cx).snapshot();
11490                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11491                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11492                (buffer.clone(), selection)
11493            };
11494
11495            Some((buffer, selection))
11496        });
11497
11498        let Some((buffer, selection)) = buffer_and_selection else {
11499            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11500        };
11501
11502        let Some(project) = self.project.as_ref() else {
11503            return Task::ready(Err(anyhow!("editor does not have project")));
11504        };
11505
11506        project.update(cx, |project, cx| {
11507            project.get_permalink_to_line(&buffer, selection, cx)
11508        })
11509    }
11510
11511    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11512        let permalink_task = self.get_permalink_to_line(cx);
11513        let workspace = self.workspace();
11514
11515        cx.spawn(|_, mut cx| async move {
11516            match permalink_task.await {
11517                Ok(permalink) => {
11518                    cx.update(|cx| {
11519                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11520                    })
11521                    .ok();
11522                }
11523                Err(err) => {
11524                    let message = format!("Failed to copy permalink: {err}");
11525
11526                    Err::<(), anyhow::Error>(err).log_err();
11527
11528                    if let Some(workspace) = workspace {
11529                        workspace
11530                            .update(&mut cx, |workspace, cx| {
11531                                struct CopyPermalinkToLine;
11532
11533                                workspace.show_toast(
11534                                    Toast::new(
11535                                        NotificationId::unique::<CopyPermalinkToLine>(),
11536                                        message,
11537                                    ),
11538                                    cx,
11539                                )
11540                            })
11541                            .ok();
11542                    }
11543                }
11544            }
11545        })
11546        .detach();
11547    }
11548
11549    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11550        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11551        if let Some(file) = self.target_file(cx) {
11552            if let Some(path) = file.path().to_str() {
11553                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11554            }
11555        }
11556    }
11557
11558    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11559        let permalink_task = self.get_permalink_to_line(cx);
11560        let workspace = self.workspace();
11561
11562        cx.spawn(|_, mut cx| async move {
11563            match permalink_task.await {
11564                Ok(permalink) => {
11565                    cx.update(|cx| {
11566                        cx.open_url(permalink.as_ref());
11567                    })
11568                    .ok();
11569                }
11570                Err(err) => {
11571                    let message = format!("Failed to open permalink: {err}");
11572
11573                    Err::<(), anyhow::Error>(err).log_err();
11574
11575                    if let Some(workspace) = workspace {
11576                        workspace
11577                            .update(&mut cx, |workspace, cx| {
11578                                struct OpenPermalinkToLine;
11579
11580                                workspace.show_toast(
11581                                    Toast::new(
11582                                        NotificationId::unique::<OpenPermalinkToLine>(),
11583                                        message,
11584                                    ),
11585                                    cx,
11586                                )
11587                            })
11588                            .ok();
11589                    }
11590                }
11591            }
11592        })
11593        .detach();
11594    }
11595
11596    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11597        self.insert_uuid(UuidVersion::V4, cx);
11598    }
11599
11600    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11601        self.insert_uuid(UuidVersion::V7, cx);
11602    }
11603
11604    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11605        self.transact(cx, |this, cx| {
11606            let edits = this
11607                .selections
11608                .all::<Point>(cx)
11609                .into_iter()
11610                .map(|selection| {
11611                    let uuid = match version {
11612                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11613                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11614                    };
11615
11616                    (selection.range(), uuid.to_string())
11617                });
11618            this.edit(edits, cx);
11619            this.refresh_inline_completion(true, false, cx);
11620        });
11621    }
11622
11623    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11624    /// last highlight added will be used.
11625    ///
11626    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11627    pub fn highlight_rows<T: 'static>(
11628        &mut self,
11629        range: Range<Anchor>,
11630        color: Hsla,
11631        should_autoscroll: bool,
11632        cx: &mut ViewContext<Self>,
11633    ) {
11634        let snapshot = self.buffer().read(cx).snapshot(cx);
11635        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11636        let ix = row_highlights.binary_search_by(|highlight| {
11637            Ordering::Equal
11638                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11639                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11640        });
11641
11642        if let Err(mut ix) = ix {
11643            let index = post_inc(&mut self.highlight_order);
11644
11645            // If this range intersects with the preceding highlight, then merge it with
11646            // the preceding highlight. Otherwise insert a new highlight.
11647            let mut merged = false;
11648            if ix > 0 {
11649                let prev_highlight = &mut row_highlights[ix - 1];
11650                if prev_highlight
11651                    .range
11652                    .end
11653                    .cmp(&range.start, &snapshot)
11654                    .is_ge()
11655                {
11656                    ix -= 1;
11657                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11658                        prev_highlight.range.end = range.end;
11659                    }
11660                    merged = true;
11661                    prev_highlight.index = index;
11662                    prev_highlight.color = color;
11663                    prev_highlight.should_autoscroll = should_autoscroll;
11664                }
11665            }
11666
11667            if !merged {
11668                row_highlights.insert(
11669                    ix,
11670                    RowHighlight {
11671                        range: range.clone(),
11672                        index,
11673                        color,
11674                        should_autoscroll,
11675                    },
11676                );
11677            }
11678
11679            // If any of the following highlights intersect with this one, merge them.
11680            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11681                let highlight = &row_highlights[ix];
11682                if next_highlight
11683                    .range
11684                    .start
11685                    .cmp(&highlight.range.end, &snapshot)
11686                    .is_le()
11687                {
11688                    if next_highlight
11689                        .range
11690                        .end
11691                        .cmp(&highlight.range.end, &snapshot)
11692                        .is_gt()
11693                    {
11694                        row_highlights[ix].range.end = next_highlight.range.end;
11695                    }
11696                    row_highlights.remove(ix + 1);
11697                } else {
11698                    break;
11699                }
11700            }
11701        }
11702    }
11703
11704    /// Remove any highlighted row ranges of the given type that intersect the
11705    /// given ranges.
11706    pub fn remove_highlighted_rows<T: 'static>(
11707        &mut self,
11708        ranges_to_remove: Vec<Range<Anchor>>,
11709        cx: &mut ViewContext<Self>,
11710    ) {
11711        let snapshot = self.buffer().read(cx).snapshot(cx);
11712        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11713        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11714        row_highlights.retain(|highlight| {
11715            while let Some(range_to_remove) = ranges_to_remove.peek() {
11716                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11717                    Ordering::Less | Ordering::Equal => {
11718                        ranges_to_remove.next();
11719                    }
11720                    Ordering::Greater => {
11721                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11722                            Ordering::Less | Ordering::Equal => {
11723                                return false;
11724                            }
11725                            Ordering::Greater => break,
11726                        }
11727                    }
11728                }
11729            }
11730
11731            true
11732        })
11733    }
11734
11735    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11736    pub fn clear_row_highlights<T: 'static>(&mut self) {
11737        self.highlighted_rows.remove(&TypeId::of::<T>());
11738    }
11739
11740    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11741    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11742        self.highlighted_rows
11743            .get(&TypeId::of::<T>())
11744            .map_or(&[] as &[_], |vec| vec.as_slice())
11745            .iter()
11746            .map(|highlight| (highlight.range.clone(), highlight.color))
11747    }
11748
11749    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11750    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11751    /// Allows to ignore certain kinds of highlights.
11752    pub fn highlighted_display_rows(
11753        &mut self,
11754        cx: &mut WindowContext,
11755    ) -> BTreeMap<DisplayRow, Hsla> {
11756        let snapshot = self.snapshot(cx);
11757        let mut used_highlight_orders = HashMap::default();
11758        self.highlighted_rows
11759            .iter()
11760            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11761            .fold(
11762                BTreeMap::<DisplayRow, Hsla>::new(),
11763                |mut unique_rows, highlight| {
11764                    let start = highlight.range.start.to_display_point(&snapshot);
11765                    let end = highlight.range.end.to_display_point(&snapshot);
11766                    let start_row = start.row().0;
11767                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11768                        && end.column() == 0
11769                    {
11770                        end.row().0.saturating_sub(1)
11771                    } else {
11772                        end.row().0
11773                    };
11774                    for row in start_row..=end_row {
11775                        let used_index =
11776                            used_highlight_orders.entry(row).or_insert(highlight.index);
11777                        if highlight.index >= *used_index {
11778                            *used_index = highlight.index;
11779                            unique_rows.insert(DisplayRow(row), highlight.color);
11780                        }
11781                    }
11782                    unique_rows
11783                },
11784            )
11785    }
11786
11787    pub fn highlighted_display_row_for_autoscroll(
11788        &self,
11789        snapshot: &DisplaySnapshot,
11790    ) -> Option<DisplayRow> {
11791        self.highlighted_rows
11792            .values()
11793            .flat_map(|highlighted_rows| highlighted_rows.iter())
11794            .filter_map(|highlight| {
11795                if highlight.should_autoscroll {
11796                    Some(highlight.range.start.to_display_point(snapshot).row())
11797                } else {
11798                    None
11799                }
11800            })
11801            .min()
11802    }
11803
11804    pub fn set_search_within_ranges(
11805        &mut self,
11806        ranges: &[Range<Anchor>],
11807        cx: &mut ViewContext<Self>,
11808    ) {
11809        self.highlight_background::<SearchWithinRange>(
11810            ranges,
11811            |colors| colors.editor_document_highlight_read_background,
11812            cx,
11813        )
11814    }
11815
11816    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11817        self.breadcrumb_header = Some(new_header);
11818    }
11819
11820    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11821        self.clear_background_highlights::<SearchWithinRange>(cx);
11822    }
11823
11824    pub fn highlight_background<T: 'static>(
11825        &mut self,
11826        ranges: &[Range<Anchor>],
11827        color_fetcher: fn(&ThemeColors) -> Hsla,
11828        cx: &mut ViewContext<Self>,
11829    ) {
11830        self.background_highlights
11831            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11832        self.scrollbar_marker_state.dirty = true;
11833        cx.notify();
11834    }
11835
11836    pub fn clear_background_highlights<T: 'static>(
11837        &mut self,
11838        cx: &mut ViewContext<Self>,
11839    ) -> Option<BackgroundHighlight> {
11840        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11841        if !text_highlights.1.is_empty() {
11842            self.scrollbar_marker_state.dirty = true;
11843            cx.notify();
11844        }
11845        Some(text_highlights)
11846    }
11847
11848    pub fn highlight_gutter<T: 'static>(
11849        &mut self,
11850        ranges: &[Range<Anchor>],
11851        color_fetcher: fn(&AppContext) -> Hsla,
11852        cx: &mut ViewContext<Self>,
11853    ) {
11854        self.gutter_highlights
11855            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11856        cx.notify();
11857    }
11858
11859    pub fn clear_gutter_highlights<T: 'static>(
11860        &mut self,
11861        cx: &mut ViewContext<Self>,
11862    ) -> Option<GutterHighlight> {
11863        cx.notify();
11864        self.gutter_highlights.remove(&TypeId::of::<T>())
11865    }
11866
11867    #[cfg(feature = "test-support")]
11868    pub fn all_text_background_highlights(
11869        &mut self,
11870        cx: &mut ViewContext<Self>,
11871    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11872        let snapshot = self.snapshot(cx);
11873        let buffer = &snapshot.buffer_snapshot;
11874        let start = buffer.anchor_before(0);
11875        let end = buffer.anchor_after(buffer.len());
11876        let theme = cx.theme().colors();
11877        self.background_highlights_in_range(start..end, &snapshot, theme)
11878    }
11879
11880    #[cfg(feature = "test-support")]
11881    pub fn search_background_highlights(
11882        &mut self,
11883        cx: &mut ViewContext<Self>,
11884    ) -> Vec<Range<Point>> {
11885        let snapshot = self.buffer().read(cx).snapshot(cx);
11886
11887        let highlights = self
11888            .background_highlights
11889            .get(&TypeId::of::<items::BufferSearchHighlights>());
11890
11891        if let Some((_color, ranges)) = highlights {
11892            ranges
11893                .iter()
11894                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11895                .collect_vec()
11896        } else {
11897            vec![]
11898        }
11899    }
11900
11901    fn document_highlights_for_position<'a>(
11902        &'a self,
11903        position: Anchor,
11904        buffer: &'a MultiBufferSnapshot,
11905    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11906        let read_highlights = self
11907            .background_highlights
11908            .get(&TypeId::of::<DocumentHighlightRead>())
11909            .map(|h| &h.1);
11910        let write_highlights = self
11911            .background_highlights
11912            .get(&TypeId::of::<DocumentHighlightWrite>())
11913            .map(|h| &h.1);
11914        let left_position = position.bias_left(buffer);
11915        let right_position = position.bias_right(buffer);
11916        read_highlights
11917            .into_iter()
11918            .chain(write_highlights)
11919            .flat_map(move |ranges| {
11920                let start_ix = match ranges.binary_search_by(|probe| {
11921                    let cmp = probe.end.cmp(&left_position, buffer);
11922                    if cmp.is_ge() {
11923                        Ordering::Greater
11924                    } else {
11925                        Ordering::Less
11926                    }
11927                }) {
11928                    Ok(i) | Err(i) => i,
11929                };
11930
11931                ranges[start_ix..]
11932                    .iter()
11933                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11934            })
11935    }
11936
11937    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11938        self.background_highlights
11939            .get(&TypeId::of::<T>())
11940            .map_or(false, |(_, highlights)| !highlights.is_empty())
11941    }
11942
11943    pub fn background_highlights_in_range(
11944        &self,
11945        search_range: Range<Anchor>,
11946        display_snapshot: &DisplaySnapshot,
11947        theme: &ThemeColors,
11948    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11949        let mut results = Vec::new();
11950        for (color_fetcher, ranges) in self.background_highlights.values() {
11951            let color = color_fetcher(theme);
11952            let start_ix = match ranges.binary_search_by(|probe| {
11953                let cmp = probe
11954                    .end
11955                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11956                if cmp.is_gt() {
11957                    Ordering::Greater
11958                } else {
11959                    Ordering::Less
11960                }
11961            }) {
11962                Ok(i) | Err(i) => i,
11963            };
11964            for range in &ranges[start_ix..] {
11965                if range
11966                    .start
11967                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11968                    .is_ge()
11969                {
11970                    break;
11971                }
11972
11973                let start = range.start.to_display_point(display_snapshot);
11974                let end = range.end.to_display_point(display_snapshot);
11975                results.push((start..end, color))
11976            }
11977        }
11978        results
11979    }
11980
11981    pub fn background_highlight_row_ranges<T: 'static>(
11982        &self,
11983        search_range: Range<Anchor>,
11984        display_snapshot: &DisplaySnapshot,
11985        count: usize,
11986    ) -> Vec<RangeInclusive<DisplayPoint>> {
11987        let mut results = Vec::new();
11988        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11989            return vec![];
11990        };
11991
11992        let start_ix = match ranges.binary_search_by(|probe| {
11993            let cmp = probe
11994                .end
11995                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11996            if cmp.is_gt() {
11997                Ordering::Greater
11998            } else {
11999                Ordering::Less
12000            }
12001        }) {
12002            Ok(i) | Err(i) => i,
12003        };
12004        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12005            if let (Some(start_display), Some(end_display)) = (start, end) {
12006                results.push(
12007                    start_display.to_display_point(display_snapshot)
12008                        ..=end_display.to_display_point(display_snapshot),
12009                );
12010            }
12011        };
12012        let mut start_row: Option<Point> = None;
12013        let mut end_row: Option<Point> = None;
12014        if ranges.len() > count {
12015            return Vec::new();
12016        }
12017        for range in &ranges[start_ix..] {
12018            if range
12019                .start
12020                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12021                .is_ge()
12022            {
12023                break;
12024            }
12025            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12026            if let Some(current_row) = &end_row {
12027                if end.row == current_row.row {
12028                    continue;
12029                }
12030            }
12031            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12032            if start_row.is_none() {
12033                assert_eq!(end_row, None);
12034                start_row = Some(start);
12035                end_row = Some(end);
12036                continue;
12037            }
12038            if let Some(current_end) = end_row.as_mut() {
12039                if start.row > current_end.row + 1 {
12040                    push_region(start_row, end_row);
12041                    start_row = Some(start);
12042                    end_row = Some(end);
12043                } else {
12044                    // Merge two hunks.
12045                    *current_end = end;
12046                }
12047            } else {
12048                unreachable!();
12049            }
12050        }
12051        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12052        push_region(start_row, end_row);
12053        results
12054    }
12055
12056    pub fn gutter_highlights_in_range(
12057        &self,
12058        search_range: Range<Anchor>,
12059        display_snapshot: &DisplaySnapshot,
12060        cx: &AppContext,
12061    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12062        let mut results = Vec::new();
12063        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12064            let color = color_fetcher(cx);
12065            let start_ix = match ranges.binary_search_by(|probe| {
12066                let cmp = probe
12067                    .end
12068                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12069                if cmp.is_gt() {
12070                    Ordering::Greater
12071                } else {
12072                    Ordering::Less
12073                }
12074            }) {
12075                Ok(i) | Err(i) => i,
12076            };
12077            for range in &ranges[start_ix..] {
12078                if range
12079                    .start
12080                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12081                    .is_ge()
12082                {
12083                    break;
12084                }
12085
12086                let start = range.start.to_display_point(display_snapshot);
12087                let end = range.end.to_display_point(display_snapshot);
12088                results.push((start..end, color))
12089            }
12090        }
12091        results
12092    }
12093
12094    /// Get the text ranges corresponding to the redaction query
12095    pub fn redacted_ranges(
12096        &self,
12097        search_range: Range<Anchor>,
12098        display_snapshot: &DisplaySnapshot,
12099        cx: &WindowContext,
12100    ) -> Vec<Range<DisplayPoint>> {
12101        display_snapshot
12102            .buffer_snapshot
12103            .redacted_ranges(search_range, |file| {
12104                if let Some(file) = file {
12105                    file.is_private()
12106                        && EditorSettings::get(
12107                            Some(SettingsLocation {
12108                                worktree_id: file.worktree_id(cx),
12109                                path: file.path().as_ref(),
12110                            }),
12111                            cx,
12112                        )
12113                        .redact_private_values
12114                } else {
12115                    false
12116                }
12117            })
12118            .map(|range| {
12119                range.start.to_display_point(display_snapshot)
12120                    ..range.end.to_display_point(display_snapshot)
12121            })
12122            .collect()
12123    }
12124
12125    pub fn highlight_text<T: 'static>(
12126        &mut self,
12127        ranges: Vec<Range<Anchor>>,
12128        style: HighlightStyle,
12129        cx: &mut ViewContext<Self>,
12130    ) {
12131        self.display_map.update(cx, |map, _| {
12132            map.highlight_text(TypeId::of::<T>(), ranges, style)
12133        });
12134        cx.notify();
12135    }
12136
12137    pub(crate) fn highlight_inlays<T: 'static>(
12138        &mut self,
12139        highlights: Vec<InlayHighlight>,
12140        style: HighlightStyle,
12141        cx: &mut ViewContext<Self>,
12142    ) {
12143        self.display_map.update(cx, |map, _| {
12144            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12145        });
12146        cx.notify();
12147    }
12148
12149    pub fn text_highlights<'a, T: 'static>(
12150        &'a self,
12151        cx: &'a AppContext,
12152    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12153        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12154    }
12155
12156    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12157        let cleared = self
12158            .display_map
12159            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12160        if cleared {
12161            cx.notify();
12162        }
12163    }
12164
12165    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12166        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12167            && self.focus_handle.is_focused(cx)
12168    }
12169
12170    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12171        self.show_cursor_when_unfocused = is_enabled;
12172        cx.notify();
12173    }
12174
12175    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12176        self.project
12177            .as_ref()
12178            .map(|project| project.read(cx).lsp_store())
12179    }
12180
12181    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12182        cx.notify();
12183    }
12184
12185    fn on_buffer_event(
12186        &mut self,
12187        multibuffer: Model<MultiBuffer>,
12188        event: &multi_buffer::Event,
12189        cx: &mut ViewContext<Self>,
12190    ) {
12191        match event {
12192            multi_buffer::Event::Edited {
12193                singleton_buffer_edited,
12194                edited_buffer: buffer_edited,
12195            } => {
12196                self.scrollbar_marker_state.dirty = true;
12197                self.active_indent_guides_state.dirty = true;
12198                self.refresh_active_diagnostics(cx);
12199                self.refresh_code_actions(cx);
12200                if self.has_active_inline_completion() {
12201                    self.update_visible_inline_completion(cx);
12202                }
12203                if let Some(buffer) = buffer_edited {
12204                    let buffer_id = buffer.read(cx).remote_id();
12205                    if !self.registered_buffers.contains_key(&buffer_id) {
12206                        if let Some(lsp_store) = self.lsp_store(cx) {
12207                            lsp_store.update(cx, |lsp_store, cx| {
12208                                self.registered_buffers.insert(
12209                                    buffer_id,
12210                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12211                                );
12212                            })
12213                        }
12214                    }
12215                }
12216                cx.emit(EditorEvent::BufferEdited);
12217                cx.emit(SearchEvent::MatchesInvalidated);
12218                if *singleton_buffer_edited {
12219                    if let Some(project) = &self.project {
12220                        let project = project.read(cx);
12221                        #[allow(clippy::mutable_key_type)]
12222                        let languages_affected = multibuffer
12223                            .read(cx)
12224                            .all_buffers()
12225                            .into_iter()
12226                            .filter_map(|buffer| {
12227                                let buffer = buffer.read(cx);
12228                                let language = buffer.language()?;
12229                                if project.is_local()
12230                                    && project
12231                                        .language_servers_for_local_buffer(buffer, cx)
12232                                        .count()
12233                                        == 0
12234                                {
12235                                    None
12236                                } else {
12237                                    Some(language)
12238                                }
12239                            })
12240                            .cloned()
12241                            .collect::<HashSet<_>>();
12242                        if !languages_affected.is_empty() {
12243                            self.refresh_inlay_hints(
12244                                InlayHintRefreshReason::BufferEdited(languages_affected),
12245                                cx,
12246                            );
12247                        }
12248                    }
12249                }
12250
12251                let Some(project) = &self.project else { return };
12252                let (telemetry, is_via_ssh) = {
12253                    let project = project.read(cx);
12254                    let telemetry = project.client().telemetry().clone();
12255                    let is_via_ssh = project.is_via_ssh();
12256                    (telemetry, is_via_ssh)
12257                };
12258                refresh_linked_ranges(self, cx);
12259                telemetry.log_edit_event("editor", is_via_ssh);
12260            }
12261            multi_buffer::Event::ExcerptsAdded {
12262                buffer,
12263                predecessor,
12264                excerpts,
12265            } => {
12266                self.tasks_update_task = Some(self.refresh_runnables(cx));
12267                let buffer_id = buffer.read(cx).remote_id();
12268                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12269                    if let Some(project) = &self.project {
12270                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12271                    }
12272                }
12273                cx.emit(EditorEvent::ExcerptsAdded {
12274                    buffer: buffer.clone(),
12275                    predecessor: *predecessor,
12276                    excerpts: excerpts.clone(),
12277                });
12278                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12279            }
12280            multi_buffer::Event::ExcerptsRemoved { ids } => {
12281                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12282                let buffer = self.buffer.read(cx);
12283                self.registered_buffers
12284                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12285                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12286            }
12287            multi_buffer::Event::ExcerptsEdited { ids } => {
12288                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12289            }
12290            multi_buffer::Event::ExcerptsExpanded { ids } => {
12291                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12292            }
12293            multi_buffer::Event::Reparsed(buffer_id) => {
12294                self.tasks_update_task = Some(self.refresh_runnables(cx));
12295
12296                cx.emit(EditorEvent::Reparsed(*buffer_id));
12297            }
12298            multi_buffer::Event::LanguageChanged(buffer_id) => {
12299                linked_editing_ranges::refresh_linked_ranges(self, cx);
12300                cx.emit(EditorEvent::Reparsed(*buffer_id));
12301                cx.notify();
12302            }
12303            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12304            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12305            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12306                cx.emit(EditorEvent::TitleChanged)
12307            }
12308            // multi_buffer::Event::DiffBaseChanged => {
12309            //     self.scrollbar_marker_state.dirty = true;
12310            //     cx.emit(EditorEvent::DiffBaseChanged);
12311            //     cx.notify();
12312            // }
12313            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12314            multi_buffer::Event::DiagnosticsUpdated => {
12315                self.refresh_active_diagnostics(cx);
12316                self.scrollbar_marker_state.dirty = true;
12317                cx.notify();
12318            }
12319            _ => {}
12320        };
12321    }
12322
12323    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12324        cx.notify();
12325    }
12326
12327    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12328        self.tasks_update_task = Some(self.refresh_runnables(cx));
12329        self.refresh_inline_completion(true, false, cx);
12330        self.refresh_inlay_hints(
12331            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12332                self.selections.newest_anchor().head(),
12333                &self.buffer.read(cx).snapshot(cx),
12334                cx,
12335            )),
12336            cx,
12337        );
12338
12339        let old_cursor_shape = self.cursor_shape;
12340
12341        {
12342            let editor_settings = EditorSettings::get_global(cx);
12343            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12344            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12345            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12346        }
12347
12348        if old_cursor_shape != self.cursor_shape {
12349            cx.emit(EditorEvent::CursorShapeChanged);
12350        }
12351
12352        let project_settings = ProjectSettings::get_global(cx);
12353        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12354
12355        if self.mode == EditorMode::Full {
12356            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12357            if self.git_blame_inline_enabled != inline_blame_enabled {
12358                self.toggle_git_blame_inline_internal(false, cx);
12359            }
12360        }
12361
12362        cx.notify();
12363    }
12364
12365    pub fn set_searchable(&mut self, searchable: bool) {
12366        self.searchable = searchable;
12367    }
12368
12369    pub fn searchable(&self) -> bool {
12370        self.searchable
12371    }
12372
12373    fn open_proposed_changes_editor(
12374        &mut self,
12375        _: &OpenProposedChangesEditor,
12376        cx: &mut ViewContext<Self>,
12377    ) {
12378        let Some(workspace) = self.workspace() else {
12379            cx.propagate();
12380            return;
12381        };
12382
12383        let selections = self.selections.all::<usize>(cx);
12384        let buffer = self.buffer.read(cx);
12385        let mut new_selections_by_buffer = HashMap::default();
12386        for selection in selections {
12387            for (buffer, range, _) in
12388                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12389            {
12390                let mut range = range.to_point(buffer.read(cx));
12391                range.start.column = 0;
12392                range.end.column = buffer.read(cx).line_len(range.end.row);
12393                new_selections_by_buffer
12394                    .entry(buffer)
12395                    .or_insert(Vec::new())
12396                    .push(range)
12397            }
12398        }
12399
12400        let proposed_changes_buffers = new_selections_by_buffer
12401            .into_iter()
12402            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12403            .collect::<Vec<_>>();
12404        let proposed_changes_editor = cx.new_view(|cx| {
12405            ProposedChangesEditor::new(
12406                "Proposed changes",
12407                proposed_changes_buffers,
12408                self.project.clone(),
12409                cx,
12410            )
12411        });
12412
12413        cx.window_context().defer(move |cx| {
12414            workspace.update(cx, |workspace, cx| {
12415                workspace.active_pane().update(cx, |pane, cx| {
12416                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12417                });
12418            });
12419        });
12420    }
12421
12422    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12423        self.open_excerpts_common(None, true, cx)
12424    }
12425
12426    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12427        self.open_excerpts_common(None, false, cx)
12428    }
12429
12430    fn open_excerpts_common(
12431        &mut self,
12432        jump_data: Option<JumpData>,
12433        split: bool,
12434        cx: &mut ViewContext<Self>,
12435    ) {
12436        let Some(workspace) = self.workspace() else {
12437            cx.propagate();
12438            return;
12439        };
12440
12441        if self.buffer.read(cx).is_singleton() {
12442            cx.propagate();
12443            return;
12444        }
12445
12446        let mut new_selections_by_buffer = HashMap::default();
12447        match &jump_data {
12448            Some(jump_data) => {
12449                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12450                if let Some(buffer) = multi_buffer_snapshot
12451                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12452                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12453                {
12454                    let buffer_snapshot = buffer.read(cx).snapshot();
12455                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12456                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12457                    } else {
12458                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12459                    };
12460                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12461                    new_selections_by_buffer.insert(
12462                        buffer,
12463                        (
12464                            vec![jump_to_offset..jump_to_offset],
12465                            Some(jump_data.line_offset_from_top),
12466                        ),
12467                    );
12468                }
12469            }
12470            None => {
12471                let selections = self.selections.all::<usize>(cx);
12472                let buffer = self.buffer.read(cx);
12473                for selection in selections {
12474                    for (mut buffer_handle, mut range, _) in
12475                        buffer.range_to_buffer_ranges(selection.range(), cx)
12476                    {
12477                        // When editing branch buffers, jump to the corresponding location
12478                        // in their base buffer.
12479                        let buffer = buffer_handle.read(cx);
12480                        if let Some(base_buffer) = buffer.base_buffer() {
12481                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12482                            buffer_handle = base_buffer;
12483                        }
12484
12485                        if selection.reversed {
12486                            mem::swap(&mut range.start, &mut range.end);
12487                        }
12488                        new_selections_by_buffer
12489                            .entry(buffer_handle)
12490                            .or_insert((Vec::new(), None))
12491                            .0
12492                            .push(range)
12493                    }
12494                }
12495            }
12496        }
12497
12498        if new_selections_by_buffer.is_empty() {
12499            return;
12500        }
12501
12502        // We defer the pane interaction because we ourselves are a workspace item
12503        // and activating a new item causes the pane to call a method on us reentrantly,
12504        // which panics if we're on the stack.
12505        cx.window_context().defer(move |cx| {
12506            workspace.update(cx, |workspace, cx| {
12507                let pane = if split {
12508                    workspace.adjacent_pane(cx)
12509                } else {
12510                    workspace.active_pane().clone()
12511                };
12512
12513                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12514                    let editor = buffer
12515                        .read(cx)
12516                        .file()
12517                        .is_none()
12518                        .then(|| {
12519                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12520                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12521                            // Instead, we try to activate the existing editor in the pane first.
12522                            let (editor, pane_item_index) =
12523                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12524                                    let editor = item.downcast::<Editor>()?;
12525                                    let singleton_buffer =
12526                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12527                                    if singleton_buffer == buffer {
12528                                        Some((editor, i))
12529                                    } else {
12530                                        None
12531                                    }
12532                                })?;
12533                            pane.update(cx, |pane, cx| {
12534                                pane.activate_item(pane_item_index, true, true, cx)
12535                            });
12536                            Some(editor)
12537                        })
12538                        .flatten()
12539                        .unwrap_or_else(|| {
12540                            workspace.open_project_item::<Self>(
12541                                pane.clone(),
12542                                buffer,
12543                                true,
12544                                true,
12545                                cx,
12546                            )
12547                        });
12548
12549                    editor.update(cx, |editor, cx| {
12550                        let autoscroll = match scroll_offset {
12551                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12552                            None => Autoscroll::newest(),
12553                        };
12554                        let nav_history = editor.nav_history.take();
12555                        editor.change_selections(Some(autoscroll), cx, |s| {
12556                            s.select_ranges(ranges);
12557                        });
12558                        editor.nav_history = nav_history;
12559                    });
12560                }
12561            })
12562        });
12563    }
12564
12565    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12566        let snapshot = self.buffer.read(cx).read(cx);
12567        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12568        Some(
12569            ranges
12570                .iter()
12571                .map(move |range| {
12572                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12573                })
12574                .collect(),
12575        )
12576    }
12577
12578    fn selection_replacement_ranges(
12579        &self,
12580        range: Range<OffsetUtf16>,
12581        cx: &mut AppContext,
12582    ) -> Vec<Range<OffsetUtf16>> {
12583        let selections = self.selections.all::<OffsetUtf16>(cx);
12584        let newest_selection = selections
12585            .iter()
12586            .max_by_key(|selection| selection.id)
12587            .unwrap();
12588        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12589        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12590        let snapshot = self.buffer.read(cx).read(cx);
12591        selections
12592            .into_iter()
12593            .map(|mut selection| {
12594                selection.start.0 =
12595                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12596                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12597                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12598                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12599            })
12600            .collect()
12601    }
12602
12603    fn report_editor_event(
12604        &self,
12605        event_type: &'static str,
12606        file_extension: Option<String>,
12607        cx: &AppContext,
12608    ) {
12609        if cfg!(any(test, feature = "test-support")) {
12610            return;
12611        }
12612
12613        let Some(project) = &self.project else { return };
12614
12615        // If None, we are in a file without an extension
12616        let file = self
12617            .buffer
12618            .read(cx)
12619            .as_singleton()
12620            .and_then(|b| b.read(cx).file());
12621        let file_extension = file_extension.or(file
12622            .as_ref()
12623            .and_then(|file| Path::new(file.file_name(cx)).extension())
12624            .and_then(|e| e.to_str())
12625            .map(|a| a.to_string()));
12626
12627        let vim_mode = cx
12628            .global::<SettingsStore>()
12629            .raw_user_settings()
12630            .get("vim_mode")
12631            == Some(&serde_json::Value::Bool(true));
12632
12633        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12634            == language::language_settings::InlineCompletionProvider::Copilot;
12635        let copilot_enabled_for_language = self
12636            .buffer
12637            .read(cx)
12638            .settings_at(0, cx)
12639            .show_inline_completions;
12640
12641        let project = project.read(cx);
12642        telemetry::event!(
12643            event_type,
12644            file_extension,
12645            vim_mode,
12646            copilot_enabled,
12647            copilot_enabled_for_language,
12648            is_via_ssh = project.is_via_ssh(),
12649        );
12650    }
12651
12652    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12653    /// with each line being an array of {text, highlight} objects.
12654    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12655        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12656            return;
12657        };
12658
12659        #[derive(Serialize)]
12660        struct Chunk<'a> {
12661            text: String,
12662            highlight: Option<&'a str>,
12663        }
12664
12665        let snapshot = buffer.read(cx).snapshot();
12666        let range = self
12667            .selected_text_range(false, cx)
12668            .and_then(|selection| {
12669                if selection.range.is_empty() {
12670                    None
12671                } else {
12672                    Some(selection.range)
12673                }
12674            })
12675            .unwrap_or_else(|| 0..snapshot.len());
12676
12677        let chunks = snapshot.chunks(range, true);
12678        let mut lines = Vec::new();
12679        let mut line: VecDeque<Chunk> = VecDeque::new();
12680
12681        let Some(style) = self.style.as_ref() else {
12682            return;
12683        };
12684
12685        for chunk in chunks {
12686            let highlight = chunk
12687                .syntax_highlight_id
12688                .and_then(|id| id.name(&style.syntax));
12689            let mut chunk_lines = chunk.text.split('\n').peekable();
12690            while let Some(text) = chunk_lines.next() {
12691                let mut merged_with_last_token = false;
12692                if let Some(last_token) = line.back_mut() {
12693                    if last_token.highlight == highlight {
12694                        last_token.text.push_str(text);
12695                        merged_with_last_token = true;
12696                    }
12697                }
12698
12699                if !merged_with_last_token {
12700                    line.push_back(Chunk {
12701                        text: text.into(),
12702                        highlight,
12703                    });
12704                }
12705
12706                if chunk_lines.peek().is_some() {
12707                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12708                        line.pop_front();
12709                    }
12710                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12711                        line.pop_back();
12712                    }
12713
12714                    lines.push(mem::take(&mut line));
12715                }
12716            }
12717        }
12718
12719        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12720            return;
12721        };
12722        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12723    }
12724
12725    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12726        self.request_autoscroll(Autoscroll::newest(), cx);
12727        let position = self.selections.newest_display(cx).start;
12728        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12729    }
12730
12731    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12732        &self.inlay_hint_cache
12733    }
12734
12735    pub fn replay_insert_event(
12736        &mut self,
12737        text: &str,
12738        relative_utf16_range: Option<Range<isize>>,
12739        cx: &mut ViewContext<Self>,
12740    ) {
12741        if !self.input_enabled {
12742            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12743            return;
12744        }
12745        if let Some(relative_utf16_range) = relative_utf16_range {
12746            let selections = self.selections.all::<OffsetUtf16>(cx);
12747            self.change_selections(None, cx, |s| {
12748                let new_ranges = selections.into_iter().map(|range| {
12749                    let start = OffsetUtf16(
12750                        range
12751                            .head()
12752                            .0
12753                            .saturating_add_signed(relative_utf16_range.start),
12754                    );
12755                    let end = OffsetUtf16(
12756                        range
12757                            .head()
12758                            .0
12759                            .saturating_add_signed(relative_utf16_range.end),
12760                    );
12761                    start..end
12762                });
12763                s.select_ranges(new_ranges);
12764            });
12765        }
12766
12767        self.handle_input(text, cx);
12768    }
12769
12770    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12771        let Some(provider) = self.semantics_provider.as_ref() else {
12772            return false;
12773        };
12774
12775        let mut supports = false;
12776        self.buffer().read(cx).for_each_buffer(|buffer| {
12777            supports |= provider.supports_inlay_hints(buffer, cx);
12778        });
12779        supports
12780    }
12781
12782    pub fn focus(&self, cx: &mut WindowContext) {
12783        cx.focus(&self.focus_handle)
12784    }
12785
12786    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12787        self.focus_handle.is_focused(cx)
12788    }
12789
12790    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12791        cx.emit(EditorEvent::Focused);
12792
12793        if let Some(descendant) = self
12794            .last_focused_descendant
12795            .take()
12796            .and_then(|descendant| descendant.upgrade())
12797        {
12798            cx.focus(&descendant);
12799        } else {
12800            if let Some(blame) = self.blame.as_ref() {
12801                blame.update(cx, GitBlame::focus)
12802            }
12803
12804            self.blink_manager.update(cx, BlinkManager::enable);
12805            self.show_cursor_names(cx);
12806            self.buffer.update(cx, |buffer, cx| {
12807                buffer.finalize_last_transaction(cx);
12808                if self.leader_peer_id.is_none() {
12809                    buffer.set_active_selections(
12810                        &self.selections.disjoint_anchors(),
12811                        self.selections.line_mode,
12812                        self.cursor_shape,
12813                        cx,
12814                    );
12815                }
12816            });
12817        }
12818    }
12819
12820    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12821        cx.emit(EditorEvent::FocusedIn)
12822    }
12823
12824    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12825        if event.blurred != self.focus_handle {
12826            self.last_focused_descendant = Some(event.blurred);
12827        }
12828    }
12829
12830    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12831        self.blink_manager.update(cx, BlinkManager::disable);
12832        self.buffer
12833            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12834
12835        if let Some(blame) = self.blame.as_ref() {
12836            blame.update(cx, GitBlame::blur)
12837        }
12838        if !self.hover_state.focused(cx) {
12839            hide_hover(self, cx);
12840        }
12841
12842        self.hide_context_menu(cx);
12843        cx.emit(EditorEvent::Blurred);
12844        cx.notify();
12845    }
12846
12847    pub fn register_action<A: Action>(
12848        &mut self,
12849        listener: impl Fn(&A, &mut WindowContext) + 'static,
12850    ) -> Subscription {
12851        let id = self.next_editor_action_id.post_inc();
12852        let listener = Arc::new(listener);
12853        self.editor_actions.borrow_mut().insert(
12854            id,
12855            Box::new(move |cx| {
12856                let cx = cx.window_context();
12857                let listener = listener.clone();
12858                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12859                    let action = action.downcast_ref().unwrap();
12860                    if phase == DispatchPhase::Bubble {
12861                        listener(action, cx)
12862                    }
12863                })
12864            }),
12865        );
12866
12867        let editor_actions = self.editor_actions.clone();
12868        Subscription::new(move || {
12869            editor_actions.borrow_mut().remove(&id);
12870        })
12871    }
12872
12873    pub fn file_header_size(&self) -> u32 {
12874        FILE_HEADER_HEIGHT
12875    }
12876
12877    pub fn revert(
12878        &mut self,
12879        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12880        cx: &mut ViewContext<Self>,
12881    ) {
12882        self.buffer().update(cx, |multi_buffer, cx| {
12883            for (buffer_id, changes) in revert_changes {
12884                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12885                    buffer.update(cx, |buffer, cx| {
12886                        buffer.edit(
12887                            changes.into_iter().map(|(range, text)| {
12888                                (range, text.to_string().map(Arc::<str>::from))
12889                            }),
12890                            None,
12891                            cx,
12892                        );
12893                    });
12894                }
12895            }
12896        });
12897        self.change_selections(None, cx, |selections| selections.refresh());
12898    }
12899
12900    pub fn to_pixel_point(
12901        &mut self,
12902        source: multi_buffer::Anchor,
12903        editor_snapshot: &EditorSnapshot,
12904        cx: &mut ViewContext<Self>,
12905    ) -> Option<gpui::Point<Pixels>> {
12906        let source_point = source.to_display_point(editor_snapshot);
12907        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12908    }
12909
12910    pub fn display_to_pixel_point(
12911        &self,
12912        source: DisplayPoint,
12913        editor_snapshot: &EditorSnapshot,
12914        cx: &WindowContext,
12915    ) -> Option<gpui::Point<Pixels>> {
12916        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12917        let text_layout_details = self.text_layout_details(cx);
12918        let scroll_top = text_layout_details
12919            .scroll_anchor
12920            .scroll_position(editor_snapshot)
12921            .y;
12922
12923        if source.row().as_f32() < scroll_top.floor() {
12924            return None;
12925        }
12926        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12927        let source_y = line_height * (source.row().as_f32() - scroll_top);
12928        Some(gpui::Point::new(source_x, source_y))
12929    }
12930
12931    pub fn has_active_completions_menu(&self) -> bool {
12932        self.context_menu.borrow().as_ref().map_or(false, |menu| {
12933            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12934        })
12935    }
12936
12937    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12938        self.addons
12939            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12940    }
12941
12942    pub fn unregister_addon<T: Addon>(&mut self) {
12943        self.addons.remove(&std::any::TypeId::of::<T>());
12944    }
12945
12946    pub fn addon<T: Addon>(&self) -> Option<&T> {
12947        let type_id = std::any::TypeId::of::<T>();
12948        self.addons
12949            .get(&type_id)
12950            .and_then(|item| item.to_any().downcast_ref::<T>())
12951    }
12952
12953    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12954        let text_layout_details = self.text_layout_details(cx);
12955        let style = &text_layout_details.editor_style;
12956        let font_id = cx.text_system().resolve_font(&style.text.font());
12957        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12958        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12959
12960        let em_width = cx
12961            .text_system()
12962            .typographic_bounds(font_id, font_size, 'm')
12963            .unwrap()
12964            .size
12965            .width;
12966
12967        gpui::Point::new(em_width, line_height)
12968    }
12969}
12970
12971fn get_unstaged_changes_for_buffers(
12972    project: &Model<Project>,
12973    buffers: impl IntoIterator<Item = Model<Buffer>>,
12974    cx: &mut ViewContext<Editor>,
12975) {
12976    let mut tasks = Vec::new();
12977    project.update(cx, |project, cx| {
12978        for buffer in buffers {
12979            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12980        }
12981    });
12982    cx.spawn(|this, mut cx| async move {
12983        let change_sets = futures::future::join_all(tasks).await;
12984        this.update(&mut cx, |this, cx| {
12985            for change_set in change_sets {
12986                if let Some(change_set) = change_set.log_err() {
12987                    this.diff_map.add_change_set(change_set, cx);
12988                }
12989            }
12990        })
12991        .ok();
12992    })
12993    .detach();
12994}
12995
12996fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12997    let tab_size = tab_size.get() as usize;
12998    let mut width = offset;
12999
13000    for ch in text.chars() {
13001        width += if ch == '\t' {
13002            tab_size - (width % tab_size)
13003        } else {
13004            1
13005        };
13006    }
13007
13008    width - offset
13009}
13010
13011#[cfg(test)]
13012mod tests {
13013    use super::*;
13014
13015    #[test]
13016    fn test_string_size_with_expanded_tabs() {
13017        let nz = |val| NonZeroU32::new(val).unwrap();
13018        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13019        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13020        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13021        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13022        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13023        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13024        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13025        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13026    }
13027}
13028
13029/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13030struct WordBreakingTokenizer<'a> {
13031    input: &'a str,
13032}
13033
13034impl<'a> WordBreakingTokenizer<'a> {
13035    fn new(input: &'a str) -> Self {
13036        Self { input }
13037    }
13038}
13039
13040fn is_char_ideographic(ch: char) -> bool {
13041    use unicode_script::Script::*;
13042    use unicode_script::UnicodeScript;
13043    matches!(ch.script(), Han | Tangut | Yi)
13044}
13045
13046fn is_grapheme_ideographic(text: &str) -> bool {
13047    text.chars().any(is_char_ideographic)
13048}
13049
13050fn is_grapheme_whitespace(text: &str) -> bool {
13051    text.chars().any(|x| x.is_whitespace())
13052}
13053
13054fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13055    text.chars().next().map_or(false, |ch| {
13056        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13057    })
13058}
13059
13060#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13061struct WordBreakToken<'a> {
13062    token: &'a str,
13063    grapheme_len: usize,
13064    is_whitespace: bool,
13065}
13066
13067impl<'a> Iterator for WordBreakingTokenizer<'a> {
13068    /// Yields a span, the count of graphemes in the token, and whether it was
13069    /// whitespace. Note that it also breaks at word boundaries.
13070    type Item = WordBreakToken<'a>;
13071
13072    fn next(&mut self) -> Option<Self::Item> {
13073        use unicode_segmentation::UnicodeSegmentation;
13074        if self.input.is_empty() {
13075            return None;
13076        }
13077
13078        let mut iter = self.input.graphemes(true).peekable();
13079        let mut offset = 0;
13080        let mut graphemes = 0;
13081        if let Some(first_grapheme) = iter.next() {
13082            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13083            offset += first_grapheme.len();
13084            graphemes += 1;
13085            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13086                if let Some(grapheme) = iter.peek().copied() {
13087                    if should_stay_with_preceding_ideograph(grapheme) {
13088                        offset += grapheme.len();
13089                        graphemes += 1;
13090                    }
13091                }
13092            } else {
13093                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13094                let mut next_word_bound = words.peek().copied();
13095                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13096                    next_word_bound = words.next();
13097                }
13098                while let Some(grapheme) = iter.peek().copied() {
13099                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13100                        break;
13101                    };
13102                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13103                        break;
13104                    };
13105                    offset += grapheme.len();
13106                    graphemes += 1;
13107                    iter.next();
13108                }
13109            }
13110            let token = &self.input[..offset];
13111            self.input = &self.input[offset..];
13112            if is_whitespace {
13113                Some(WordBreakToken {
13114                    token: " ",
13115                    grapheme_len: 1,
13116                    is_whitespace: true,
13117                })
13118            } else {
13119                Some(WordBreakToken {
13120                    token,
13121                    grapheme_len: graphemes,
13122                    is_whitespace: false,
13123                })
13124            }
13125        } else {
13126            None
13127        }
13128    }
13129}
13130
13131#[test]
13132fn test_word_breaking_tokenizer() {
13133    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13134        ("", &[]),
13135        ("  ", &[(" ", 1, true)]),
13136        ("Ʒ", &[("Ʒ", 1, false)]),
13137        ("Ǽ", &[("Ǽ", 1, false)]),
13138        ("", &[("", 1, false)]),
13139        ("⋑⋑", &[("⋑⋑", 2, false)]),
13140        (
13141            "原理,进而",
13142            &[
13143                ("", 1, false),
13144                ("理,", 2, false),
13145                ("", 1, false),
13146                ("", 1, false),
13147            ],
13148        ),
13149        (
13150            "hello world",
13151            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13152        ),
13153        (
13154            "hello, world",
13155            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13156        ),
13157        (
13158            "  hello world",
13159            &[
13160                (" ", 1, true),
13161                ("hello", 5, false),
13162                (" ", 1, true),
13163                ("world", 5, false),
13164            ],
13165        ),
13166        (
13167            "这是什么 \n 钢笔",
13168            &[
13169                ("", 1, false),
13170                ("", 1, false),
13171                ("", 1, false),
13172                ("", 1, false),
13173                (" ", 1, true),
13174                ("", 1, false),
13175                ("", 1, false),
13176            ],
13177        ),
13178        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13179    ];
13180
13181    for (input, result) in tests {
13182        assert_eq!(
13183            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13184            result
13185                .iter()
13186                .copied()
13187                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13188                    token,
13189                    grapheme_len,
13190                    is_whitespace,
13191                })
13192                .collect::<Vec<_>>()
13193        );
13194    }
13195}
13196
13197fn wrap_with_prefix(
13198    line_prefix: String,
13199    unwrapped_text: String,
13200    wrap_column: usize,
13201    tab_size: NonZeroU32,
13202) -> String {
13203    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13204    let mut wrapped_text = String::new();
13205    let mut current_line = line_prefix.clone();
13206
13207    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13208    let mut current_line_len = line_prefix_len;
13209    for WordBreakToken {
13210        token,
13211        grapheme_len,
13212        is_whitespace,
13213    } in tokenizer
13214    {
13215        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13216            wrapped_text.push_str(current_line.trim_end());
13217            wrapped_text.push('\n');
13218            current_line.truncate(line_prefix.len());
13219            current_line_len = line_prefix_len;
13220            if !is_whitespace {
13221                current_line.push_str(token);
13222                current_line_len += grapheme_len;
13223            }
13224        } else if !is_whitespace {
13225            current_line.push_str(token);
13226            current_line_len += grapheme_len;
13227        } else if current_line_len != line_prefix_len {
13228            current_line.push(' ');
13229            current_line_len += 1;
13230        }
13231    }
13232
13233    if !current_line.is_empty() {
13234        wrapped_text.push_str(&current_line);
13235    }
13236    wrapped_text
13237}
13238
13239#[test]
13240fn test_wrap_with_prefix() {
13241    assert_eq!(
13242        wrap_with_prefix(
13243            "# ".to_string(),
13244            "abcdefg".to_string(),
13245            4,
13246            NonZeroU32::new(4).unwrap()
13247        ),
13248        "# abcdefg"
13249    );
13250    assert_eq!(
13251        wrap_with_prefix(
13252            "".to_string(),
13253            "\thello world".to_string(),
13254            8,
13255            NonZeroU32::new(4).unwrap()
13256        ),
13257        "hello\nworld"
13258    );
13259    assert_eq!(
13260        wrap_with_prefix(
13261            "// ".to_string(),
13262            "xx \nyy zz aa bb cc".to_string(),
13263            12,
13264            NonZeroU32::new(4).unwrap()
13265        ),
13266        "// xx yy zz\n// aa bb cc"
13267    );
13268    assert_eq!(
13269        wrap_with_prefix(
13270            String::new(),
13271            "这是什么 \n 钢笔".to_string(),
13272            3,
13273            NonZeroU32::new(4).unwrap()
13274        ),
13275        "这是什\n么 钢\n"
13276    );
13277}
13278
13279fn hunks_for_selections(
13280    snapshot: &EditorSnapshot,
13281    selections: &[Selection<Point>],
13282) -> Vec<MultiBufferDiffHunk> {
13283    hunks_for_ranges(
13284        selections.iter().map(|selection| selection.range()),
13285        snapshot,
13286    )
13287}
13288
13289pub fn hunks_for_ranges(
13290    ranges: impl Iterator<Item = Range<Point>>,
13291    snapshot: &EditorSnapshot,
13292) -> Vec<MultiBufferDiffHunk> {
13293    let mut hunks = Vec::new();
13294    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13295        HashMap::default();
13296    for query_range in ranges {
13297        let query_rows =
13298            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13299        for hunk in snapshot.diff_map.diff_hunks_in_range(
13300            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13301            &snapshot.buffer_snapshot,
13302        ) {
13303            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13304            // when the caret is just above or just below the deleted hunk.
13305            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13306            let related_to_selection = if allow_adjacent {
13307                hunk.row_range.overlaps(&query_rows)
13308                    || hunk.row_range.start == query_rows.end
13309                    || hunk.row_range.end == query_rows.start
13310            } else {
13311                hunk.row_range.overlaps(&query_rows)
13312            };
13313            if related_to_selection {
13314                if !processed_buffer_rows
13315                    .entry(hunk.buffer_id)
13316                    .or_default()
13317                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13318                {
13319                    continue;
13320                }
13321                hunks.push(hunk);
13322            }
13323        }
13324    }
13325
13326    hunks
13327}
13328
13329pub trait CollaborationHub {
13330    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13331    fn user_participant_indices<'a>(
13332        &self,
13333        cx: &'a AppContext,
13334    ) -> &'a HashMap<u64, ParticipantIndex>;
13335    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13336}
13337
13338impl CollaborationHub for Model<Project> {
13339    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13340        self.read(cx).collaborators()
13341    }
13342
13343    fn user_participant_indices<'a>(
13344        &self,
13345        cx: &'a AppContext,
13346    ) -> &'a HashMap<u64, ParticipantIndex> {
13347        self.read(cx).user_store().read(cx).participant_indices()
13348    }
13349
13350    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13351        let this = self.read(cx);
13352        let user_ids = this.collaborators().values().map(|c| c.user_id);
13353        this.user_store().read_with(cx, |user_store, cx| {
13354            user_store.participant_names(user_ids, cx)
13355        })
13356    }
13357}
13358
13359pub trait SemanticsProvider {
13360    fn hover(
13361        &self,
13362        buffer: &Model<Buffer>,
13363        position: text::Anchor,
13364        cx: &mut AppContext,
13365    ) -> Option<Task<Vec<project::Hover>>>;
13366
13367    fn inlay_hints(
13368        &self,
13369        buffer_handle: Model<Buffer>,
13370        range: Range<text::Anchor>,
13371        cx: &mut AppContext,
13372    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13373
13374    fn resolve_inlay_hint(
13375        &self,
13376        hint: InlayHint,
13377        buffer_handle: Model<Buffer>,
13378        server_id: LanguageServerId,
13379        cx: &mut AppContext,
13380    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13381
13382    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13383
13384    fn document_highlights(
13385        &self,
13386        buffer: &Model<Buffer>,
13387        position: text::Anchor,
13388        cx: &mut AppContext,
13389    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13390
13391    fn definitions(
13392        &self,
13393        buffer: &Model<Buffer>,
13394        position: text::Anchor,
13395        kind: GotoDefinitionKind,
13396        cx: &mut AppContext,
13397    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13398
13399    fn range_for_rename(
13400        &self,
13401        buffer: &Model<Buffer>,
13402        position: text::Anchor,
13403        cx: &mut AppContext,
13404    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13405
13406    fn perform_rename(
13407        &self,
13408        buffer: &Model<Buffer>,
13409        position: text::Anchor,
13410        new_name: String,
13411        cx: &mut AppContext,
13412    ) -> Option<Task<Result<ProjectTransaction>>>;
13413}
13414
13415pub trait CompletionProvider {
13416    fn completions(
13417        &self,
13418        buffer: &Model<Buffer>,
13419        buffer_position: text::Anchor,
13420        trigger: CompletionContext,
13421        cx: &mut ViewContext<Editor>,
13422    ) -> Task<Result<Vec<Completion>>>;
13423
13424    fn resolve_completions(
13425        &self,
13426        buffer: Model<Buffer>,
13427        completion_indices: Vec<usize>,
13428        completions: Rc<RefCell<Box<[Completion]>>>,
13429        cx: &mut ViewContext<Editor>,
13430    ) -> Task<Result<bool>>;
13431
13432    fn apply_additional_edits_for_completion(
13433        &self,
13434        buffer: Model<Buffer>,
13435        completion: Completion,
13436        push_to_history: bool,
13437        cx: &mut ViewContext<Editor>,
13438    ) -> Task<Result<Option<language::Transaction>>>;
13439
13440    fn is_completion_trigger(
13441        &self,
13442        buffer: &Model<Buffer>,
13443        position: language::Anchor,
13444        text: &str,
13445        trigger_in_words: bool,
13446        cx: &mut ViewContext<Editor>,
13447    ) -> bool;
13448
13449    fn sort_completions(&self) -> bool {
13450        true
13451    }
13452}
13453
13454pub trait CodeActionProvider {
13455    fn code_actions(
13456        &self,
13457        buffer: &Model<Buffer>,
13458        range: Range<text::Anchor>,
13459        cx: &mut WindowContext,
13460    ) -> Task<Result<Vec<CodeAction>>>;
13461
13462    fn apply_code_action(
13463        &self,
13464        buffer_handle: Model<Buffer>,
13465        action: CodeAction,
13466        excerpt_id: ExcerptId,
13467        push_to_history: bool,
13468        cx: &mut WindowContext,
13469    ) -> Task<Result<ProjectTransaction>>;
13470}
13471
13472impl CodeActionProvider for Model<Project> {
13473    fn code_actions(
13474        &self,
13475        buffer: &Model<Buffer>,
13476        range: Range<text::Anchor>,
13477        cx: &mut WindowContext,
13478    ) -> Task<Result<Vec<CodeAction>>> {
13479        self.update(cx, |project, cx| {
13480            project.code_actions(buffer, range, None, cx)
13481        })
13482    }
13483
13484    fn apply_code_action(
13485        &self,
13486        buffer_handle: Model<Buffer>,
13487        action: CodeAction,
13488        _excerpt_id: ExcerptId,
13489        push_to_history: bool,
13490        cx: &mut WindowContext,
13491    ) -> Task<Result<ProjectTransaction>> {
13492        self.update(cx, |project, cx| {
13493            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13494        })
13495    }
13496}
13497
13498fn snippet_completions(
13499    project: &Project,
13500    buffer: &Model<Buffer>,
13501    buffer_position: text::Anchor,
13502    cx: &mut AppContext,
13503) -> Task<Result<Vec<Completion>>> {
13504    let language = buffer.read(cx).language_at(buffer_position);
13505    let language_name = language.as_ref().map(|language| language.lsp_id());
13506    let snippet_store = project.snippets().read(cx);
13507    let snippets = snippet_store.snippets_for(language_name, cx);
13508
13509    if snippets.is_empty() {
13510        return Task::ready(Ok(vec![]));
13511    }
13512    let snapshot = buffer.read(cx).text_snapshot();
13513    let chars: String = snapshot
13514        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13515        .collect();
13516
13517    let scope = language.map(|language| language.default_scope());
13518    let executor = cx.background_executor().clone();
13519
13520    cx.background_executor().spawn(async move {
13521        let classifier = CharClassifier::new(scope).for_completion(true);
13522        let mut last_word = chars
13523            .chars()
13524            .take_while(|c| classifier.is_word(*c))
13525            .collect::<String>();
13526        last_word = last_word.chars().rev().collect();
13527
13528        if last_word.is_empty() {
13529            return Ok(vec![]);
13530        }
13531
13532        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13533        let to_lsp = |point: &text::Anchor| {
13534            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13535            point_to_lsp(end)
13536        };
13537        let lsp_end = to_lsp(&buffer_position);
13538
13539        let candidates = snippets
13540            .iter()
13541            .enumerate()
13542            .flat_map(|(ix, snippet)| {
13543                snippet
13544                    .prefix
13545                    .iter()
13546                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13547            })
13548            .collect::<Vec<StringMatchCandidate>>();
13549
13550        let mut matches = fuzzy::match_strings(
13551            &candidates,
13552            &last_word,
13553            last_word.chars().any(|c| c.is_uppercase()),
13554            100,
13555            &Default::default(),
13556            executor,
13557        )
13558        .await;
13559
13560        // Remove all candidates where the query's start does not match the start of any word in the candidate
13561        if let Some(query_start) = last_word.chars().next() {
13562            matches.retain(|string_match| {
13563                split_words(&string_match.string).any(|word| {
13564                    // Check that the first codepoint of the word as lowercase matches the first
13565                    // codepoint of the query as lowercase
13566                    word.chars()
13567                        .flat_map(|codepoint| codepoint.to_lowercase())
13568                        .zip(query_start.to_lowercase())
13569                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13570                })
13571            });
13572        }
13573
13574        let matched_strings = matches
13575            .into_iter()
13576            .map(|m| m.string)
13577            .collect::<HashSet<_>>();
13578
13579        let result: Vec<Completion> = snippets
13580            .into_iter()
13581            .filter_map(|snippet| {
13582                let matching_prefix = snippet
13583                    .prefix
13584                    .iter()
13585                    .find(|prefix| matched_strings.contains(*prefix))?;
13586                let start = as_offset - last_word.len();
13587                let start = snapshot.anchor_before(start);
13588                let range = start..buffer_position;
13589                let lsp_start = to_lsp(&start);
13590                let lsp_range = lsp::Range {
13591                    start: lsp_start,
13592                    end: lsp_end,
13593                };
13594                Some(Completion {
13595                    old_range: range,
13596                    new_text: snippet.body.clone(),
13597                    label: CodeLabel {
13598                        text: matching_prefix.clone(),
13599                        runs: vec![],
13600                        filter_range: 0..matching_prefix.len(),
13601                    },
13602                    server_id: LanguageServerId(usize::MAX),
13603                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13604                    lsp_completion: lsp::CompletionItem {
13605                        label: snippet.prefix.first().unwrap().clone(),
13606                        kind: Some(CompletionItemKind::SNIPPET),
13607                        label_details: snippet.description.as_ref().map(|description| {
13608                            lsp::CompletionItemLabelDetails {
13609                                detail: Some(description.clone()),
13610                                description: None,
13611                            }
13612                        }),
13613                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13614                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13615                            lsp::InsertReplaceEdit {
13616                                new_text: snippet.body.clone(),
13617                                insert: lsp_range,
13618                                replace: lsp_range,
13619                            },
13620                        )),
13621                        filter_text: Some(snippet.body.clone()),
13622                        sort_text: Some(char::MAX.to_string()),
13623                        ..Default::default()
13624                    },
13625                    confirm: None,
13626                })
13627            })
13628            .collect();
13629
13630        Ok(result)
13631    })
13632}
13633
13634impl CompletionProvider for Model<Project> {
13635    fn completions(
13636        &self,
13637        buffer: &Model<Buffer>,
13638        buffer_position: text::Anchor,
13639        options: CompletionContext,
13640        cx: &mut ViewContext<Editor>,
13641    ) -> Task<Result<Vec<Completion>>> {
13642        self.update(cx, |project, cx| {
13643            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13644            let project_completions = project.completions(buffer, buffer_position, options, cx);
13645            cx.background_executor().spawn(async move {
13646                let mut completions = project_completions.await?;
13647                let snippets_completions = snippets.await?;
13648                completions.extend(snippets_completions);
13649                Ok(completions)
13650            })
13651        })
13652    }
13653
13654    fn resolve_completions(
13655        &self,
13656        buffer: Model<Buffer>,
13657        completion_indices: Vec<usize>,
13658        completions: Rc<RefCell<Box<[Completion]>>>,
13659        cx: &mut ViewContext<Editor>,
13660    ) -> Task<Result<bool>> {
13661        self.update(cx, |project, cx| {
13662            project.resolve_completions(buffer, completion_indices, completions, cx)
13663        })
13664    }
13665
13666    fn apply_additional_edits_for_completion(
13667        &self,
13668        buffer: Model<Buffer>,
13669        completion: Completion,
13670        push_to_history: bool,
13671        cx: &mut ViewContext<Editor>,
13672    ) -> Task<Result<Option<language::Transaction>>> {
13673        self.update(cx, |project, cx| {
13674            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13675        })
13676    }
13677
13678    fn is_completion_trigger(
13679        &self,
13680        buffer: &Model<Buffer>,
13681        position: language::Anchor,
13682        text: &str,
13683        trigger_in_words: bool,
13684        cx: &mut ViewContext<Editor>,
13685    ) -> bool {
13686        let mut chars = text.chars();
13687        let char = if let Some(char) = chars.next() {
13688            char
13689        } else {
13690            return false;
13691        };
13692        if chars.next().is_some() {
13693            return false;
13694        }
13695
13696        let buffer = buffer.read(cx);
13697        let snapshot = buffer.snapshot();
13698        if !snapshot.settings_at(position, cx).show_completions_on_input {
13699            return false;
13700        }
13701        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13702        if trigger_in_words && classifier.is_word(char) {
13703            return true;
13704        }
13705
13706        buffer.completion_triggers().contains(text)
13707    }
13708}
13709
13710impl SemanticsProvider for Model<Project> {
13711    fn hover(
13712        &self,
13713        buffer: &Model<Buffer>,
13714        position: text::Anchor,
13715        cx: &mut AppContext,
13716    ) -> Option<Task<Vec<project::Hover>>> {
13717        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13718    }
13719
13720    fn document_highlights(
13721        &self,
13722        buffer: &Model<Buffer>,
13723        position: text::Anchor,
13724        cx: &mut AppContext,
13725    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13726        Some(self.update(cx, |project, cx| {
13727            project.document_highlights(buffer, position, cx)
13728        }))
13729    }
13730
13731    fn definitions(
13732        &self,
13733        buffer: &Model<Buffer>,
13734        position: text::Anchor,
13735        kind: GotoDefinitionKind,
13736        cx: &mut AppContext,
13737    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13738        Some(self.update(cx, |project, cx| match kind {
13739            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13740            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13741            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13742            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13743        }))
13744    }
13745
13746    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13747        // TODO: make this work for remote projects
13748        self.read(cx)
13749            .language_servers_for_local_buffer(buffer.read(cx), cx)
13750            .any(
13751                |(_, server)| match server.capabilities().inlay_hint_provider {
13752                    Some(lsp::OneOf::Left(enabled)) => enabled,
13753                    Some(lsp::OneOf::Right(_)) => true,
13754                    None => false,
13755                },
13756            )
13757    }
13758
13759    fn inlay_hints(
13760        &self,
13761        buffer_handle: Model<Buffer>,
13762        range: Range<text::Anchor>,
13763        cx: &mut AppContext,
13764    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13765        Some(self.update(cx, |project, cx| {
13766            project.inlay_hints(buffer_handle, range, cx)
13767        }))
13768    }
13769
13770    fn resolve_inlay_hint(
13771        &self,
13772        hint: InlayHint,
13773        buffer_handle: Model<Buffer>,
13774        server_id: LanguageServerId,
13775        cx: &mut AppContext,
13776    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13777        Some(self.update(cx, |project, cx| {
13778            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13779        }))
13780    }
13781
13782    fn range_for_rename(
13783        &self,
13784        buffer: &Model<Buffer>,
13785        position: text::Anchor,
13786        cx: &mut AppContext,
13787    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13788        Some(self.update(cx, |project, cx| {
13789            project.prepare_rename(buffer.clone(), position, cx)
13790        }))
13791    }
13792
13793    fn perform_rename(
13794        &self,
13795        buffer: &Model<Buffer>,
13796        position: text::Anchor,
13797        new_name: String,
13798        cx: &mut AppContext,
13799    ) -> Option<Task<Result<ProjectTransaction>>> {
13800        Some(self.update(cx, |project, cx| {
13801            project.perform_rename(buffer.clone(), position, new_name, cx)
13802        }))
13803    }
13804}
13805
13806fn inlay_hint_settings(
13807    location: Anchor,
13808    snapshot: &MultiBufferSnapshot,
13809    cx: &mut ViewContext<'_, Editor>,
13810) -> InlayHintSettings {
13811    let file = snapshot.file_at(location);
13812    let language = snapshot.language_at(location).map(|l| l.name());
13813    language_settings(language, file, cx).inlay_hints
13814}
13815
13816fn consume_contiguous_rows(
13817    contiguous_row_selections: &mut Vec<Selection<Point>>,
13818    selection: &Selection<Point>,
13819    display_map: &DisplaySnapshot,
13820    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13821) -> (MultiBufferRow, MultiBufferRow) {
13822    contiguous_row_selections.push(selection.clone());
13823    let start_row = MultiBufferRow(selection.start.row);
13824    let mut end_row = ending_row(selection, display_map);
13825
13826    while let Some(next_selection) = selections.peek() {
13827        if next_selection.start.row <= end_row.0 {
13828            end_row = ending_row(next_selection, display_map);
13829            contiguous_row_selections.push(selections.next().unwrap().clone());
13830        } else {
13831            break;
13832        }
13833    }
13834    (start_row, end_row)
13835}
13836
13837fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13838    if next_selection.end.column > 0 || next_selection.is_empty() {
13839        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13840    } else {
13841        MultiBufferRow(next_selection.end.row)
13842    }
13843}
13844
13845impl EditorSnapshot {
13846    pub fn remote_selections_in_range<'a>(
13847        &'a self,
13848        range: &'a Range<Anchor>,
13849        collaboration_hub: &dyn CollaborationHub,
13850        cx: &'a AppContext,
13851    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13852        let participant_names = collaboration_hub.user_names(cx);
13853        let participant_indices = collaboration_hub.user_participant_indices(cx);
13854        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13855        let collaborators_by_replica_id = collaborators_by_peer_id
13856            .iter()
13857            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13858            .collect::<HashMap<_, _>>();
13859        self.buffer_snapshot
13860            .selections_in_range(range, false)
13861            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13862                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13863                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13864                let user_name = participant_names.get(&collaborator.user_id).cloned();
13865                Some(RemoteSelection {
13866                    replica_id,
13867                    selection,
13868                    cursor_shape,
13869                    line_mode,
13870                    participant_index,
13871                    peer_id: collaborator.peer_id,
13872                    user_name,
13873                })
13874            })
13875    }
13876
13877    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13878        self.display_snapshot.buffer_snapshot.language_at(position)
13879    }
13880
13881    pub fn is_focused(&self) -> bool {
13882        self.is_focused
13883    }
13884
13885    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13886        self.placeholder_text.as_ref()
13887    }
13888
13889    pub fn scroll_position(&self) -> gpui::Point<f32> {
13890        self.scroll_anchor.scroll_position(&self.display_snapshot)
13891    }
13892
13893    fn gutter_dimensions(
13894        &self,
13895        font_id: FontId,
13896        font_size: Pixels,
13897        em_width: Pixels,
13898        em_advance: Pixels,
13899        max_line_number_width: Pixels,
13900        cx: &AppContext,
13901    ) -> GutterDimensions {
13902        if !self.show_gutter {
13903            return GutterDimensions::default();
13904        }
13905        let descent = cx.text_system().descent(font_id, font_size);
13906
13907        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13908            matches!(
13909                ProjectSettings::get_global(cx).git.git_gutter,
13910                Some(GitGutterSetting::TrackedFiles)
13911            )
13912        });
13913        let gutter_settings = EditorSettings::get_global(cx).gutter;
13914        let show_line_numbers = self
13915            .show_line_numbers
13916            .unwrap_or(gutter_settings.line_numbers);
13917        let line_gutter_width = if show_line_numbers {
13918            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13919            let min_width_for_number_on_gutter = em_advance * 4.0;
13920            max_line_number_width.max(min_width_for_number_on_gutter)
13921        } else {
13922            0.0.into()
13923        };
13924
13925        let show_code_actions = self
13926            .show_code_actions
13927            .unwrap_or(gutter_settings.code_actions);
13928
13929        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13930
13931        let git_blame_entries_width =
13932            self.git_blame_gutter_max_author_length
13933                .map(|max_author_length| {
13934                    // Length of the author name, but also space for the commit hash,
13935                    // the spacing and the timestamp.
13936                    let max_char_count = max_author_length
13937                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13938                        + 7 // length of commit sha
13939                        + 14 // length of max relative timestamp ("60 minutes ago")
13940                        + 4; // gaps and margins
13941
13942                    em_advance * max_char_count
13943                });
13944
13945        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13946        left_padding += if show_code_actions || show_runnables {
13947            em_width * 3.0
13948        } else if show_git_gutter && show_line_numbers {
13949            em_width * 2.0
13950        } else if show_git_gutter || show_line_numbers {
13951            em_width
13952        } else {
13953            px(0.)
13954        };
13955
13956        let right_padding = if gutter_settings.folds && show_line_numbers {
13957            em_width * 4.0
13958        } else if gutter_settings.folds {
13959            em_width * 3.0
13960        } else if show_line_numbers {
13961            em_width
13962        } else {
13963            px(0.)
13964        };
13965
13966        GutterDimensions {
13967            left_padding,
13968            right_padding,
13969            width: line_gutter_width + left_padding + right_padding,
13970            margin: -descent,
13971            git_blame_entries_width,
13972        }
13973    }
13974
13975    pub fn render_crease_toggle(
13976        &self,
13977        buffer_row: MultiBufferRow,
13978        row_contains_cursor: bool,
13979        editor: View<Editor>,
13980        cx: &mut WindowContext,
13981    ) -> Option<AnyElement> {
13982        let folded = self.is_line_folded(buffer_row);
13983        let mut is_foldable = false;
13984
13985        if let Some(crease) = self
13986            .crease_snapshot
13987            .query_row(buffer_row, &self.buffer_snapshot)
13988        {
13989            is_foldable = true;
13990            match crease {
13991                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13992                    if let Some(render_toggle) = render_toggle {
13993                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13994                            if folded {
13995                                editor.update(cx, |editor, cx| {
13996                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13997                                });
13998                            } else {
13999                                editor.update(cx, |editor, cx| {
14000                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14001                                });
14002                            }
14003                        });
14004                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14005                    }
14006                }
14007            }
14008        }
14009
14010        is_foldable |= self.starts_indent(buffer_row);
14011
14012        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14013            Some(
14014                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14015                    .toggle_state(folded)
14016                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14017                        if folded {
14018                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14019                        } else {
14020                            this.fold_at(&FoldAt { buffer_row }, cx);
14021                        }
14022                    }))
14023                    .into_any_element(),
14024            )
14025        } else {
14026            None
14027        }
14028    }
14029
14030    pub fn render_crease_trailer(
14031        &self,
14032        buffer_row: MultiBufferRow,
14033        cx: &mut WindowContext,
14034    ) -> Option<AnyElement> {
14035        let folded = self.is_line_folded(buffer_row);
14036        if let Crease::Inline { render_trailer, .. } = self
14037            .crease_snapshot
14038            .query_row(buffer_row, &self.buffer_snapshot)?
14039        {
14040            let render_trailer = render_trailer.as_ref()?;
14041            Some(render_trailer(buffer_row, folded, cx))
14042        } else {
14043            None
14044        }
14045    }
14046}
14047
14048impl Deref for EditorSnapshot {
14049    type Target = DisplaySnapshot;
14050
14051    fn deref(&self) -> &Self::Target {
14052        &self.display_snapshot
14053    }
14054}
14055
14056#[derive(Clone, Debug, PartialEq, Eq)]
14057pub enum EditorEvent {
14058    InputIgnored {
14059        text: Arc<str>,
14060    },
14061    InputHandled {
14062        utf16_range_to_replace: Option<Range<isize>>,
14063        text: Arc<str>,
14064    },
14065    ExcerptsAdded {
14066        buffer: Model<Buffer>,
14067        predecessor: ExcerptId,
14068        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14069    },
14070    ExcerptsRemoved {
14071        ids: Vec<ExcerptId>,
14072    },
14073    BufferFoldToggled {
14074        ids: Vec<ExcerptId>,
14075        folded: bool,
14076    },
14077    ExcerptsEdited {
14078        ids: Vec<ExcerptId>,
14079    },
14080    ExcerptsExpanded {
14081        ids: Vec<ExcerptId>,
14082    },
14083    BufferEdited,
14084    Edited {
14085        transaction_id: clock::Lamport,
14086    },
14087    Reparsed(BufferId),
14088    Focused,
14089    FocusedIn,
14090    Blurred,
14091    DirtyChanged,
14092    Saved,
14093    TitleChanged,
14094    DiffBaseChanged,
14095    SelectionsChanged {
14096        local: bool,
14097    },
14098    ScrollPositionChanged {
14099        local: bool,
14100        autoscroll: bool,
14101    },
14102    Closed,
14103    TransactionUndone {
14104        transaction_id: clock::Lamport,
14105    },
14106    TransactionBegun {
14107        transaction_id: clock::Lamport,
14108    },
14109    Reloaded,
14110    CursorShapeChanged,
14111}
14112
14113impl EventEmitter<EditorEvent> for Editor {}
14114
14115impl FocusableView for Editor {
14116    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14117        self.focus_handle.clone()
14118    }
14119}
14120
14121impl Render for Editor {
14122    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14123        let settings = ThemeSettings::get_global(cx);
14124
14125        let mut text_style = match self.mode {
14126            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14127                color: cx.theme().colors().editor_foreground,
14128                font_family: settings.ui_font.family.clone(),
14129                font_features: settings.ui_font.features.clone(),
14130                font_fallbacks: settings.ui_font.fallbacks.clone(),
14131                font_size: rems(0.875).into(),
14132                font_weight: settings.ui_font.weight,
14133                line_height: relative(settings.buffer_line_height.value()),
14134                ..Default::default()
14135            },
14136            EditorMode::Full => TextStyle {
14137                color: cx.theme().colors().editor_foreground,
14138                font_family: settings.buffer_font.family.clone(),
14139                font_features: settings.buffer_font.features.clone(),
14140                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14141                font_size: settings.buffer_font_size(cx).into(),
14142                font_weight: settings.buffer_font.weight,
14143                line_height: relative(settings.buffer_line_height.value()),
14144                ..Default::default()
14145            },
14146        };
14147        if let Some(text_style_refinement) = &self.text_style_refinement {
14148            text_style.refine(text_style_refinement)
14149        }
14150
14151        let background = match self.mode {
14152            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14153            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14154            EditorMode::Full => cx.theme().colors().editor_background,
14155        };
14156
14157        EditorElement::new(
14158            cx.view(),
14159            EditorStyle {
14160                background,
14161                local_player: cx.theme().players().local(),
14162                text: text_style,
14163                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14164                syntax: cx.theme().syntax().clone(),
14165                status: cx.theme().status().clone(),
14166                inlay_hints_style: make_inlay_hints_style(cx),
14167                inline_completion_styles: make_suggestion_styles(cx),
14168                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14169            },
14170        )
14171    }
14172}
14173
14174impl ViewInputHandler for Editor {
14175    fn text_for_range(
14176        &mut self,
14177        range_utf16: Range<usize>,
14178        adjusted_range: &mut Option<Range<usize>>,
14179        cx: &mut ViewContext<Self>,
14180    ) -> Option<String> {
14181        let snapshot = self.buffer.read(cx).read(cx);
14182        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14183        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14184        if (start.0..end.0) != range_utf16 {
14185            adjusted_range.replace(start.0..end.0);
14186        }
14187        Some(snapshot.text_for_range(start..end).collect())
14188    }
14189
14190    fn selected_text_range(
14191        &mut self,
14192        ignore_disabled_input: bool,
14193        cx: &mut ViewContext<Self>,
14194    ) -> Option<UTF16Selection> {
14195        // Prevent the IME menu from appearing when holding down an alphabetic key
14196        // while input is disabled.
14197        if !ignore_disabled_input && !self.input_enabled {
14198            return None;
14199        }
14200
14201        let selection = self.selections.newest::<OffsetUtf16>(cx);
14202        let range = selection.range();
14203
14204        Some(UTF16Selection {
14205            range: range.start.0..range.end.0,
14206            reversed: selection.reversed,
14207        })
14208    }
14209
14210    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14211        let snapshot = self.buffer.read(cx).read(cx);
14212        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14213        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14214    }
14215
14216    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14217        self.clear_highlights::<InputComposition>(cx);
14218        self.ime_transaction.take();
14219    }
14220
14221    fn replace_text_in_range(
14222        &mut self,
14223        range_utf16: Option<Range<usize>>,
14224        text: &str,
14225        cx: &mut ViewContext<Self>,
14226    ) {
14227        if !self.input_enabled {
14228            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14229            return;
14230        }
14231
14232        self.transact(cx, |this, cx| {
14233            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14234                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14235                Some(this.selection_replacement_ranges(range_utf16, cx))
14236            } else {
14237                this.marked_text_ranges(cx)
14238            };
14239
14240            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14241                let newest_selection_id = this.selections.newest_anchor().id;
14242                this.selections
14243                    .all::<OffsetUtf16>(cx)
14244                    .iter()
14245                    .zip(ranges_to_replace.iter())
14246                    .find_map(|(selection, range)| {
14247                        if selection.id == newest_selection_id {
14248                            Some(
14249                                (range.start.0 as isize - selection.head().0 as isize)
14250                                    ..(range.end.0 as isize - selection.head().0 as isize),
14251                            )
14252                        } else {
14253                            None
14254                        }
14255                    })
14256            });
14257
14258            cx.emit(EditorEvent::InputHandled {
14259                utf16_range_to_replace: range_to_replace,
14260                text: text.into(),
14261            });
14262
14263            if let Some(new_selected_ranges) = new_selected_ranges {
14264                this.change_selections(None, cx, |selections| {
14265                    selections.select_ranges(new_selected_ranges)
14266                });
14267                this.backspace(&Default::default(), cx);
14268            }
14269
14270            this.handle_input(text, cx);
14271        });
14272
14273        if let Some(transaction) = self.ime_transaction {
14274            self.buffer.update(cx, |buffer, cx| {
14275                buffer.group_until_transaction(transaction, cx);
14276            });
14277        }
14278
14279        self.unmark_text(cx);
14280    }
14281
14282    fn replace_and_mark_text_in_range(
14283        &mut self,
14284        range_utf16: Option<Range<usize>>,
14285        text: &str,
14286        new_selected_range_utf16: Option<Range<usize>>,
14287        cx: &mut ViewContext<Self>,
14288    ) {
14289        if !self.input_enabled {
14290            return;
14291        }
14292
14293        let transaction = self.transact(cx, |this, cx| {
14294            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14295                let snapshot = this.buffer.read(cx).read(cx);
14296                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14297                    for marked_range in &mut marked_ranges {
14298                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14299                        marked_range.start.0 += relative_range_utf16.start;
14300                        marked_range.start =
14301                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14302                        marked_range.end =
14303                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14304                    }
14305                }
14306                Some(marked_ranges)
14307            } else if let Some(range_utf16) = range_utf16 {
14308                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14309                Some(this.selection_replacement_ranges(range_utf16, cx))
14310            } else {
14311                None
14312            };
14313
14314            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14315                let newest_selection_id = this.selections.newest_anchor().id;
14316                this.selections
14317                    .all::<OffsetUtf16>(cx)
14318                    .iter()
14319                    .zip(ranges_to_replace.iter())
14320                    .find_map(|(selection, range)| {
14321                        if selection.id == newest_selection_id {
14322                            Some(
14323                                (range.start.0 as isize - selection.head().0 as isize)
14324                                    ..(range.end.0 as isize - selection.head().0 as isize),
14325                            )
14326                        } else {
14327                            None
14328                        }
14329                    })
14330            });
14331
14332            cx.emit(EditorEvent::InputHandled {
14333                utf16_range_to_replace: range_to_replace,
14334                text: text.into(),
14335            });
14336
14337            if let Some(ranges) = ranges_to_replace {
14338                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14339            }
14340
14341            let marked_ranges = {
14342                let snapshot = this.buffer.read(cx).read(cx);
14343                this.selections
14344                    .disjoint_anchors()
14345                    .iter()
14346                    .map(|selection| {
14347                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14348                    })
14349                    .collect::<Vec<_>>()
14350            };
14351
14352            if text.is_empty() {
14353                this.unmark_text(cx);
14354            } else {
14355                this.highlight_text::<InputComposition>(
14356                    marked_ranges.clone(),
14357                    HighlightStyle {
14358                        underline: Some(UnderlineStyle {
14359                            thickness: px(1.),
14360                            color: None,
14361                            wavy: false,
14362                        }),
14363                        ..Default::default()
14364                    },
14365                    cx,
14366                );
14367            }
14368
14369            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14370            let use_autoclose = this.use_autoclose;
14371            let use_auto_surround = this.use_auto_surround;
14372            this.set_use_autoclose(false);
14373            this.set_use_auto_surround(false);
14374            this.handle_input(text, cx);
14375            this.set_use_autoclose(use_autoclose);
14376            this.set_use_auto_surround(use_auto_surround);
14377
14378            if let Some(new_selected_range) = new_selected_range_utf16 {
14379                let snapshot = this.buffer.read(cx).read(cx);
14380                let new_selected_ranges = marked_ranges
14381                    .into_iter()
14382                    .map(|marked_range| {
14383                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14384                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14385                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14386                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14387                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14388                    })
14389                    .collect::<Vec<_>>();
14390
14391                drop(snapshot);
14392                this.change_selections(None, cx, |selections| {
14393                    selections.select_ranges(new_selected_ranges)
14394                });
14395            }
14396        });
14397
14398        self.ime_transaction = self.ime_transaction.or(transaction);
14399        if let Some(transaction) = self.ime_transaction {
14400            self.buffer.update(cx, |buffer, cx| {
14401                buffer.group_until_transaction(transaction, cx);
14402            });
14403        }
14404
14405        if self.text_highlights::<InputComposition>(cx).is_none() {
14406            self.ime_transaction.take();
14407        }
14408    }
14409
14410    fn bounds_for_range(
14411        &mut self,
14412        range_utf16: Range<usize>,
14413        element_bounds: gpui::Bounds<Pixels>,
14414        cx: &mut ViewContext<Self>,
14415    ) -> Option<gpui::Bounds<Pixels>> {
14416        let text_layout_details = self.text_layout_details(cx);
14417        let gpui::Point {
14418            x: em_width,
14419            y: line_height,
14420        } = self.character_size(cx);
14421
14422        let snapshot = self.snapshot(cx);
14423        let scroll_position = snapshot.scroll_position();
14424        let scroll_left = scroll_position.x * em_width;
14425
14426        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14427        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14428            + self.gutter_dimensions.width
14429            + self.gutter_dimensions.margin;
14430        let y = line_height * (start.row().as_f32() - scroll_position.y);
14431
14432        Some(Bounds {
14433            origin: element_bounds.origin + point(x, y),
14434            size: size(em_width, line_height),
14435        })
14436    }
14437}
14438
14439trait SelectionExt {
14440    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14441    fn spanned_rows(
14442        &self,
14443        include_end_if_at_line_start: bool,
14444        map: &DisplaySnapshot,
14445    ) -> Range<MultiBufferRow>;
14446}
14447
14448impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14449    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14450        let start = self
14451            .start
14452            .to_point(&map.buffer_snapshot)
14453            .to_display_point(map);
14454        let end = self
14455            .end
14456            .to_point(&map.buffer_snapshot)
14457            .to_display_point(map);
14458        if self.reversed {
14459            end..start
14460        } else {
14461            start..end
14462        }
14463    }
14464
14465    fn spanned_rows(
14466        &self,
14467        include_end_if_at_line_start: bool,
14468        map: &DisplaySnapshot,
14469    ) -> Range<MultiBufferRow> {
14470        let start = self.start.to_point(&map.buffer_snapshot);
14471        let mut end = self.end.to_point(&map.buffer_snapshot);
14472        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14473            end.row -= 1;
14474        }
14475
14476        let buffer_start = map.prev_line_boundary(start).0;
14477        let buffer_end = map.next_line_boundary(end).0;
14478        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14479    }
14480}
14481
14482impl<T: InvalidationRegion> InvalidationStack<T> {
14483    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14484    where
14485        S: Clone + ToOffset,
14486    {
14487        while let Some(region) = self.last() {
14488            let all_selections_inside_invalidation_ranges =
14489                if selections.len() == region.ranges().len() {
14490                    selections
14491                        .iter()
14492                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14493                        .all(|(selection, invalidation_range)| {
14494                            let head = selection.head().to_offset(buffer);
14495                            invalidation_range.start <= head && invalidation_range.end >= head
14496                        })
14497                } else {
14498                    false
14499                };
14500
14501            if all_selections_inside_invalidation_ranges {
14502                break;
14503            } else {
14504                self.pop();
14505            }
14506        }
14507    }
14508}
14509
14510impl<T> Default for InvalidationStack<T> {
14511    fn default() -> Self {
14512        Self(Default::default())
14513    }
14514}
14515
14516impl<T> Deref for InvalidationStack<T> {
14517    type Target = Vec<T>;
14518
14519    fn deref(&self) -> &Self::Target {
14520        &self.0
14521    }
14522}
14523
14524impl<T> DerefMut for InvalidationStack<T> {
14525    fn deref_mut(&mut self) -> &mut Self::Target {
14526        &mut self.0
14527    }
14528}
14529
14530impl InvalidationRegion for SnippetState {
14531    fn ranges(&self) -> &[Range<Anchor>] {
14532        &self.ranges[self.active_index]
14533    }
14534}
14535
14536pub fn diagnostic_block_renderer(
14537    diagnostic: Diagnostic,
14538    max_message_rows: Option<u8>,
14539    allow_closing: bool,
14540    _is_valid: bool,
14541) -> RenderBlock {
14542    let (text_without_backticks, code_ranges) =
14543        highlight_diagnostic_message(&diagnostic, max_message_rows);
14544
14545    Arc::new(move |cx: &mut BlockContext| {
14546        let group_id: SharedString = cx.block_id.to_string().into();
14547
14548        let mut text_style = cx.text_style().clone();
14549        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14550        let theme_settings = ThemeSettings::get_global(cx);
14551        text_style.font_family = theme_settings.buffer_font.family.clone();
14552        text_style.font_style = theme_settings.buffer_font.style;
14553        text_style.font_features = theme_settings.buffer_font.features.clone();
14554        text_style.font_weight = theme_settings.buffer_font.weight;
14555
14556        let multi_line_diagnostic = diagnostic.message.contains('\n');
14557
14558        let buttons = |diagnostic: &Diagnostic| {
14559            if multi_line_diagnostic {
14560                v_flex()
14561            } else {
14562                h_flex()
14563            }
14564            .when(allow_closing, |div| {
14565                div.children(diagnostic.is_primary.then(|| {
14566                    IconButton::new("close-block", IconName::XCircle)
14567                        .icon_color(Color::Muted)
14568                        .size(ButtonSize::Compact)
14569                        .style(ButtonStyle::Transparent)
14570                        .visible_on_hover(group_id.clone())
14571                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14572                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14573                }))
14574            })
14575            .child(
14576                IconButton::new("copy-block", IconName::Copy)
14577                    .icon_color(Color::Muted)
14578                    .size(ButtonSize::Compact)
14579                    .style(ButtonStyle::Transparent)
14580                    .visible_on_hover(group_id.clone())
14581                    .on_click({
14582                        let message = diagnostic.message.clone();
14583                        move |_click, cx| {
14584                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14585                        }
14586                    })
14587                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14588            )
14589        };
14590
14591        let icon_size = buttons(&diagnostic)
14592            .into_any_element()
14593            .layout_as_root(AvailableSpace::min_size(), cx);
14594
14595        h_flex()
14596            .id(cx.block_id)
14597            .group(group_id.clone())
14598            .relative()
14599            .size_full()
14600            .block_mouse_down()
14601            .pl(cx.gutter_dimensions.width)
14602            .w(cx.max_width - cx.gutter_dimensions.full_width())
14603            .child(
14604                div()
14605                    .flex()
14606                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14607                    .flex_shrink(),
14608            )
14609            .child(buttons(&diagnostic))
14610            .child(div().flex().flex_shrink_0().child(
14611                StyledText::new(text_without_backticks.clone()).with_highlights(
14612                    &text_style,
14613                    code_ranges.iter().map(|range| {
14614                        (
14615                            range.clone(),
14616                            HighlightStyle {
14617                                font_weight: Some(FontWeight::BOLD),
14618                                ..Default::default()
14619                            },
14620                        )
14621                    }),
14622                ),
14623            ))
14624            .into_any_element()
14625    })
14626}
14627
14628fn inline_completion_edit_text(
14629    editor_snapshot: &EditorSnapshot,
14630    edits: &Vec<(Range<Anchor>, String)>,
14631    include_deletions: bool,
14632    cx: &WindowContext,
14633) -> InlineCompletionText {
14634    let edit_start = edits
14635        .first()
14636        .unwrap()
14637        .0
14638        .start
14639        .to_display_point(editor_snapshot);
14640
14641    let mut text = String::new();
14642    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14643    let mut highlights = Vec::new();
14644    for (old_range, new_text) in edits {
14645        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14646        text.extend(
14647            editor_snapshot
14648                .buffer_snapshot
14649                .chunks(offset..old_offset_range.start, false)
14650                .map(|chunk| chunk.text),
14651        );
14652        offset = old_offset_range.end;
14653
14654        let start = text.len();
14655        let color = if include_deletions && new_text.is_empty() {
14656            text.extend(
14657                editor_snapshot
14658                    .buffer_snapshot
14659                    .chunks(old_offset_range.start..offset, false)
14660                    .map(|chunk| chunk.text),
14661            );
14662            cx.theme().status().deleted_background
14663        } else {
14664            text.push_str(new_text);
14665            cx.theme().status().created_background
14666        };
14667        let end = text.len();
14668
14669        highlights.push((
14670            start..end,
14671            HighlightStyle {
14672                background_color: Some(color),
14673                ..Default::default()
14674            },
14675        ));
14676    }
14677
14678    let edit_end = edits
14679        .last()
14680        .unwrap()
14681        .0
14682        .end
14683        .to_display_point(editor_snapshot);
14684    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14685        .to_offset(editor_snapshot, Bias::Right);
14686    text.extend(
14687        editor_snapshot
14688            .buffer_snapshot
14689            .chunks(offset..end_of_line, false)
14690            .map(|chunk| chunk.text),
14691    );
14692
14693    InlineCompletionText::Edit {
14694        text: text.into(),
14695        highlights,
14696    }
14697}
14698
14699pub fn highlight_diagnostic_message(
14700    diagnostic: &Diagnostic,
14701    mut max_message_rows: Option<u8>,
14702) -> (SharedString, Vec<Range<usize>>) {
14703    let mut text_without_backticks = String::new();
14704    let mut code_ranges = Vec::new();
14705
14706    if let Some(source) = &diagnostic.source {
14707        text_without_backticks.push_str(source);
14708        code_ranges.push(0..source.len());
14709        text_without_backticks.push_str(": ");
14710    }
14711
14712    let mut prev_offset = 0;
14713    let mut in_code_block = false;
14714    let has_row_limit = max_message_rows.is_some();
14715    let mut newline_indices = diagnostic
14716        .message
14717        .match_indices('\n')
14718        .filter(|_| has_row_limit)
14719        .map(|(ix, _)| ix)
14720        .fuse()
14721        .peekable();
14722
14723    for (quote_ix, _) in diagnostic
14724        .message
14725        .match_indices('`')
14726        .chain([(diagnostic.message.len(), "")])
14727    {
14728        let mut first_newline_ix = None;
14729        let mut last_newline_ix = None;
14730        while let Some(newline_ix) = newline_indices.peek() {
14731            if *newline_ix < quote_ix {
14732                if first_newline_ix.is_none() {
14733                    first_newline_ix = Some(*newline_ix);
14734                }
14735                last_newline_ix = Some(*newline_ix);
14736
14737                if let Some(rows_left) = &mut max_message_rows {
14738                    if *rows_left == 0 {
14739                        break;
14740                    } else {
14741                        *rows_left -= 1;
14742                    }
14743                }
14744                let _ = newline_indices.next();
14745            } else {
14746                break;
14747            }
14748        }
14749        let prev_len = text_without_backticks.len();
14750        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14751        text_without_backticks.push_str(new_text);
14752        if in_code_block {
14753            code_ranges.push(prev_len..text_without_backticks.len());
14754        }
14755        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14756        in_code_block = !in_code_block;
14757        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14758            text_without_backticks.push_str("...");
14759            break;
14760        }
14761    }
14762
14763    (text_without_backticks.into(), code_ranges)
14764}
14765
14766fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14767    match severity {
14768        DiagnosticSeverity::ERROR => colors.error,
14769        DiagnosticSeverity::WARNING => colors.warning,
14770        DiagnosticSeverity::INFORMATION => colors.info,
14771        DiagnosticSeverity::HINT => colors.info,
14772        _ => colors.ignored,
14773    }
14774}
14775
14776pub fn styled_runs_for_code_label<'a>(
14777    label: &'a CodeLabel,
14778    syntax_theme: &'a theme::SyntaxTheme,
14779) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14780    let fade_out = HighlightStyle {
14781        fade_out: Some(0.35),
14782        ..Default::default()
14783    };
14784
14785    let mut prev_end = label.filter_range.end;
14786    label
14787        .runs
14788        .iter()
14789        .enumerate()
14790        .flat_map(move |(ix, (range, highlight_id))| {
14791            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14792                style
14793            } else {
14794                return Default::default();
14795            };
14796            let mut muted_style = style;
14797            muted_style.highlight(fade_out);
14798
14799            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14800            if range.start >= label.filter_range.end {
14801                if range.start > prev_end {
14802                    runs.push((prev_end..range.start, fade_out));
14803                }
14804                runs.push((range.clone(), muted_style));
14805            } else if range.end <= label.filter_range.end {
14806                runs.push((range.clone(), style));
14807            } else {
14808                runs.push((range.start..label.filter_range.end, style));
14809                runs.push((label.filter_range.end..range.end, muted_style));
14810            }
14811            prev_end = cmp::max(prev_end, range.end);
14812
14813            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14814                runs.push((prev_end..label.text.len(), fade_out));
14815            }
14816
14817            runs
14818        })
14819}
14820
14821pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14822    let mut prev_index = 0;
14823    let mut prev_codepoint: Option<char> = None;
14824    text.char_indices()
14825        .chain([(text.len(), '\0')])
14826        .filter_map(move |(index, codepoint)| {
14827            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14828            let is_boundary = index == text.len()
14829                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14830                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14831            if is_boundary {
14832                let chunk = &text[prev_index..index];
14833                prev_index = index;
14834                Some(chunk)
14835            } else {
14836                None
14837            }
14838        })
14839}
14840
14841pub trait RangeToAnchorExt: Sized {
14842    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14843
14844    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14845        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14846        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14847    }
14848}
14849
14850impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14851    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14852        let start_offset = self.start.to_offset(snapshot);
14853        let end_offset = self.end.to_offset(snapshot);
14854        if start_offset == end_offset {
14855            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14856        } else {
14857            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14858        }
14859    }
14860}
14861
14862pub trait RowExt {
14863    fn as_f32(&self) -> f32;
14864
14865    fn next_row(&self) -> Self;
14866
14867    fn previous_row(&self) -> Self;
14868
14869    fn minus(&self, other: Self) -> u32;
14870}
14871
14872impl RowExt for DisplayRow {
14873    fn as_f32(&self) -> f32 {
14874        self.0 as f32
14875    }
14876
14877    fn next_row(&self) -> Self {
14878        Self(self.0 + 1)
14879    }
14880
14881    fn previous_row(&self) -> Self {
14882        Self(self.0.saturating_sub(1))
14883    }
14884
14885    fn minus(&self, other: Self) -> u32 {
14886        self.0 - other.0
14887    }
14888}
14889
14890impl RowExt for MultiBufferRow {
14891    fn as_f32(&self) -> f32 {
14892        self.0 as f32
14893    }
14894
14895    fn next_row(&self) -> Self {
14896        Self(self.0 + 1)
14897    }
14898
14899    fn previous_row(&self) -> Self {
14900        Self(self.0.saturating_sub(1))
14901    }
14902
14903    fn minus(&self, other: Self) -> u32 {
14904        self.0 - other.0
14905    }
14906}
14907
14908trait RowRangeExt {
14909    type Row;
14910
14911    fn len(&self) -> usize;
14912
14913    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14914}
14915
14916impl RowRangeExt for Range<MultiBufferRow> {
14917    type Row = MultiBufferRow;
14918
14919    fn len(&self) -> usize {
14920        (self.end.0 - self.start.0) as usize
14921    }
14922
14923    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14924        (self.start.0..self.end.0).map(MultiBufferRow)
14925    }
14926}
14927
14928impl RowRangeExt for Range<DisplayRow> {
14929    type Row = DisplayRow;
14930
14931    fn len(&self) -> usize {
14932        (self.end.0 - self.start.0) as usize
14933    }
14934
14935    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14936        (self.start.0..self.end.0).map(DisplayRow)
14937    }
14938}
14939
14940fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14941    if hunk.diff_base_byte_range.is_empty() {
14942        DiffHunkStatus::Added
14943    } else if hunk.row_range.is_empty() {
14944        DiffHunkStatus::Removed
14945    } else {
14946        DiffHunkStatus::Modified
14947    }
14948}
14949
14950/// If select range has more than one line, we
14951/// just point the cursor to range.start.
14952fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14953    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14954        range
14955    } else {
14956        range.start..range.start
14957    }
14958}
14959
14960pub struct KillRing(ClipboardItem);
14961impl Global for KillRing {}
14962
14963const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);