editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod code_context_menus;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51use ::git::diff::DiffHunkStatus;
   52pub(crate) use actions::*;
   53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{anyhow, Context as _, Result};
   56use blink_manager::BlinkManager;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::StringMatchCandidate;
   73
   74use code_context_menus::{
   75    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   76    CompletionEntry, CompletionsMenu, ContextMenuOrigin,
   77};
   78use git::blame::GitBlame;
   79use gpui::{
   80    div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
   81    AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
   82    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
   83    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
   84    MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
   85    Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   87    WeakView, WindowContext,
   88};
   89use highlight_matching_bracket::refresh_matching_bracket_highlights;
   90use hover_popover::{hide_hover, HoverState};
   91pub(crate) use hunk_diff::HoveredHunk;
   92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
  103    Point, Selection, SelectionGoal, TransactionId,
  104};
  105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  106use linked_editing_ranges::refresh_linked_ranges;
  107use mouse_context_menu::MouseContextMenu;
  108pub use proposed_changes_editor::{
  109    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  110};
  111use similar::{ChangeTag, TextDiff};
  112use std::iter::Peekable;
  113use task::{ResolvedTask, TaskTemplate, TaskVariables};
  114
  115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  116pub use lsp::CompletionContext;
  117use lsp::{
  118    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  119    LanguageServerId, LanguageServerName,
  120};
  121
  122use movement::TextLayoutDetails;
  123pub use multi_buffer::{
  124    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  125    ToPoint,
  126};
  127use multi_buffer::{
  128    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  129};
  130use project::{
  131    buffer_store::BufferChangeSet,
  132    lsp_store::{FormatTarget, FormatTrigger, OpenLspBufferHandle},
  133    project_settings::{GitGutterSetting, ProjectSettings},
  134    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  135    LspStore, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  136};
  137use rand::prelude::*;
  138use rpc::{proto::*, ErrorExt};
  139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  140use selections_collection::{
  141    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  142};
  143use serde::{Deserialize, Serialize};
  144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  145use smallvec::SmallVec;
  146use snippet::Snippet;
  147use std::{
  148    any::TypeId,
  149    borrow::Cow,
  150    cell::RefCell,
  151    cmp::{self, Ordering, Reverse},
  152    mem,
  153    num::NonZeroU32,
  154    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  155    path::{Path, PathBuf},
  156    rc::Rc,
  157    sync::Arc,
  158    time::{Duration, Instant},
  159};
  160pub use sum_tree::Bias;
  161use sum_tree::TreeMap;
  162use text::{BufferId, OffsetUtf16, Rope};
  163use theme::{
  164    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  165    ThemeColors, ThemeSettings,
  166};
  167use ui::{
  168    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  169    PopoverMenuHandle, Tooltip,
  170};
  171use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  172use workspace::item::{ItemHandle, PreviewTabsSettings};
  173use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  174use workspace::{
  175    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  176};
  177use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  178
  179use crate::hover_links::{find_url, find_url_from_range};
  180use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  181
  182pub const FILE_HEADER_HEIGHT: u32 = 2;
  183pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  184pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  185pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  186const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  187const MAX_LINE_LEN: usize = 1024;
  188const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  189const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  190pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  191#[doc(hidden)]
  192pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  193
  194pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  195pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  196
  197pub fn render_parsed_markdown(
  198    element_id: impl Into<ElementId>,
  199    parsed: &language::ParsedMarkdown,
  200    editor_style: &EditorStyle,
  201    workspace: Option<WeakView<Workspace>>,
  202    cx: &mut WindowContext,
  203) -> InteractiveText {
  204    let code_span_background_color = cx
  205        .theme()
  206        .colors()
  207        .editor_document_highlight_read_background;
  208
  209    let highlights = gpui::combine_highlights(
  210        parsed.highlights.iter().filter_map(|(range, highlight)| {
  211            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  212            Some((range.clone(), highlight))
  213        }),
  214        parsed
  215            .regions
  216            .iter()
  217            .zip(&parsed.region_ranges)
  218            .filter_map(|(region, range)| {
  219                if region.code {
  220                    Some((
  221                        range.clone(),
  222                        HighlightStyle {
  223                            background_color: Some(code_span_background_color),
  224                            ..Default::default()
  225                        },
  226                    ))
  227                } else {
  228                    None
  229                }
  230            }),
  231    );
  232
  233    let mut links = Vec::new();
  234    let mut link_ranges = Vec::new();
  235    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  236        if let Some(link) = region.link.clone() {
  237            links.push(link);
  238            link_ranges.push(range.clone());
  239        }
  240    }
  241
  242    InteractiveText::new(
  243        element_id,
  244        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  245    )
  246    .on_click(link_ranges, move |clicked_range_ix, cx| {
  247        match &links[clicked_range_ix] {
  248            markdown::Link::Web { url } => cx.open_url(url),
  249            markdown::Link::Path { path } => {
  250                if let Some(workspace) = &workspace {
  251                    _ = workspace.update(cx, |workspace, cx| {
  252                        workspace.open_abs_path(path.clone(), false, cx).detach();
  253                    });
  254                }
  255            }
  256        }
  257    })
  258}
  259
  260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  261pub(crate) enum InlayId {
  262    InlineCompletion(usize),
  263    Hint(usize),
  264}
  265
  266impl InlayId {
  267    fn id(&self) -> usize {
  268        match self {
  269            Self::InlineCompletion(id) => *id,
  270            Self::Hint(id) => *id,
  271        }
  272    }
  273}
  274
  275enum DiffRowHighlight {}
  276enum DocumentHighlightRead {}
  277enum DocumentHighlightWrite {}
  278enum InputComposition {}
  279
  280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  281pub enum Navigated {
  282    Yes,
  283    No,
  284}
  285
  286impl Navigated {
  287    pub fn from_bool(yes: bool) -> Navigated {
  288        if yes {
  289            Navigated::Yes
  290        } else {
  291            Navigated::No
  292        }
  293    }
  294}
  295
  296pub fn init_settings(cx: &mut AppContext) {
  297    EditorSettings::register(cx);
  298}
  299
  300pub fn init(cx: &mut AppContext) {
  301    init_settings(cx);
  302
  303    workspace::register_project_item::<Editor>(cx);
  304    workspace::FollowableViewRegistry::register::<Editor>(cx);
  305    workspace::register_serializable_item::<Editor>(cx);
  306
  307    cx.observe_new_views(
  308        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  309            workspace.register_action(Editor::new_file);
  310            workspace.register_action(Editor::new_file_vertical);
  311            workspace.register_action(Editor::new_file_horizontal);
  312        },
  313    )
  314    .detach();
  315
  316    cx.on_action(move |_: &workspace::NewFile, cx| {
  317        let app_state = workspace::AppState::global(cx);
  318        if let Some(app_state) = app_state.upgrade() {
  319            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  320                Editor::new_file(workspace, &Default::default(), cx)
  321            })
  322            .detach();
  323        }
  324    });
  325    cx.on_action(move |_: &workspace::NewWindow, cx| {
  326        let app_state = workspace::AppState::global(cx);
  327        if let Some(app_state) = app_state.upgrade() {
  328            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  329                Editor::new_file(workspace, &Default::default(), cx)
  330            })
  331            .detach();
  332        }
  333    });
  334    git::project_diff::init(cx);
  335}
  336
  337pub struct SearchWithinRange;
  338
  339trait InvalidationRegion {
  340    fn ranges(&self) -> &[Range<Anchor>];
  341}
  342
  343#[derive(Clone, Debug, PartialEq)]
  344pub enum SelectPhase {
  345    Begin {
  346        position: DisplayPoint,
  347        add: bool,
  348        click_count: usize,
  349    },
  350    BeginColumnar {
  351        position: DisplayPoint,
  352        reset: bool,
  353        goal_column: u32,
  354    },
  355    Extend {
  356        position: DisplayPoint,
  357        click_count: usize,
  358    },
  359    Update {
  360        position: DisplayPoint,
  361        goal_column: u32,
  362        scroll_delta: gpui::Point<f32>,
  363    },
  364    End,
  365}
  366
  367#[derive(Clone, Debug)]
  368pub enum SelectMode {
  369    Character,
  370    Word(Range<Anchor>),
  371    Line(Range<Anchor>),
  372    All,
  373}
  374
  375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  376pub enum EditorMode {
  377    SingleLine { auto_width: bool },
  378    AutoHeight { max_lines: usize },
  379    Full,
  380}
  381
  382#[derive(Copy, Clone, Debug)]
  383pub enum SoftWrap {
  384    /// Prefer not to wrap at all.
  385    ///
  386    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  387    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  388    GitDiff,
  389    /// Prefer a single line generally, unless an overly long line is encountered.
  390    None,
  391    /// Soft wrap lines that exceed the editor width.
  392    EditorWidth,
  393    /// Soft wrap lines at the preferred line length.
  394    Column(u32),
  395    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  396    Bounded(u32),
  397}
  398
  399#[derive(Clone)]
  400pub struct EditorStyle {
  401    pub background: Hsla,
  402    pub local_player: PlayerColor,
  403    pub text: TextStyle,
  404    pub scrollbar_width: Pixels,
  405    pub syntax: Arc<SyntaxTheme>,
  406    pub status: StatusColors,
  407    pub inlay_hints_style: HighlightStyle,
  408    pub inline_completion_styles: InlineCompletionStyles,
  409    pub unnecessary_code_fade: f32,
  410}
  411
  412impl Default for EditorStyle {
  413    fn default() -> Self {
  414        Self {
  415            background: Hsla::default(),
  416            local_player: PlayerColor::default(),
  417            text: TextStyle::default(),
  418            scrollbar_width: Pixels::default(),
  419            syntax: Default::default(),
  420            // HACK: Status colors don't have a real default.
  421            // We should look into removing the status colors from the editor
  422            // style and retrieve them directly from the theme.
  423            status: StatusColors::dark(),
  424            inlay_hints_style: HighlightStyle::default(),
  425            inline_completion_styles: InlineCompletionStyles {
  426                insertion: HighlightStyle::default(),
  427                whitespace: HighlightStyle::default(),
  428            },
  429            unnecessary_code_fade: Default::default(),
  430        }
  431    }
  432}
  433
  434pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  435    let show_background = language_settings::language_settings(None, None, cx)
  436        .inlay_hints
  437        .show_background;
  438
  439    HighlightStyle {
  440        color: Some(cx.theme().status().hint),
  441        background_color: show_background.then(|| cx.theme().status().hint_background),
  442        ..HighlightStyle::default()
  443    }
  444}
  445
  446pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
  447    InlineCompletionStyles {
  448        insertion: HighlightStyle {
  449            color: Some(cx.theme().status().predictive),
  450            ..HighlightStyle::default()
  451        },
  452        whitespace: HighlightStyle {
  453            background_color: Some(cx.theme().status().created_background),
  454            ..HighlightStyle::default()
  455        },
  456    }
  457}
  458
  459type CompletionId = usize;
  460
  461#[derive(Debug, Clone)]
  462struct InlineCompletionMenuHint {
  463    provider_name: &'static str,
  464    text: InlineCompletionText,
  465}
  466
  467#[derive(Clone, Debug)]
  468enum InlineCompletionText {
  469    Move(SharedString),
  470    Edit {
  471        text: SharedString,
  472        highlights: Vec<(Range<usize>, HighlightStyle)>,
  473    },
  474}
  475
  476enum InlineCompletion {
  477    Edit(Vec<(Range<Anchor>, String)>),
  478    Move(Anchor),
  479}
  480
  481struct InlineCompletionState {
  482    inlay_ids: Vec<InlayId>,
  483    completion: InlineCompletion,
  484    invalidation_range: Range<Anchor>,
  485}
  486
  487enum InlineCompletionHighlight {}
  488
  489#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  490struct EditorActionId(usize);
  491
  492impl EditorActionId {
  493    pub fn post_inc(&mut self) -> Self {
  494        let answer = self.0;
  495
  496        *self = Self(answer + 1);
  497
  498        Self(answer)
  499    }
  500}
  501
  502// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  503// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  504
  505type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  506type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  507
  508#[derive(Default)]
  509struct ScrollbarMarkerState {
  510    scrollbar_size: Size<Pixels>,
  511    dirty: bool,
  512    markers: Arc<[PaintQuad]>,
  513    pending_refresh: Option<Task<Result<()>>>,
  514}
  515
  516impl ScrollbarMarkerState {
  517    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  518        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  519    }
  520}
  521
  522#[derive(Clone, Debug)]
  523struct RunnableTasks {
  524    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  525    offset: MultiBufferOffset,
  526    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  527    column: u32,
  528    // Values of all named captures, including those starting with '_'
  529    extra_variables: HashMap<String, String>,
  530    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  531    context_range: Range<BufferOffset>,
  532}
  533
  534impl RunnableTasks {
  535    fn resolve<'a>(
  536        &'a self,
  537        cx: &'a task::TaskContext,
  538    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  539        self.templates.iter().filter_map(|(kind, template)| {
  540            template
  541                .resolve_task(&kind.to_id_base(), cx)
  542                .map(|task| (kind.clone(), task))
  543        })
  544    }
  545}
  546
  547#[derive(Clone)]
  548struct ResolvedTasks {
  549    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  550    position: Anchor,
  551}
  552#[derive(Copy, Clone, Debug)]
  553struct MultiBufferOffset(usize);
  554#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  555struct BufferOffset(usize);
  556
  557// Addons allow storing per-editor state in other crates (e.g. Vim)
  558pub trait Addon: 'static {
  559    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  560
  561    fn to_any(&self) -> &dyn std::any::Any;
  562}
  563
  564#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  565pub enum IsVimMode {
  566    Yes,
  567    No,
  568}
  569
  570/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  571///
  572/// See the [module level documentation](self) for more information.
  573pub struct Editor {
  574    focus_handle: FocusHandle,
  575    last_focused_descendant: Option<WeakFocusHandle>,
  576    /// The text buffer being edited
  577    buffer: Model<MultiBuffer>,
  578    /// Map of how text in the buffer should be displayed.
  579    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  580    pub display_map: Model<DisplayMap>,
  581    pub selections: SelectionsCollection,
  582    pub scroll_manager: ScrollManager,
  583    /// When inline assist editors are linked, they all render cursors because
  584    /// typing enters text into each of them, even the ones that aren't focused.
  585    pub(crate) show_cursor_when_unfocused: bool,
  586    columnar_selection_tail: Option<Anchor>,
  587    add_selections_state: Option<AddSelectionsState>,
  588    select_next_state: Option<SelectNextState>,
  589    select_prev_state: Option<SelectNextState>,
  590    selection_history: SelectionHistory,
  591    autoclose_regions: Vec<AutocloseRegion>,
  592    snippet_stack: InvalidationStack<SnippetState>,
  593    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  594    ime_transaction: Option<TransactionId>,
  595    active_diagnostics: Option<ActiveDiagnosticGroup>,
  596    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  597
  598    project: Option<Model<Project>>,
  599    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  600    completion_provider: Option<Box<dyn CompletionProvider>>,
  601    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  602    blink_manager: Model<BlinkManager>,
  603    show_cursor_names: bool,
  604    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  605    pub show_local_selections: bool,
  606    mode: EditorMode,
  607    show_breadcrumbs: bool,
  608    show_gutter: bool,
  609    show_scrollbars: bool,
  610    show_line_numbers: Option<bool>,
  611    use_relative_line_numbers: Option<bool>,
  612    show_git_diff_gutter: Option<bool>,
  613    show_code_actions: Option<bool>,
  614    show_runnables: Option<bool>,
  615    show_wrap_guides: Option<bool>,
  616    show_indent_guides: Option<bool>,
  617    placeholder_text: Option<Arc<str>>,
  618    highlight_order: usize,
  619    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  620    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  621    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  622    scrollbar_marker_state: ScrollbarMarkerState,
  623    active_indent_guides_state: ActiveIndentGuidesState,
  624    nav_history: Option<ItemNavHistory>,
  625    context_menu: RefCell<Option<CodeContextMenu>>,
  626    mouse_context_menu: Option<MouseContextMenu>,
  627    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  628    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  629    signature_help_state: SignatureHelpState,
  630    auto_signature_help: Option<bool>,
  631    find_all_references_task_sources: Vec<Anchor>,
  632    next_completion_id: CompletionId,
  633    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  634    code_actions_task: Option<Task<Result<()>>>,
  635    document_highlights_task: Option<Task<()>>,
  636    linked_editing_range_task: Option<Task<Option<()>>>,
  637    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  638    pending_rename: Option<RenameState>,
  639    searchable: bool,
  640    cursor_shape: CursorShape,
  641    current_line_highlight: Option<CurrentLineHighlight>,
  642    collapse_matches: bool,
  643    autoindent_mode: Option<AutoindentMode>,
  644    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  645    input_enabled: bool,
  646    use_modal_editing: bool,
  647    read_only: bool,
  648    leader_peer_id: Option<PeerId>,
  649    remote_id: Option<ViewId>,
  650    hover_state: HoverState,
  651    gutter_hovered: bool,
  652    hovered_link_state: Option<HoveredLinkState>,
  653    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  654    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  655    active_inline_completion: Option<InlineCompletionState>,
  656    // enable_inline_completions is a switch that Vim can use to disable
  657    // inline completions based on its mode.
  658    enable_inline_completions: bool,
  659    show_inline_completions_override: Option<bool>,
  660    inlay_hint_cache: InlayHintCache,
  661    diff_map: DiffMap,
  662    next_inlay_id: usize,
  663    _subscriptions: Vec<Subscription>,
  664    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  665    gutter_dimensions: GutterDimensions,
  666    style: Option<EditorStyle>,
  667    text_style_refinement: Option<TextStyleRefinement>,
  668    next_editor_action_id: EditorActionId,
  669    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  670    use_autoclose: bool,
  671    use_auto_surround: bool,
  672    auto_replace_emoji_shortcode: bool,
  673    show_git_blame_gutter: bool,
  674    show_git_blame_inline: bool,
  675    show_git_blame_inline_delay_task: Option<Task<()>>,
  676    git_blame_inline_enabled: bool,
  677    serialize_dirty_buffers: bool,
  678    show_selection_menu: Option<bool>,
  679    blame: Option<Model<GitBlame>>,
  680    blame_subscription: Option<Subscription>,
  681    custom_context_menu: Option<
  682        Box<
  683            dyn 'static
  684                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  685        >,
  686    >,
  687    last_bounds: Option<Bounds<Pixels>>,
  688    expect_bounds_change: Option<Bounds<Pixels>>,
  689    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  690    tasks_update_task: Option<Task<()>>,
  691    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  692    breadcrumb_header: Option<String>,
  693    focused_block: Option<FocusedBlock>,
  694    next_scroll_position: NextScrollCursorCenterTopBottom,
  695    addons: HashMap<TypeId, Box<dyn Addon>>,
  696    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  697    toggle_fold_multiple_buffers: Task<()>,
  698    _scroll_cursor_center_top_bottom_task: Task<()>,
  699}
  700
  701#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  702enum NextScrollCursorCenterTopBottom {
  703    #[default]
  704    Center,
  705    Top,
  706    Bottom,
  707}
  708
  709impl NextScrollCursorCenterTopBottom {
  710    fn next(&self) -> Self {
  711        match self {
  712            Self::Center => Self::Top,
  713            Self::Top => Self::Bottom,
  714            Self::Bottom => Self::Center,
  715        }
  716    }
  717}
  718
  719#[derive(Clone)]
  720pub struct EditorSnapshot {
  721    pub mode: EditorMode,
  722    show_gutter: bool,
  723    show_line_numbers: Option<bool>,
  724    show_git_diff_gutter: Option<bool>,
  725    show_code_actions: Option<bool>,
  726    show_runnables: Option<bool>,
  727    git_blame_gutter_max_author_length: Option<usize>,
  728    pub display_snapshot: DisplaySnapshot,
  729    pub placeholder_text: Option<Arc<str>>,
  730    diff_map: DiffMapSnapshot,
  731    is_focused: bool,
  732    scroll_anchor: ScrollAnchor,
  733    ongoing_scroll: OngoingScroll,
  734    current_line_highlight: CurrentLineHighlight,
  735    gutter_hovered: bool,
  736}
  737
  738const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  739
  740#[derive(Default, Debug, Clone, Copy)]
  741pub struct GutterDimensions {
  742    pub left_padding: Pixels,
  743    pub right_padding: Pixels,
  744    pub width: Pixels,
  745    pub margin: Pixels,
  746    pub git_blame_entries_width: Option<Pixels>,
  747}
  748
  749impl GutterDimensions {
  750    /// The full width of the space taken up by the gutter.
  751    pub fn full_width(&self) -> Pixels {
  752        self.margin + self.width
  753    }
  754
  755    /// The width of the space reserved for the fold indicators,
  756    /// use alongside 'justify_end' and `gutter_width` to
  757    /// right align content with the line numbers
  758    pub fn fold_area_width(&self) -> Pixels {
  759        self.margin + self.right_padding
  760    }
  761}
  762
  763#[derive(Debug)]
  764pub struct RemoteSelection {
  765    pub replica_id: ReplicaId,
  766    pub selection: Selection<Anchor>,
  767    pub cursor_shape: CursorShape,
  768    pub peer_id: PeerId,
  769    pub line_mode: bool,
  770    pub participant_index: Option<ParticipantIndex>,
  771    pub user_name: Option<SharedString>,
  772}
  773
  774#[derive(Clone, Debug)]
  775struct SelectionHistoryEntry {
  776    selections: Arc<[Selection<Anchor>]>,
  777    select_next_state: Option<SelectNextState>,
  778    select_prev_state: Option<SelectNextState>,
  779    add_selections_state: Option<AddSelectionsState>,
  780}
  781
  782enum SelectionHistoryMode {
  783    Normal,
  784    Undoing,
  785    Redoing,
  786}
  787
  788#[derive(Clone, PartialEq, Eq, Hash)]
  789struct HoveredCursor {
  790    replica_id: u16,
  791    selection_id: usize,
  792}
  793
  794impl Default for SelectionHistoryMode {
  795    fn default() -> Self {
  796        Self::Normal
  797    }
  798}
  799
  800#[derive(Default)]
  801struct SelectionHistory {
  802    #[allow(clippy::type_complexity)]
  803    selections_by_transaction:
  804        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  805    mode: SelectionHistoryMode,
  806    undo_stack: VecDeque<SelectionHistoryEntry>,
  807    redo_stack: VecDeque<SelectionHistoryEntry>,
  808}
  809
  810impl SelectionHistory {
  811    fn insert_transaction(
  812        &mut self,
  813        transaction_id: TransactionId,
  814        selections: Arc<[Selection<Anchor>]>,
  815    ) {
  816        self.selections_by_transaction
  817            .insert(transaction_id, (selections, None));
  818    }
  819
  820    #[allow(clippy::type_complexity)]
  821    fn transaction(
  822        &self,
  823        transaction_id: TransactionId,
  824    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  825        self.selections_by_transaction.get(&transaction_id)
  826    }
  827
  828    #[allow(clippy::type_complexity)]
  829    fn transaction_mut(
  830        &mut self,
  831        transaction_id: TransactionId,
  832    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  833        self.selections_by_transaction.get_mut(&transaction_id)
  834    }
  835
  836    fn push(&mut self, entry: SelectionHistoryEntry) {
  837        if !entry.selections.is_empty() {
  838            match self.mode {
  839                SelectionHistoryMode::Normal => {
  840                    self.push_undo(entry);
  841                    self.redo_stack.clear();
  842                }
  843                SelectionHistoryMode::Undoing => self.push_redo(entry),
  844                SelectionHistoryMode::Redoing => self.push_undo(entry),
  845            }
  846        }
  847    }
  848
  849    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  850        if self
  851            .undo_stack
  852            .back()
  853            .map_or(true, |e| e.selections != entry.selections)
  854        {
  855            self.undo_stack.push_back(entry);
  856            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  857                self.undo_stack.pop_front();
  858            }
  859        }
  860    }
  861
  862    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  863        if self
  864            .redo_stack
  865            .back()
  866            .map_or(true, |e| e.selections != entry.selections)
  867        {
  868            self.redo_stack.push_back(entry);
  869            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  870                self.redo_stack.pop_front();
  871            }
  872        }
  873    }
  874}
  875
  876struct RowHighlight {
  877    index: usize,
  878    range: Range<Anchor>,
  879    color: Hsla,
  880    should_autoscroll: bool,
  881}
  882
  883#[derive(Clone, Debug)]
  884struct AddSelectionsState {
  885    above: bool,
  886    stack: Vec<usize>,
  887}
  888
  889#[derive(Clone)]
  890struct SelectNextState {
  891    query: AhoCorasick,
  892    wordwise: bool,
  893    done: bool,
  894}
  895
  896impl std::fmt::Debug for SelectNextState {
  897    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  898        f.debug_struct(std::any::type_name::<Self>())
  899            .field("wordwise", &self.wordwise)
  900            .field("done", &self.done)
  901            .finish()
  902    }
  903}
  904
  905#[derive(Debug)]
  906struct AutocloseRegion {
  907    selection_id: usize,
  908    range: Range<Anchor>,
  909    pair: BracketPair,
  910}
  911
  912#[derive(Debug)]
  913struct SnippetState {
  914    ranges: Vec<Vec<Range<Anchor>>>,
  915    active_index: usize,
  916    choices: Vec<Option<Vec<String>>>,
  917}
  918
  919#[doc(hidden)]
  920pub struct RenameState {
  921    pub range: Range<Anchor>,
  922    pub old_name: Arc<str>,
  923    pub editor: View<Editor>,
  924    block_id: CustomBlockId,
  925}
  926
  927struct InvalidationStack<T>(Vec<T>);
  928
  929struct RegisteredInlineCompletionProvider {
  930    provider: Arc<dyn InlineCompletionProviderHandle>,
  931    _subscription: Subscription,
  932}
  933
  934#[derive(Debug)]
  935struct ActiveDiagnosticGroup {
  936    primary_range: Range<Anchor>,
  937    primary_message: String,
  938    group_id: usize,
  939    blocks: HashMap<CustomBlockId, Diagnostic>,
  940    is_valid: bool,
  941}
  942
  943#[derive(Serialize, Deserialize, Clone, Debug)]
  944pub struct ClipboardSelection {
  945    pub len: usize,
  946    pub is_entire_line: bool,
  947    pub first_line_indent: u32,
  948}
  949
  950#[derive(Debug)]
  951pub(crate) struct NavigationData {
  952    cursor_anchor: Anchor,
  953    cursor_position: Point,
  954    scroll_anchor: ScrollAnchor,
  955    scroll_top_row: u32,
  956}
  957
  958#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  959pub enum GotoDefinitionKind {
  960    Symbol,
  961    Declaration,
  962    Type,
  963    Implementation,
  964}
  965
  966#[derive(Debug, Clone)]
  967enum InlayHintRefreshReason {
  968    Toggle(bool),
  969    SettingsChange(InlayHintSettings),
  970    NewLinesShown,
  971    BufferEdited(HashSet<Arc<Language>>),
  972    RefreshRequested,
  973    ExcerptsRemoved(Vec<ExcerptId>),
  974}
  975
  976impl InlayHintRefreshReason {
  977    fn description(&self) -> &'static str {
  978        match self {
  979            Self::Toggle(_) => "toggle",
  980            Self::SettingsChange(_) => "settings change",
  981            Self::NewLinesShown => "new lines shown",
  982            Self::BufferEdited(_) => "buffer edited",
  983            Self::RefreshRequested => "refresh requested",
  984            Self::ExcerptsRemoved(_) => "excerpts removed",
  985        }
  986    }
  987}
  988
  989pub(crate) struct FocusedBlock {
  990    id: BlockId,
  991    focus_handle: WeakFocusHandle,
  992}
  993
  994#[derive(Clone)]
  995enum JumpData {
  996    MultiBufferRow {
  997        row: MultiBufferRow,
  998        line_offset_from_top: u32,
  999    },
 1000    MultiBufferPoint {
 1001        excerpt_id: ExcerptId,
 1002        position: Point,
 1003        anchor: text::Anchor,
 1004        line_offset_from_top: u32,
 1005    },
 1006}
 1007
 1008impl Editor {
 1009    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1010        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1011        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1012        Self::new(
 1013            EditorMode::SingleLine { auto_width: false },
 1014            buffer,
 1015            None,
 1016            false,
 1017            cx,
 1018        )
 1019    }
 1020
 1021    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1022        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1023        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1024        Self::new(EditorMode::Full, buffer, None, false, cx)
 1025    }
 1026
 1027    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1028        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1029        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1030        Self::new(
 1031            EditorMode::SingleLine { auto_width: true },
 1032            buffer,
 1033            None,
 1034            false,
 1035            cx,
 1036        )
 1037    }
 1038
 1039    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1040        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1041        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1042        Self::new(
 1043            EditorMode::AutoHeight { max_lines },
 1044            buffer,
 1045            None,
 1046            false,
 1047            cx,
 1048        )
 1049    }
 1050
 1051    pub fn for_buffer(
 1052        buffer: Model<Buffer>,
 1053        project: Option<Model<Project>>,
 1054        cx: &mut ViewContext<Self>,
 1055    ) -> Self {
 1056        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1057        Self::new(EditorMode::Full, buffer, project, false, cx)
 1058    }
 1059
 1060    pub fn for_multibuffer(
 1061        buffer: Model<MultiBuffer>,
 1062        project: Option<Model<Project>>,
 1063        show_excerpt_controls: bool,
 1064        cx: &mut ViewContext<Self>,
 1065    ) -> Self {
 1066        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1067    }
 1068
 1069    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1070        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1071        let mut clone = Self::new(
 1072            self.mode,
 1073            self.buffer.clone(),
 1074            self.project.clone(),
 1075            show_excerpt_controls,
 1076            cx,
 1077        );
 1078        self.display_map.update(cx, |display_map, cx| {
 1079            let snapshot = display_map.snapshot(cx);
 1080            clone.display_map.update(cx, |display_map, cx| {
 1081                display_map.set_state(&snapshot, cx);
 1082            });
 1083        });
 1084        clone.selections.clone_state(&self.selections);
 1085        clone.scroll_manager.clone_state(&self.scroll_manager);
 1086        clone.searchable = self.searchable;
 1087        clone
 1088    }
 1089
 1090    pub fn new(
 1091        mode: EditorMode,
 1092        buffer: Model<MultiBuffer>,
 1093        project: Option<Model<Project>>,
 1094        show_excerpt_controls: bool,
 1095        cx: &mut ViewContext<Self>,
 1096    ) -> Self {
 1097        let style = cx.text_style();
 1098        let font_size = style.font_size.to_pixels(cx.rem_size());
 1099        let editor = cx.view().downgrade();
 1100        let fold_placeholder = FoldPlaceholder {
 1101            constrain_width: true,
 1102            render: Arc::new(move |fold_id, fold_range, cx| {
 1103                let editor = editor.clone();
 1104                div()
 1105                    .id(fold_id)
 1106                    .bg(cx.theme().colors().ghost_element_background)
 1107                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1108                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1109                    .rounded_sm()
 1110                    .size_full()
 1111                    .cursor_pointer()
 1112                    .child("")
 1113                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1114                    .on_click(move |_, cx| {
 1115                        editor
 1116                            .update(cx, |editor, cx| {
 1117                                editor.unfold_ranges(
 1118                                    &[fold_range.start..fold_range.end],
 1119                                    true,
 1120                                    false,
 1121                                    cx,
 1122                                );
 1123                                cx.stop_propagation();
 1124                            })
 1125                            .ok();
 1126                    })
 1127                    .into_any()
 1128            }),
 1129            merge_adjacent: true,
 1130            ..Default::default()
 1131        };
 1132        let display_map = cx.new_model(|cx| {
 1133            DisplayMap::new(
 1134                buffer.clone(),
 1135                style.font(),
 1136                font_size,
 1137                None,
 1138                show_excerpt_controls,
 1139                FILE_HEADER_HEIGHT,
 1140                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1141                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1142                fold_placeholder,
 1143                cx,
 1144            )
 1145        });
 1146
 1147        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1148
 1149        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1150
 1151        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1152            .then(|| language_settings::SoftWrap::None);
 1153
 1154        let mut project_subscriptions = Vec::new();
 1155        if mode == EditorMode::Full {
 1156            if let Some(project) = project.as_ref() {
 1157                if buffer.read(cx).is_singleton() {
 1158                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1159                        cx.emit(EditorEvent::TitleChanged);
 1160                    }));
 1161                }
 1162                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1163                    if let project::Event::RefreshInlayHints = event {
 1164                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1165                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1166                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1167                            let focus_handle = editor.focus_handle(cx);
 1168                            if focus_handle.is_focused(cx) {
 1169                                let snapshot = buffer.read(cx).snapshot();
 1170                                for (range, snippet) in snippet_edits {
 1171                                    let editor_range =
 1172                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1173                                    editor
 1174                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1175                                        .ok();
 1176                                }
 1177                            }
 1178                        }
 1179                    }
 1180                }));
 1181                if let Some(task_inventory) = project
 1182                    .read(cx)
 1183                    .task_store()
 1184                    .read(cx)
 1185                    .task_inventory()
 1186                    .cloned()
 1187                {
 1188                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1189                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1190                    }));
 1191                }
 1192            }
 1193        }
 1194
 1195        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1196
 1197        let inlay_hint_settings =
 1198            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1199        let focus_handle = cx.focus_handle();
 1200        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1201        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1202            .detach();
 1203        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1204            .detach();
 1205        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1206
 1207        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1208            Some(false)
 1209        } else {
 1210            None
 1211        };
 1212
 1213        let mut code_action_providers = Vec::new();
 1214        if let Some(project) = project.clone() {
 1215            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1216            code_action_providers.push(Rc::new(project) as Rc<_>);
 1217        }
 1218
 1219        let mut this = Self {
 1220            focus_handle,
 1221            show_cursor_when_unfocused: false,
 1222            last_focused_descendant: None,
 1223            buffer: buffer.clone(),
 1224            display_map: display_map.clone(),
 1225            selections,
 1226            scroll_manager: ScrollManager::new(cx),
 1227            columnar_selection_tail: None,
 1228            add_selections_state: None,
 1229            select_next_state: None,
 1230            select_prev_state: None,
 1231            selection_history: Default::default(),
 1232            autoclose_regions: Default::default(),
 1233            snippet_stack: Default::default(),
 1234            select_larger_syntax_node_stack: Vec::new(),
 1235            ime_transaction: Default::default(),
 1236            active_diagnostics: None,
 1237            soft_wrap_mode_override,
 1238            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1239            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1240            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1241            project,
 1242            blink_manager: blink_manager.clone(),
 1243            show_local_selections: true,
 1244            show_scrollbars: true,
 1245            mode,
 1246            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1247            show_gutter: mode == EditorMode::Full,
 1248            show_line_numbers: None,
 1249            use_relative_line_numbers: None,
 1250            show_git_diff_gutter: None,
 1251            show_code_actions: None,
 1252            show_runnables: None,
 1253            show_wrap_guides: None,
 1254            show_indent_guides,
 1255            placeholder_text: None,
 1256            highlight_order: 0,
 1257            highlighted_rows: HashMap::default(),
 1258            background_highlights: Default::default(),
 1259            gutter_highlights: TreeMap::default(),
 1260            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1261            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1262            nav_history: None,
 1263            context_menu: RefCell::new(None),
 1264            mouse_context_menu: None,
 1265            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1266            completion_tasks: Default::default(),
 1267            signature_help_state: SignatureHelpState::default(),
 1268            auto_signature_help: None,
 1269            find_all_references_task_sources: Vec::new(),
 1270            next_completion_id: 0,
 1271            next_inlay_id: 0,
 1272            code_action_providers,
 1273            available_code_actions: Default::default(),
 1274            code_actions_task: Default::default(),
 1275            document_highlights_task: Default::default(),
 1276            linked_editing_range_task: Default::default(),
 1277            pending_rename: Default::default(),
 1278            searchable: true,
 1279            cursor_shape: EditorSettings::get_global(cx)
 1280                .cursor_shape
 1281                .unwrap_or_default(),
 1282            current_line_highlight: None,
 1283            autoindent_mode: Some(AutoindentMode::EachLine),
 1284            collapse_matches: false,
 1285            workspace: None,
 1286            input_enabled: true,
 1287            use_modal_editing: mode == EditorMode::Full,
 1288            read_only: false,
 1289            use_autoclose: true,
 1290            use_auto_surround: true,
 1291            auto_replace_emoji_shortcode: false,
 1292            leader_peer_id: None,
 1293            remote_id: None,
 1294            hover_state: Default::default(),
 1295            hovered_link_state: Default::default(),
 1296            inline_completion_provider: None,
 1297            active_inline_completion: None,
 1298            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1299            diff_map: DiffMap::default(),
 1300            gutter_hovered: false,
 1301            pixel_position_of_newest_cursor: None,
 1302            last_bounds: None,
 1303            expect_bounds_change: None,
 1304            gutter_dimensions: GutterDimensions::default(),
 1305            style: None,
 1306            show_cursor_names: false,
 1307            hovered_cursors: Default::default(),
 1308            next_editor_action_id: EditorActionId::default(),
 1309            editor_actions: Rc::default(),
 1310            show_inline_completions_override: None,
 1311            enable_inline_completions: true,
 1312            custom_context_menu: None,
 1313            show_git_blame_gutter: false,
 1314            show_git_blame_inline: false,
 1315            show_selection_menu: None,
 1316            show_git_blame_inline_delay_task: None,
 1317            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1318            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1319                .session
 1320                .restore_unsaved_buffers,
 1321            blame: None,
 1322            blame_subscription: None,
 1323            tasks: Default::default(),
 1324            _subscriptions: vec![
 1325                cx.observe(&buffer, Self::on_buffer_changed),
 1326                cx.subscribe(&buffer, Self::on_buffer_event),
 1327                cx.observe(&display_map, Self::on_display_map_changed),
 1328                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1329                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1330                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1331                cx.observe_window_activation(|editor, cx| {
 1332                    let active = cx.is_window_active();
 1333                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1334                        if active {
 1335                            blink_manager.enable(cx);
 1336                        } else {
 1337                            blink_manager.disable(cx);
 1338                        }
 1339                    });
 1340                }),
 1341            ],
 1342            tasks_update_task: None,
 1343            linked_edit_ranges: Default::default(),
 1344            previous_search_ranges: None,
 1345            breadcrumb_header: None,
 1346            focused_block: None,
 1347            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1348            addons: HashMap::default(),
 1349            registered_buffers: HashMap::default(),
 1350            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1351            toggle_fold_multiple_buffers: Task::ready(()),
 1352            text_style_refinement: None,
 1353        };
 1354        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1355        this._subscriptions.extend(project_subscriptions);
 1356
 1357        this.end_selection(cx);
 1358        this.scroll_manager.show_scrollbar(cx);
 1359
 1360        if mode == EditorMode::Full {
 1361            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1362            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1363
 1364            if this.git_blame_inline_enabled {
 1365                this.git_blame_inline_enabled = true;
 1366                this.start_git_blame_inline(false, cx);
 1367            }
 1368
 1369            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1370                if let Some(project) = this.project.as_ref() {
 1371                    let lsp_store = project.read(cx).lsp_store();
 1372                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1373                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1374                    });
 1375                    this.registered_buffers
 1376                        .insert(buffer.read(cx).remote_id(), handle);
 1377                }
 1378            }
 1379        }
 1380
 1381        this.report_editor_event("Editor Opened", None, cx);
 1382        this
 1383    }
 1384
 1385    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1386        self.mouse_context_menu
 1387            .as_ref()
 1388            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1389    }
 1390
 1391    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1392        let mut key_context = KeyContext::new_with_defaults();
 1393        key_context.add("Editor");
 1394        let mode = match self.mode {
 1395            EditorMode::SingleLine { .. } => "single_line",
 1396            EditorMode::AutoHeight { .. } => "auto_height",
 1397            EditorMode::Full => "full",
 1398        };
 1399
 1400        if EditorSettings::jupyter_enabled(cx) {
 1401            key_context.add("jupyter");
 1402        }
 1403
 1404        key_context.set("mode", mode);
 1405        if self.pending_rename.is_some() {
 1406            key_context.add("renaming");
 1407        }
 1408        match self.context_menu.borrow().as_ref() {
 1409            Some(CodeContextMenu::Completions(_)) => {
 1410                key_context.add("menu");
 1411                key_context.add("showing_completions")
 1412            }
 1413            Some(CodeContextMenu::CodeActions(_)) => {
 1414                key_context.add("menu");
 1415                key_context.add("showing_code_actions")
 1416            }
 1417            None => {}
 1418        }
 1419
 1420        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1421        if !self.focus_handle(cx).contains_focused(cx)
 1422            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1423        {
 1424            for addon in self.addons.values() {
 1425                addon.extend_key_context(&mut key_context, cx)
 1426            }
 1427        }
 1428
 1429        if let Some(extension) = self
 1430            .buffer
 1431            .read(cx)
 1432            .as_singleton()
 1433            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1434        {
 1435            key_context.set("extension", extension.to_string());
 1436        }
 1437
 1438        if self.has_active_inline_completion() {
 1439            key_context.add("copilot_suggestion");
 1440            key_context.add("inline_completion");
 1441        }
 1442
 1443        if !self
 1444            .selections
 1445            .disjoint
 1446            .iter()
 1447            .all(|selection| selection.start == selection.end)
 1448        {
 1449            key_context.add("selection");
 1450        }
 1451
 1452        key_context
 1453    }
 1454
 1455    pub fn new_file(
 1456        workspace: &mut Workspace,
 1457        _: &workspace::NewFile,
 1458        cx: &mut ViewContext<Workspace>,
 1459    ) {
 1460        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1461            "Failed to create buffer",
 1462            cx,
 1463            |e, _| match e.error_code() {
 1464                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1465                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1466                e.error_tag("required").unwrap_or("the latest version")
 1467            )),
 1468                _ => None,
 1469            },
 1470        );
 1471    }
 1472
 1473    pub fn new_in_workspace(
 1474        workspace: &mut Workspace,
 1475        cx: &mut ViewContext<Workspace>,
 1476    ) -> Task<Result<View<Editor>>> {
 1477        let project = workspace.project().clone();
 1478        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1479
 1480        cx.spawn(|workspace, mut cx| async move {
 1481            let buffer = create.await?;
 1482            workspace.update(&mut cx, |workspace, cx| {
 1483                let editor =
 1484                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1485                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1486                editor
 1487            })
 1488        })
 1489    }
 1490
 1491    fn new_file_vertical(
 1492        workspace: &mut Workspace,
 1493        _: &workspace::NewFileSplitVertical,
 1494        cx: &mut ViewContext<Workspace>,
 1495    ) {
 1496        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1497    }
 1498
 1499    fn new_file_horizontal(
 1500        workspace: &mut Workspace,
 1501        _: &workspace::NewFileSplitHorizontal,
 1502        cx: &mut ViewContext<Workspace>,
 1503    ) {
 1504        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1505    }
 1506
 1507    fn new_file_in_direction(
 1508        workspace: &mut Workspace,
 1509        direction: SplitDirection,
 1510        cx: &mut ViewContext<Workspace>,
 1511    ) {
 1512        let project = workspace.project().clone();
 1513        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1514
 1515        cx.spawn(|workspace, mut cx| async move {
 1516            let buffer = create.await?;
 1517            workspace.update(&mut cx, move |workspace, cx| {
 1518                workspace.split_item(
 1519                    direction,
 1520                    Box::new(
 1521                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1522                    ),
 1523                    cx,
 1524                )
 1525            })?;
 1526            anyhow::Ok(())
 1527        })
 1528        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1529            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1530                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1531                e.error_tag("required").unwrap_or("the latest version")
 1532            )),
 1533            _ => None,
 1534        });
 1535    }
 1536
 1537    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1538        self.leader_peer_id
 1539    }
 1540
 1541    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1542        &self.buffer
 1543    }
 1544
 1545    pub fn workspace(&self) -> Option<View<Workspace>> {
 1546        self.workspace.as_ref()?.0.upgrade()
 1547    }
 1548
 1549    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1550        self.buffer().read(cx).title(cx)
 1551    }
 1552
 1553    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1554        let git_blame_gutter_max_author_length = self
 1555            .render_git_blame_gutter(cx)
 1556            .then(|| {
 1557                if let Some(blame) = self.blame.as_ref() {
 1558                    let max_author_length =
 1559                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1560                    Some(max_author_length)
 1561                } else {
 1562                    None
 1563                }
 1564            })
 1565            .flatten();
 1566
 1567        EditorSnapshot {
 1568            mode: self.mode,
 1569            show_gutter: self.show_gutter,
 1570            show_line_numbers: self.show_line_numbers,
 1571            show_git_diff_gutter: self.show_git_diff_gutter,
 1572            show_code_actions: self.show_code_actions,
 1573            show_runnables: self.show_runnables,
 1574            git_blame_gutter_max_author_length,
 1575            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1576            scroll_anchor: self.scroll_manager.anchor(),
 1577            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1578            placeholder_text: self.placeholder_text.clone(),
 1579            diff_map: self.diff_map.snapshot(),
 1580            is_focused: self.focus_handle.is_focused(cx),
 1581            current_line_highlight: self
 1582                .current_line_highlight
 1583                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1584            gutter_hovered: self.gutter_hovered,
 1585        }
 1586    }
 1587
 1588    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1589        self.buffer.read(cx).language_at(point, cx)
 1590    }
 1591
 1592    pub fn file_at<T: ToOffset>(
 1593        &self,
 1594        point: T,
 1595        cx: &AppContext,
 1596    ) -> Option<Arc<dyn language::File>> {
 1597        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1598    }
 1599
 1600    pub fn active_excerpt(
 1601        &self,
 1602        cx: &AppContext,
 1603    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1604        self.buffer
 1605            .read(cx)
 1606            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1607    }
 1608
 1609    pub fn mode(&self) -> EditorMode {
 1610        self.mode
 1611    }
 1612
 1613    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1614        self.collaboration_hub.as_deref()
 1615    }
 1616
 1617    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1618        self.collaboration_hub = Some(hub);
 1619    }
 1620
 1621    pub fn set_custom_context_menu(
 1622        &mut self,
 1623        f: impl 'static
 1624            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1625    ) {
 1626        self.custom_context_menu = Some(Box::new(f))
 1627    }
 1628
 1629    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1630        self.completion_provider = provider;
 1631    }
 1632
 1633    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1634        self.semantics_provider.clone()
 1635    }
 1636
 1637    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1638        self.semantics_provider = provider;
 1639    }
 1640
 1641    pub fn set_inline_completion_provider<T>(
 1642        &mut self,
 1643        provider: Option<Model<T>>,
 1644        cx: &mut ViewContext<Self>,
 1645    ) where
 1646        T: InlineCompletionProvider,
 1647    {
 1648        self.inline_completion_provider =
 1649            provider.map(|provider| RegisteredInlineCompletionProvider {
 1650                _subscription: cx.observe(&provider, |this, _, cx| {
 1651                    if this.focus_handle.is_focused(cx) {
 1652                        this.update_visible_inline_completion(cx);
 1653                    }
 1654                }),
 1655                provider: Arc::new(provider),
 1656            });
 1657        self.refresh_inline_completion(false, false, cx);
 1658    }
 1659
 1660    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1661        self.placeholder_text.as_deref()
 1662    }
 1663
 1664    pub fn set_placeholder_text(
 1665        &mut self,
 1666        placeholder_text: impl Into<Arc<str>>,
 1667        cx: &mut ViewContext<Self>,
 1668    ) {
 1669        let placeholder_text = Some(placeholder_text.into());
 1670        if self.placeholder_text != placeholder_text {
 1671            self.placeholder_text = placeholder_text;
 1672            cx.notify();
 1673        }
 1674    }
 1675
 1676    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1677        self.cursor_shape = cursor_shape;
 1678
 1679        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1680        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1681
 1682        cx.notify();
 1683    }
 1684
 1685    pub fn set_current_line_highlight(
 1686        &mut self,
 1687        current_line_highlight: Option<CurrentLineHighlight>,
 1688    ) {
 1689        self.current_line_highlight = current_line_highlight;
 1690    }
 1691
 1692    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1693        self.collapse_matches = collapse_matches;
 1694    }
 1695
 1696    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1697        let buffers = self.buffer.read(cx).all_buffers();
 1698        let Some(lsp_store) = self.lsp_store(cx) else {
 1699            return;
 1700        };
 1701        lsp_store.update(cx, |lsp_store, cx| {
 1702            for buffer in buffers {
 1703                self.registered_buffers
 1704                    .entry(buffer.read(cx).remote_id())
 1705                    .or_insert_with(|| {
 1706                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1707                    });
 1708            }
 1709        })
 1710    }
 1711
 1712    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1713        if self.collapse_matches {
 1714            return range.start..range.start;
 1715        }
 1716        range.clone()
 1717    }
 1718
 1719    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1720        if self.display_map.read(cx).clip_at_line_ends != clip {
 1721            self.display_map
 1722                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1723        }
 1724    }
 1725
 1726    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1727        self.input_enabled = input_enabled;
 1728    }
 1729
 1730    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 1731        self.enable_inline_completions = enabled;
 1732    }
 1733
 1734    pub fn set_autoindent(&mut self, autoindent: bool) {
 1735        if autoindent {
 1736            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1737        } else {
 1738            self.autoindent_mode = None;
 1739        }
 1740    }
 1741
 1742    pub fn read_only(&self, cx: &AppContext) -> bool {
 1743        self.read_only || self.buffer.read(cx).read_only()
 1744    }
 1745
 1746    pub fn set_read_only(&mut self, read_only: bool) {
 1747        self.read_only = read_only;
 1748    }
 1749
 1750    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1751        self.use_autoclose = autoclose;
 1752    }
 1753
 1754    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1755        self.use_auto_surround = auto_surround;
 1756    }
 1757
 1758    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1759        self.auto_replace_emoji_shortcode = auto_replace;
 1760    }
 1761
 1762    pub fn toggle_inline_completions(
 1763        &mut self,
 1764        _: &ToggleInlineCompletions,
 1765        cx: &mut ViewContext<Self>,
 1766    ) {
 1767        if self.show_inline_completions_override.is_some() {
 1768            self.set_show_inline_completions(None, cx);
 1769        } else {
 1770            let cursor = self.selections.newest_anchor().head();
 1771            if let Some((buffer, cursor_buffer_position)) =
 1772                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1773            {
 1774                let show_inline_completions =
 1775                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1776                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1777            }
 1778        }
 1779    }
 1780
 1781    pub fn set_show_inline_completions(
 1782        &mut self,
 1783        show_inline_completions: Option<bool>,
 1784        cx: &mut ViewContext<Self>,
 1785    ) {
 1786        self.show_inline_completions_override = show_inline_completions;
 1787        self.refresh_inline_completion(false, true, cx);
 1788    }
 1789
 1790    fn should_show_inline_completions(
 1791        &self,
 1792        buffer: &Model<Buffer>,
 1793        buffer_position: language::Anchor,
 1794        cx: &AppContext,
 1795    ) -> bool {
 1796        if !self.snippet_stack.is_empty() {
 1797            return false;
 1798        }
 1799
 1800        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1801            return false;
 1802        }
 1803
 1804        if let Some(provider) = self.inline_completion_provider() {
 1805            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1806                show_inline_completions
 1807            } else {
 1808                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1809            }
 1810        } else {
 1811            false
 1812        }
 1813    }
 1814
 1815    fn inline_completions_disabled_in_scope(
 1816        &self,
 1817        buffer: &Model<Buffer>,
 1818        buffer_position: language::Anchor,
 1819        cx: &AppContext,
 1820    ) -> bool {
 1821        let snapshot = buffer.read(cx).snapshot();
 1822        let settings = snapshot.settings_at(buffer_position, cx);
 1823
 1824        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1825            return false;
 1826        };
 1827
 1828        scope.override_name().map_or(false, |scope_name| {
 1829            settings
 1830                .inline_completions_disabled_in
 1831                .iter()
 1832                .any(|s| s == scope_name)
 1833        })
 1834    }
 1835
 1836    pub fn set_use_modal_editing(&mut self, to: bool) {
 1837        self.use_modal_editing = to;
 1838    }
 1839
 1840    pub fn use_modal_editing(&self) -> bool {
 1841        self.use_modal_editing
 1842    }
 1843
 1844    fn selections_did_change(
 1845        &mut self,
 1846        local: bool,
 1847        old_cursor_position: &Anchor,
 1848        show_completions: bool,
 1849        cx: &mut ViewContext<Self>,
 1850    ) {
 1851        cx.invalidate_character_coordinates();
 1852
 1853        // Copy selections to primary selection buffer
 1854        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1855        if local {
 1856            let selections = self.selections.all::<usize>(cx);
 1857            let buffer_handle = self.buffer.read(cx).read(cx);
 1858
 1859            let mut text = String::new();
 1860            for (index, selection) in selections.iter().enumerate() {
 1861                let text_for_selection = buffer_handle
 1862                    .text_for_range(selection.start..selection.end)
 1863                    .collect::<String>();
 1864
 1865                text.push_str(&text_for_selection);
 1866                if index != selections.len() - 1 {
 1867                    text.push('\n');
 1868                }
 1869            }
 1870
 1871            if !text.is_empty() {
 1872                cx.write_to_primary(ClipboardItem::new_string(text));
 1873            }
 1874        }
 1875
 1876        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1877            self.buffer.update(cx, |buffer, cx| {
 1878                buffer.set_active_selections(
 1879                    &self.selections.disjoint_anchors(),
 1880                    self.selections.line_mode,
 1881                    self.cursor_shape,
 1882                    cx,
 1883                )
 1884            });
 1885        }
 1886        let display_map = self
 1887            .display_map
 1888            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1889        let buffer = &display_map.buffer_snapshot;
 1890        self.add_selections_state = None;
 1891        self.select_next_state = None;
 1892        self.select_prev_state = None;
 1893        self.select_larger_syntax_node_stack.clear();
 1894        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1895        self.snippet_stack
 1896            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1897        self.take_rename(false, cx);
 1898
 1899        let new_cursor_position = self.selections.newest_anchor().head();
 1900
 1901        self.push_to_nav_history(
 1902            *old_cursor_position,
 1903            Some(new_cursor_position.to_point(buffer)),
 1904            cx,
 1905        );
 1906
 1907        if local {
 1908            let new_cursor_position = self.selections.newest_anchor().head();
 1909            let mut context_menu = self.context_menu.borrow_mut();
 1910            let completion_menu = match context_menu.as_ref() {
 1911                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1912                _ => {
 1913                    *context_menu = None;
 1914                    None
 1915                }
 1916            };
 1917
 1918            if let Some(completion_menu) = completion_menu {
 1919                let cursor_position = new_cursor_position.to_offset(buffer);
 1920                let (word_range, kind) =
 1921                    buffer.surrounding_word(completion_menu.initial_position, true);
 1922                if kind == Some(CharKind::Word)
 1923                    && word_range.to_inclusive().contains(&cursor_position)
 1924                {
 1925                    let mut completion_menu = completion_menu.clone();
 1926                    drop(context_menu);
 1927
 1928                    let query = Self::completion_query(buffer, cursor_position);
 1929                    cx.spawn(move |this, mut cx| async move {
 1930                        completion_menu
 1931                            .filter(query.as_deref(), cx.background_executor().clone())
 1932                            .await;
 1933
 1934                        this.update(&mut cx, |this, cx| {
 1935                            let mut context_menu = this.context_menu.borrow_mut();
 1936                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1937                            else {
 1938                                return;
 1939                            };
 1940
 1941                            if menu.id > completion_menu.id {
 1942                                return;
 1943                            }
 1944
 1945                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1946                            drop(context_menu);
 1947                            cx.notify();
 1948                        })
 1949                    })
 1950                    .detach();
 1951
 1952                    if show_completions {
 1953                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1954                    }
 1955                } else {
 1956                    drop(context_menu);
 1957                    self.hide_context_menu(cx);
 1958                }
 1959            } else {
 1960                drop(context_menu);
 1961            }
 1962
 1963            hide_hover(self, cx);
 1964
 1965            if old_cursor_position.to_display_point(&display_map).row()
 1966                != new_cursor_position.to_display_point(&display_map).row()
 1967            {
 1968                self.available_code_actions.take();
 1969            }
 1970            self.refresh_code_actions(cx);
 1971            self.refresh_document_highlights(cx);
 1972            refresh_matching_bracket_highlights(self, cx);
 1973            self.update_visible_inline_completion(cx);
 1974            linked_editing_ranges::refresh_linked_ranges(self, cx);
 1975            if self.git_blame_inline_enabled {
 1976                self.start_inline_blame_timer(cx);
 1977            }
 1978        }
 1979
 1980        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 1981        cx.emit(EditorEvent::SelectionsChanged { local });
 1982
 1983        if self.selections.disjoint_anchors().len() == 1 {
 1984            cx.emit(SearchEvent::ActiveMatchChanged)
 1985        }
 1986        cx.notify();
 1987    }
 1988
 1989    pub fn change_selections<R>(
 1990        &mut self,
 1991        autoscroll: Option<Autoscroll>,
 1992        cx: &mut ViewContext<Self>,
 1993        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1994    ) -> R {
 1995        self.change_selections_inner(autoscroll, true, cx, change)
 1996    }
 1997
 1998    pub fn change_selections_inner<R>(
 1999        &mut self,
 2000        autoscroll: Option<Autoscroll>,
 2001        request_completions: bool,
 2002        cx: &mut ViewContext<Self>,
 2003        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2004    ) -> R {
 2005        let old_cursor_position = self.selections.newest_anchor().head();
 2006        self.push_to_selection_history();
 2007
 2008        let (changed, result) = self.selections.change_with(cx, change);
 2009
 2010        if changed {
 2011            if let Some(autoscroll) = autoscroll {
 2012                self.request_autoscroll(autoscroll, cx);
 2013            }
 2014            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2015
 2016            if self.should_open_signature_help_automatically(
 2017                &old_cursor_position,
 2018                self.signature_help_state.backspace_pressed(),
 2019                cx,
 2020            ) {
 2021                self.show_signature_help(&ShowSignatureHelp, cx);
 2022            }
 2023            self.signature_help_state.set_backspace_pressed(false);
 2024        }
 2025
 2026        result
 2027    }
 2028
 2029    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2030    where
 2031        I: IntoIterator<Item = (Range<S>, T)>,
 2032        S: ToOffset,
 2033        T: Into<Arc<str>>,
 2034    {
 2035        if self.read_only(cx) {
 2036            return;
 2037        }
 2038
 2039        self.buffer
 2040            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2041    }
 2042
 2043    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2044    where
 2045        I: IntoIterator<Item = (Range<S>, T)>,
 2046        S: ToOffset,
 2047        T: Into<Arc<str>>,
 2048    {
 2049        if self.read_only(cx) {
 2050            return;
 2051        }
 2052
 2053        self.buffer.update(cx, |buffer, cx| {
 2054            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2055        });
 2056    }
 2057
 2058    pub fn edit_with_block_indent<I, S, T>(
 2059        &mut self,
 2060        edits: I,
 2061        original_indent_columns: Vec<u32>,
 2062        cx: &mut ViewContext<Self>,
 2063    ) where
 2064        I: IntoIterator<Item = (Range<S>, T)>,
 2065        S: ToOffset,
 2066        T: Into<Arc<str>>,
 2067    {
 2068        if self.read_only(cx) {
 2069            return;
 2070        }
 2071
 2072        self.buffer.update(cx, |buffer, cx| {
 2073            buffer.edit(
 2074                edits,
 2075                Some(AutoindentMode::Block {
 2076                    original_indent_columns,
 2077                }),
 2078                cx,
 2079            )
 2080        });
 2081    }
 2082
 2083    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2084        self.hide_context_menu(cx);
 2085
 2086        match phase {
 2087            SelectPhase::Begin {
 2088                position,
 2089                add,
 2090                click_count,
 2091            } => self.begin_selection(position, add, click_count, cx),
 2092            SelectPhase::BeginColumnar {
 2093                position,
 2094                goal_column,
 2095                reset,
 2096            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2097            SelectPhase::Extend {
 2098                position,
 2099                click_count,
 2100            } => self.extend_selection(position, click_count, cx),
 2101            SelectPhase::Update {
 2102                position,
 2103                goal_column,
 2104                scroll_delta,
 2105            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2106            SelectPhase::End => self.end_selection(cx),
 2107        }
 2108    }
 2109
 2110    fn extend_selection(
 2111        &mut self,
 2112        position: DisplayPoint,
 2113        click_count: usize,
 2114        cx: &mut ViewContext<Self>,
 2115    ) {
 2116        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2117        let tail = self.selections.newest::<usize>(cx).tail();
 2118        self.begin_selection(position, false, click_count, cx);
 2119
 2120        let position = position.to_offset(&display_map, Bias::Left);
 2121        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2122
 2123        let mut pending_selection = self
 2124            .selections
 2125            .pending_anchor()
 2126            .expect("extend_selection not called with pending selection");
 2127        if position >= tail {
 2128            pending_selection.start = tail_anchor;
 2129        } else {
 2130            pending_selection.end = tail_anchor;
 2131            pending_selection.reversed = true;
 2132        }
 2133
 2134        let mut pending_mode = self.selections.pending_mode().unwrap();
 2135        match &mut pending_mode {
 2136            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2137            _ => {}
 2138        }
 2139
 2140        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2141            s.set_pending(pending_selection, pending_mode)
 2142        });
 2143    }
 2144
 2145    fn begin_selection(
 2146        &mut self,
 2147        position: DisplayPoint,
 2148        add: bool,
 2149        click_count: usize,
 2150        cx: &mut ViewContext<Self>,
 2151    ) {
 2152        if !self.focus_handle.is_focused(cx) {
 2153            self.last_focused_descendant = None;
 2154            cx.focus(&self.focus_handle);
 2155        }
 2156
 2157        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2158        let buffer = &display_map.buffer_snapshot;
 2159        let newest_selection = self.selections.newest_anchor().clone();
 2160        let position = display_map.clip_point(position, Bias::Left);
 2161
 2162        let start;
 2163        let end;
 2164        let mode;
 2165        let mut auto_scroll;
 2166        match click_count {
 2167            1 => {
 2168                start = buffer.anchor_before(position.to_point(&display_map));
 2169                end = start;
 2170                mode = SelectMode::Character;
 2171                auto_scroll = true;
 2172            }
 2173            2 => {
 2174                let range = movement::surrounding_word(&display_map, position);
 2175                start = buffer.anchor_before(range.start.to_point(&display_map));
 2176                end = buffer.anchor_before(range.end.to_point(&display_map));
 2177                mode = SelectMode::Word(start..end);
 2178                auto_scroll = true;
 2179            }
 2180            3 => {
 2181                let position = display_map
 2182                    .clip_point(position, Bias::Left)
 2183                    .to_point(&display_map);
 2184                let line_start = display_map.prev_line_boundary(position).0;
 2185                let next_line_start = buffer.clip_point(
 2186                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2187                    Bias::Left,
 2188                );
 2189                start = buffer.anchor_before(line_start);
 2190                end = buffer.anchor_before(next_line_start);
 2191                mode = SelectMode::Line(start..end);
 2192                auto_scroll = true;
 2193            }
 2194            _ => {
 2195                start = buffer.anchor_before(0);
 2196                end = buffer.anchor_before(buffer.len());
 2197                mode = SelectMode::All;
 2198                auto_scroll = false;
 2199            }
 2200        }
 2201        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2202
 2203        let point_to_delete: Option<usize> = {
 2204            let selected_points: Vec<Selection<Point>> =
 2205                self.selections.disjoint_in_range(start..end, cx);
 2206
 2207            if !add || click_count > 1 {
 2208                None
 2209            } else if !selected_points.is_empty() {
 2210                Some(selected_points[0].id)
 2211            } else {
 2212                let clicked_point_already_selected =
 2213                    self.selections.disjoint.iter().find(|selection| {
 2214                        selection.start.to_point(buffer) == start.to_point(buffer)
 2215                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2216                    });
 2217
 2218                clicked_point_already_selected.map(|selection| selection.id)
 2219            }
 2220        };
 2221
 2222        let selections_count = self.selections.count();
 2223
 2224        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2225            if let Some(point_to_delete) = point_to_delete {
 2226                s.delete(point_to_delete);
 2227
 2228                if selections_count == 1 {
 2229                    s.set_pending_anchor_range(start..end, mode);
 2230                }
 2231            } else {
 2232                if !add {
 2233                    s.clear_disjoint();
 2234                } else if click_count > 1 {
 2235                    s.delete(newest_selection.id)
 2236                }
 2237
 2238                s.set_pending_anchor_range(start..end, mode);
 2239            }
 2240        });
 2241    }
 2242
 2243    fn begin_columnar_selection(
 2244        &mut self,
 2245        position: DisplayPoint,
 2246        goal_column: u32,
 2247        reset: bool,
 2248        cx: &mut ViewContext<Self>,
 2249    ) {
 2250        if !self.focus_handle.is_focused(cx) {
 2251            self.last_focused_descendant = None;
 2252            cx.focus(&self.focus_handle);
 2253        }
 2254
 2255        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2256
 2257        if reset {
 2258            let pointer_position = display_map
 2259                .buffer_snapshot
 2260                .anchor_before(position.to_point(&display_map));
 2261
 2262            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2263                s.clear_disjoint();
 2264                s.set_pending_anchor_range(
 2265                    pointer_position..pointer_position,
 2266                    SelectMode::Character,
 2267                );
 2268            });
 2269        }
 2270
 2271        let tail = self.selections.newest::<Point>(cx).tail();
 2272        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2273
 2274        if !reset {
 2275            self.select_columns(
 2276                tail.to_display_point(&display_map),
 2277                position,
 2278                goal_column,
 2279                &display_map,
 2280                cx,
 2281            );
 2282        }
 2283    }
 2284
 2285    fn update_selection(
 2286        &mut self,
 2287        position: DisplayPoint,
 2288        goal_column: u32,
 2289        scroll_delta: gpui::Point<f32>,
 2290        cx: &mut ViewContext<Self>,
 2291    ) {
 2292        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2293
 2294        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2295            let tail = tail.to_display_point(&display_map);
 2296            self.select_columns(tail, position, goal_column, &display_map, cx);
 2297        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2298            let buffer = self.buffer.read(cx).snapshot(cx);
 2299            let head;
 2300            let tail;
 2301            let mode = self.selections.pending_mode().unwrap();
 2302            match &mode {
 2303                SelectMode::Character => {
 2304                    head = position.to_point(&display_map);
 2305                    tail = pending.tail().to_point(&buffer);
 2306                }
 2307                SelectMode::Word(original_range) => {
 2308                    let original_display_range = original_range.start.to_display_point(&display_map)
 2309                        ..original_range.end.to_display_point(&display_map);
 2310                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2311                        ..original_display_range.end.to_point(&display_map);
 2312                    if movement::is_inside_word(&display_map, position)
 2313                        || original_display_range.contains(&position)
 2314                    {
 2315                        let word_range = movement::surrounding_word(&display_map, position);
 2316                        if word_range.start < original_display_range.start {
 2317                            head = word_range.start.to_point(&display_map);
 2318                        } else {
 2319                            head = word_range.end.to_point(&display_map);
 2320                        }
 2321                    } else {
 2322                        head = position.to_point(&display_map);
 2323                    }
 2324
 2325                    if head <= original_buffer_range.start {
 2326                        tail = original_buffer_range.end;
 2327                    } else {
 2328                        tail = original_buffer_range.start;
 2329                    }
 2330                }
 2331                SelectMode::Line(original_range) => {
 2332                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2333
 2334                    let position = display_map
 2335                        .clip_point(position, Bias::Left)
 2336                        .to_point(&display_map);
 2337                    let line_start = display_map.prev_line_boundary(position).0;
 2338                    let next_line_start = buffer.clip_point(
 2339                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2340                        Bias::Left,
 2341                    );
 2342
 2343                    if line_start < original_range.start {
 2344                        head = line_start
 2345                    } else {
 2346                        head = next_line_start
 2347                    }
 2348
 2349                    if head <= original_range.start {
 2350                        tail = original_range.end;
 2351                    } else {
 2352                        tail = original_range.start;
 2353                    }
 2354                }
 2355                SelectMode::All => {
 2356                    return;
 2357                }
 2358            };
 2359
 2360            if head < tail {
 2361                pending.start = buffer.anchor_before(head);
 2362                pending.end = buffer.anchor_before(tail);
 2363                pending.reversed = true;
 2364            } else {
 2365                pending.start = buffer.anchor_before(tail);
 2366                pending.end = buffer.anchor_before(head);
 2367                pending.reversed = false;
 2368            }
 2369
 2370            self.change_selections(None, cx, |s| {
 2371                s.set_pending(pending, mode);
 2372            });
 2373        } else {
 2374            log::error!("update_selection dispatched with no pending selection");
 2375            return;
 2376        }
 2377
 2378        self.apply_scroll_delta(scroll_delta, cx);
 2379        cx.notify();
 2380    }
 2381
 2382    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2383        self.columnar_selection_tail.take();
 2384        if self.selections.pending_anchor().is_some() {
 2385            let selections = self.selections.all::<usize>(cx);
 2386            self.change_selections(None, cx, |s| {
 2387                s.select(selections);
 2388                s.clear_pending();
 2389            });
 2390        }
 2391    }
 2392
 2393    fn select_columns(
 2394        &mut self,
 2395        tail: DisplayPoint,
 2396        head: DisplayPoint,
 2397        goal_column: u32,
 2398        display_map: &DisplaySnapshot,
 2399        cx: &mut ViewContext<Self>,
 2400    ) {
 2401        let start_row = cmp::min(tail.row(), head.row());
 2402        let end_row = cmp::max(tail.row(), head.row());
 2403        let start_column = cmp::min(tail.column(), goal_column);
 2404        let end_column = cmp::max(tail.column(), goal_column);
 2405        let reversed = start_column < tail.column();
 2406
 2407        let selection_ranges = (start_row.0..=end_row.0)
 2408            .map(DisplayRow)
 2409            .filter_map(|row| {
 2410                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2411                    let start = display_map
 2412                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2413                        .to_point(display_map);
 2414                    let end = display_map
 2415                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2416                        .to_point(display_map);
 2417                    if reversed {
 2418                        Some(end..start)
 2419                    } else {
 2420                        Some(start..end)
 2421                    }
 2422                } else {
 2423                    None
 2424                }
 2425            })
 2426            .collect::<Vec<_>>();
 2427
 2428        self.change_selections(None, cx, |s| {
 2429            s.select_ranges(selection_ranges);
 2430        });
 2431        cx.notify();
 2432    }
 2433
 2434    pub fn has_pending_nonempty_selection(&self) -> bool {
 2435        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2436            Some(Selection { start, end, .. }) => start != end,
 2437            None => false,
 2438        };
 2439
 2440        pending_nonempty_selection
 2441            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2442    }
 2443
 2444    pub fn has_pending_selection(&self) -> bool {
 2445        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2446    }
 2447
 2448    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2449        if self.clear_expanded_diff_hunks(cx) {
 2450            cx.notify();
 2451            return;
 2452        }
 2453        if self.dismiss_menus_and_popups(true, cx) {
 2454            return;
 2455        }
 2456
 2457        if self.mode == EditorMode::Full
 2458            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2459        {
 2460            return;
 2461        }
 2462
 2463        cx.propagate();
 2464    }
 2465
 2466    pub fn dismiss_menus_and_popups(
 2467        &mut self,
 2468        should_report_inline_completion_event: bool,
 2469        cx: &mut ViewContext<Self>,
 2470    ) -> bool {
 2471        if self.take_rename(false, cx).is_some() {
 2472            return true;
 2473        }
 2474
 2475        if hide_hover(self, cx) {
 2476            return true;
 2477        }
 2478
 2479        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2480            return true;
 2481        }
 2482
 2483        if self.hide_context_menu(cx).is_some() {
 2484            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2485                self.update_visible_inline_completion(cx);
 2486            }
 2487            return true;
 2488        }
 2489
 2490        if self.mouse_context_menu.take().is_some() {
 2491            return true;
 2492        }
 2493
 2494        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2495            return true;
 2496        }
 2497
 2498        if self.snippet_stack.pop().is_some() {
 2499            return true;
 2500        }
 2501
 2502        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2503            self.dismiss_diagnostics(cx);
 2504            return true;
 2505        }
 2506
 2507        false
 2508    }
 2509
 2510    fn linked_editing_ranges_for(
 2511        &self,
 2512        selection: Range<text::Anchor>,
 2513        cx: &AppContext,
 2514    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2515        if self.linked_edit_ranges.is_empty() {
 2516            return None;
 2517        }
 2518        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2519            selection.end.buffer_id.and_then(|end_buffer_id| {
 2520                if selection.start.buffer_id != Some(end_buffer_id) {
 2521                    return None;
 2522                }
 2523                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2524                let snapshot = buffer.read(cx).snapshot();
 2525                self.linked_edit_ranges
 2526                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2527                    .map(|ranges| (ranges, snapshot, buffer))
 2528            })?;
 2529        use text::ToOffset as TO;
 2530        // find offset from the start of current range to current cursor position
 2531        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2532
 2533        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2534        let start_difference = start_offset - start_byte_offset;
 2535        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2536        let end_difference = end_offset - start_byte_offset;
 2537        // Current range has associated linked ranges.
 2538        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2539        for range in linked_ranges.iter() {
 2540            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2541            let end_offset = start_offset + end_difference;
 2542            let start_offset = start_offset + start_difference;
 2543            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2544                continue;
 2545            }
 2546            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 2547                if s.start.buffer_id != selection.start.buffer_id
 2548                    || s.end.buffer_id != selection.end.buffer_id
 2549                {
 2550                    return false;
 2551                }
 2552                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2553                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2554            }) {
 2555                continue;
 2556            }
 2557            let start = buffer_snapshot.anchor_after(start_offset);
 2558            let end = buffer_snapshot.anchor_after(end_offset);
 2559            linked_edits
 2560                .entry(buffer.clone())
 2561                .or_default()
 2562                .push(start..end);
 2563        }
 2564        Some(linked_edits)
 2565    }
 2566
 2567    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2568        let text: Arc<str> = text.into();
 2569
 2570        if self.read_only(cx) {
 2571            return;
 2572        }
 2573
 2574        let selections = self.selections.all_adjusted(cx);
 2575        let mut bracket_inserted = false;
 2576        let mut edits = Vec::new();
 2577        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2578        let mut new_selections = Vec::with_capacity(selections.len());
 2579        let mut new_autoclose_regions = Vec::new();
 2580        let snapshot = self.buffer.read(cx).read(cx);
 2581
 2582        for (selection, autoclose_region) in
 2583            self.selections_with_autoclose_regions(selections, &snapshot)
 2584        {
 2585            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2586                // Determine if the inserted text matches the opening or closing
 2587                // bracket of any of this language's bracket pairs.
 2588                let mut bracket_pair = None;
 2589                let mut is_bracket_pair_start = false;
 2590                let mut is_bracket_pair_end = false;
 2591                if !text.is_empty() {
 2592                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2593                    //  and they are removing the character that triggered IME popup.
 2594                    for (pair, enabled) in scope.brackets() {
 2595                        if !pair.close && !pair.surround {
 2596                            continue;
 2597                        }
 2598
 2599                        if enabled && pair.start.ends_with(text.as_ref()) {
 2600                            let prefix_len = pair.start.len() - text.len();
 2601                            let preceding_text_matches_prefix = prefix_len == 0
 2602                                || (selection.start.column >= (prefix_len as u32)
 2603                                    && snapshot.contains_str_at(
 2604                                        Point::new(
 2605                                            selection.start.row,
 2606                                            selection.start.column - (prefix_len as u32),
 2607                                        ),
 2608                                        &pair.start[..prefix_len],
 2609                                    ));
 2610                            if preceding_text_matches_prefix {
 2611                                bracket_pair = Some(pair.clone());
 2612                                is_bracket_pair_start = true;
 2613                                break;
 2614                            }
 2615                        }
 2616                        if pair.end.as_str() == text.as_ref() {
 2617                            bracket_pair = Some(pair.clone());
 2618                            is_bracket_pair_end = true;
 2619                            break;
 2620                        }
 2621                    }
 2622                }
 2623
 2624                if let Some(bracket_pair) = bracket_pair {
 2625                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2626                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2627                    let auto_surround =
 2628                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2629                    if selection.is_empty() {
 2630                        if is_bracket_pair_start {
 2631                            // If the inserted text is a suffix of an opening bracket and the
 2632                            // selection is preceded by the rest of the opening bracket, then
 2633                            // insert the closing bracket.
 2634                            let following_text_allows_autoclose = snapshot
 2635                                .chars_at(selection.start)
 2636                                .next()
 2637                                .map_or(true, |c| scope.should_autoclose_before(c));
 2638
 2639                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2640                                && bracket_pair.start.len() == 1
 2641                            {
 2642                                let target = bracket_pair.start.chars().next().unwrap();
 2643                                let current_line_count = snapshot
 2644                                    .reversed_chars_at(selection.start)
 2645                                    .take_while(|&c| c != '\n')
 2646                                    .filter(|&c| c == target)
 2647                                    .count();
 2648                                current_line_count % 2 == 1
 2649                            } else {
 2650                                false
 2651                            };
 2652
 2653                            if autoclose
 2654                                && bracket_pair.close
 2655                                && following_text_allows_autoclose
 2656                                && !is_closing_quote
 2657                            {
 2658                                let anchor = snapshot.anchor_before(selection.end);
 2659                                new_selections.push((selection.map(|_| anchor), text.len()));
 2660                                new_autoclose_regions.push((
 2661                                    anchor,
 2662                                    text.len(),
 2663                                    selection.id,
 2664                                    bracket_pair.clone(),
 2665                                ));
 2666                                edits.push((
 2667                                    selection.range(),
 2668                                    format!("{}{}", text, bracket_pair.end).into(),
 2669                                ));
 2670                                bracket_inserted = true;
 2671                                continue;
 2672                            }
 2673                        }
 2674
 2675                        if let Some(region) = autoclose_region {
 2676                            // If the selection is followed by an auto-inserted closing bracket,
 2677                            // then don't insert that closing bracket again; just move the selection
 2678                            // past the closing bracket.
 2679                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2680                                && text.as_ref() == region.pair.end.as_str();
 2681                            if should_skip {
 2682                                let anchor = snapshot.anchor_after(selection.end);
 2683                                new_selections
 2684                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2685                                continue;
 2686                            }
 2687                        }
 2688
 2689                        let always_treat_brackets_as_autoclosed = snapshot
 2690                            .settings_at(selection.start, cx)
 2691                            .always_treat_brackets_as_autoclosed;
 2692                        if always_treat_brackets_as_autoclosed
 2693                            && is_bracket_pair_end
 2694                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2695                        {
 2696                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2697                            // and the inserted text is a closing bracket and the selection is followed
 2698                            // by the closing bracket then move the selection past the closing bracket.
 2699                            let anchor = snapshot.anchor_after(selection.end);
 2700                            new_selections.push((selection.map(|_| anchor), text.len()));
 2701                            continue;
 2702                        }
 2703                    }
 2704                    // If an opening bracket is 1 character long and is typed while
 2705                    // text is selected, then surround that text with the bracket pair.
 2706                    else if auto_surround
 2707                        && bracket_pair.surround
 2708                        && is_bracket_pair_start
 2709                        && bracket_pair.start.chars().count() == 1
 2710                    {
 2711                        edits.push((selection.start..selection.start, text.clone()));
 2712                        edits.push((
 2713                            selection.end..selection.end,
 2714                            bracket_pair.end.as_str().into(),
 2715                        ));
 2716                        bracket_inserted = true;
 2717                        new_selections.push((
 2718                            Selection {
 2719                                id: selection.id,
 2720                                start: snapshot.anchor_after(selection.start),
 2721                                end: snapshot.anchor_before(selection.end),
 2722                                reversed: selection.reversed,
 2723                                goal: selection.goal,
 2724                            },
 2725                            0,
 2726                        ));
 2727                        continue;
 2728                    }
 2729                }
 2730            }
 2731
 2732            if self.auto_replace_emoji_shortcode
 2733                && selection.is_empty()
 2734                && text.as_ref().ends_with(':')
 2735            {
 2736                if let Some(possible_emoji_short_code) =
 2737                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2738                {
 2739                    if !possible_emoji_short_code.is_empty() {
 2740                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2741                            let emoji_shortcode_start = Point::new(
 2742                                selection.start.row,
 2743                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2744                            );
 2745
 2746                            // Remove shortcode from buffer
 2747                            edits.push((
 2748                                emoji_shortcode_start..selection.start,
 2749                                "".to_string().into(),
 2750                            ));
 2751                            new_selections.push((
 2752                                Selection {
 2753                                    id: selection.id,
 2754                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2755                                    end: snapshot.anchor_before(selection.start),
 2756                                    reversed: selection.reversed,
 2757                                    goal: selection.goal,
 2758                                },
 2759                                0,
 2760                            ));
 2761
 2762                            // Insert emoji
 2763                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2764                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2765                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2766
 2767                            continue;
 2768                        }
 2769                    }
 2770                }
 2771            }
 2772
 2773            // If not handling any auto-close operation, then just replace the selected
 2774            // text with the given input and move the selection to the end of the
 2775            // newly inserted text.
 2776            let anchor = snapshot.anchor_after(selection.end);
 2777            if !self.linked_edit_ranges.is_empty() {
 2778                let start_anchor = snapshot.anchor_before(selection.start);
 2779
 2780                let is_word_char = text.chars().next().map_or(true, |char| {
 2781                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2782                    classifier.is_word(char)
 2783                });
 2784
 2785                if is_word_char {
 2786                    if let Some(ranges) = self
 2787                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2788                    {
 2789                        for (buffer, edits) in ranges {
 2790                            linked_edits
 2791                                .entry(buffer.clone())
 2792                                .or_default()
 2793                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2794                        }
 2795                    }
 2796                }
 2797            }
 2798
 2799            new_selections.push((selection.map(|_| anchor), 0));
 2800            edits.push((selection.start..selection.end, text.clone()));
 2801        }
 2802
 2803        drop(snapshot);
 2804
 2805        self.transact(cx, |this, cx| {
 2806            this.buffer.update(cx, |buffer, cx| {
 2807                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2808            });
 2809            for (buffer, edits) in linked_edits {
 2810                buffer.update(cx, |buffer, cx| {
 2811                    let snapshot = buffer.snapshot();
 2812                    let edits = edits
 2813                        .into_iter()
 2814                        .map(|(range, text)| {
 2815                            use text::ToPoint as TP;
 2816                            let end_point = TP::to_point(&range.end, &snapshot);
 2817                            let start_point = TP::to_point(&range.start, &snapshot);
 2818                            (start_point..end_point, text)
 2819                        })
 2820                        .sorted_by_key(|(range, _)| range.start)
 2821                        .collect::<Vec<_>>();
 2822                    buffer.edit(edits, None, cx);
 2823                })
 2824            }
 2825            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2826            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2827            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2828            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2829                .zip(new_selection_deltas)
 2830                .map(|(selection, delta)| Selection {
 2831                    id: selection.id,
 2832                    start: selection.start + delta,
 2833                    end: selection.end + delta,
 2834                    reversed: selection.reversed,
 2835                    goal: SelectionGoal::None,
 2836                })
 2837                .collect::<Vec<_>>();
 2838
 2839            let mut i = 0;
 2840            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2841                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2842                let start = map.buffer_snapshot.anchor_before(position);
 2843                let end = map.buffer_snapshot.anchor_after(position);
 2844                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2845                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2846                        Ordering::Less => i += 1,
 2847                        Ordering::Greater => break,
 2848                        Ordering::Equal => {
 2849                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2850                                Ordering::Less => i += 1,
 2851                                Ordering::Equal => break,
 2852                                Ordering::Greater => break,
 2853                            }
 2854                        }
 2855                    }
 2856                }
 2857                this.autoclose_regions.insert(
 2858                    i,
 2859                    AutocloseRegion {
 2860                        selection_id,
 2861                        range: start..end,
 2862                        pair,
 2863                    },
 2864                );
 2865            }
 2866
 2867            let had_active_inline_completion = this.has_active_inline_completion();
 2868            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2869                s.select(new_selections)
 2870            });
 2871
 2872            if !bracket_inserted {
 2873                if let Some(on_type_format_task) =
 2874                    this.trigger_on_type_formatting(text.to_string(), cx)
 2875                {
 2876                    on_type_format_task.detach_and_log_err(cx);
 2877                }
 2878            }
 2879
 2880            let editor_settings = EditorSettings::get_global(cx);
 2881            if bracket_inserted
 2882                && (editor_settings.auto_signature_help
 2883                    || editor_settings.show_signature_help_after_edits)
 2884            {
 2885                this.show_signature_help(&ShowSignatureHelp, cx);
 2886            }
 2887
 2888            let trigger_in_words =
 2889                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2890            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2891            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2892            this.refresh_inline_completion(true, false, cx);
 2893        });
 2894    }
 2895
 2896    fn find_possible_emoji_shortcode_at_position(
 2897        snapshot: &MultiBufferSnapshot,
 2898        position: Point,
 2899    ) -> Option<String> {
 2900        let mut chars = Vec::new();
 2901        let mut found_colon = false;
 2902        for char in snapshot.reversed_chars_at(position).take(100) {
 2903            // Found a possible emoji shortcode in the middle of the buffer
 2904            if found_colon {
 2905                if char.is_whitespace() {
 2906                    chars.reverse();
 2907                    return Some(chars.iter().collect());
 2908                }
 2909                // If the previous character is not a whitespace, we are in the middle of a word
 2910                // and we only want to complete the shortcode if the word is made up of other emojis
 2911                let mut containing_word = String::new();
 2912                for ch in snapshot
 2913                    .reversed_chars_at(position)
 2914                    .skip(chars.len() + 1)
 2915                    .take(100)
 2916                {
 2917                    if ch.is_whitespace() {
 2918                        break;
 2919                    }
 2920                    containing_word.push(ch);
 2921                }
 2922                let containing_word = containing_word.chars().rev().collect::<String>();
 2923                if util::word_consists_of_emojis(containing_word.as_str()) {
 2924                    chars.reverse();
 2925                    return Some(chars.iter().collect());
 2926                }
 2927            }
 2928
 2929            if char.is_whitespace() || !char.is_ascii() {
 2930                return None;
 2931            }
 2932            if char == ':' {
 2933                found_colon = true;
 2934            } else {
 2935                chars.push(char);
 2936            }
 2937        }
 2938        // Found a possible emoji shortcode at the beginning of the buffer
 2939        chars.reverse();
 2940        Some(chars.iter().collect())
 2941    }
 2942
 2943    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2944        self.transact(cx, |this, cx| {
 2945            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2946                let selections = this.selections.all::<usize>(cx);
 2947                let multi_buffer = this.buffer.read(cx);
 2948                let buffer = multi_buffer.snapshot(cx);
 2949                selections
 2950                    .iter()
 2951                    .map(|selection| {
 2952                        let start_point = selection.start.to_point(&buffer);
 2953                        let mut indent =
 2954                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2955                        indent.len = cmp::min(indent.len, start_point.column);
 2956                        let start = selection.start;
 2957                        let end = selection.end;
 2958                        let selection_is_empty = start == end;
 2959                        let language_scope = buffer.language_scope_at(start);
 2960                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2961                            &language_scope
 2962                        {
 2963                            let leading_whitespace_len = buffer
 2964                                .reversed_chars_at(start)
 2965                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2966                                .map(|c| c.len_utf8())
 2967                                .sum::<usize>();
 2968
 2969                            let trailing_whitespace_len = buffer
 2970                                .chars_at(end)
 2971                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2972                                .map(|c| c.len_utf8())
 2973                                .sum::<usize>();
 2974
 2975                            let insert_extra_newline =
 2976                                language.brackets().any(|(pair, enabled)| {
 2977                                    let pair_start = pair.start.trim_end();
 2978                                    let pair_end = pair.end.trim_start();
 2979
 2980                                    enabled
 2981                                        && pair.newline
 2982                                        && buffer.contains_str_at(
 2983                                            end + trailing_whitespace_len,
 2984                                            pair_end,
 2985                                        )
 2986                                        && buffer.contains_str_at(
 2987                                            (start - leading_whitespace_len)
 2988                                                .saturating_sub(pair_start.len()),
 2989                                            pair_start,
 2990                                        )
 2991                                });
 2992
 2993                            // Comment extension on newline is allowed only for cursor selections
 2994                            let comment_delimiter = maybe!({
 2995                                if !selection_is_empty {
 2996                                    return None;
 2997                                }
 2998
 2999                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3000                                    return None;
 3001                                }
 3002
 3003                                let delimiters = language.line_comment_prefixes();
 3004                                let max_len_of_delimiter =
 3005                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3006                                let (snapshot, range) =
 3007                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3008
 3009                                let mut index_of_first_non_whitespace = 0;
 3010                                let comment_candidate = snapshot
 3011                                    .chars_for_range(range)
 3012                                    .skip_while(|c| {
 3013                                        let should_skip = c.is_whitespace();
 3014                                        if should_skip {
 3015                                            index_of_first_non_whitespace += 1;
 3016                                        }
 3017                                        should_skip
 3018                                    })
 3019                                    .take(max_len_of_delimiter)
 3020                                    .collect::<String>();
 3021                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3022                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3023                                })?;
 3024                                let cursor_is_placed_after_comment_marker =
 3025                                    index_of_first_non_whitespace + comment_prefix.len()
 3026                                        <= start_point.column as usize;
 3027                                if cursor_is_placed_after_comment_marker {
 3028                                    Some(comment_prefix.clone())
 3029                                } else {
 3030                                    None
 3031                                }
 3032                            });
 3033                            (comment_delimiter, insert_extra_newline)
 3034                        } else {
 3035                            (None, false)
 3036                        };
 3037
 3038                        let capacity_for_delimiter = comment_delimiter
 3039                            .as_deref()
 3040                            .map(str::len)
 3041                            .unwrap_or_default();
 3042                        let mut new_text =
 3043                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3044                        new_text.push('\n');
 3045                        new_text.extend(indent.chars());
 3046                        if let Some(delimiter) = &comment_delimiter {
 3047                            new_text.push_str(delimiter);
 3048                        }
 3049                        if insert_extra_newline {
 3050                            new_text = new_text.repeat(2);
 3051                        }
 3052
 3053                        let anchor = buffer.anchor_after(end);
 3054                        let new_selection = selection.map(|_| anchor);
 3055                        (
 3056                            (start..end, new_text),
 3057                            (insert_extra_newline, new_selection),
 3058                        )
 3059                    })
 3060                    .unzip()
 3061            };
 3062
 3063            this.edit_with_autoindent(edits, cx);
 3064            let buffer = this.buffer.read(cx).snapshot(cx);
 3065            let new_selections = selection_fixup_info
 3066                .into_iter()
 3067                .map(|(extra_newline_inserted, new_selection)| {
 3068                    let mut cursor = new_selection.end.to_point(&buffer);
 3069                    if extra_newline_inserted {
 3070                        cursor.row -= 1;
 3071                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3072                    }
 3073                    new_selection.map(|_| cursor)
 3074                })
 3075                .collect();
 3076
 3077            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3078            this.refresh_inline_completion(true, false, cx);
 3079        });
 3080    }
 3081
 3082    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3083        let buffer = self.buffer.read(cx);
 3084        let snapshot = buffer.snapshot(cx);
 3085
 3086        let mut edits = Vec::new();
 3087        let mut rows = Vec::new();
 3088
 3089        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3090            let cursor = selection.head();
 3091            let row = cursor.row;
 3092
 3093            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3094
 3095            let newline = "\n".to_string();
 3096            edits.push((start_of_line..start_of_line, newline));
 3097
 3098            rows.push(row + rows_inserted as u32);
 3099        }
 3100
 3101        self.transact(cx, |editor, cx| {
 3102            editor.edit(edits, cx);
 3103
 3104            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3105                let mut index = 0;
 3106                s.move_cursors_with(|map, _, _| {
 3107                    let row = rows[index];
 3108                    index += 1;
 3109
 3110                    let point = Point::new(row, 0);
 3111                    let boundary = map.next_line_boundary(point).1;
 3112                    let clipped = map.clip_point(boundary, Bias::Left);
 3113
 3114                    (clipped, SelectionGoal::None)
 3115                });
 3116            });
 3117
 3118            let mut indent_edits = Vec::new();
 3119            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3120            for row in rows {
 3121                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3122                for (row, indent) in indents {
 3123                    if indent.len == 0 {
 3124                        continue;
 3125                    }
 3126
 3127                    let text = match indent.kind {
 3128                        IndentKind::Space => " ".repeat(indent.len as usize),
 3129                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3130                    };
 3131                    let point = Point::new(row.0, 0);
 3132                    indent_edits.push((point..point, text));
 3133                }
 3134            }
 3135            editor.edit(indent_edits, cx);
 3136        });
 3137    }
 3138
 3139    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3140        let buffer = self.buffer.read(cx);
 3141        let snapshot = buffer.snapshot(cx);
 3142
 3143        let mut edits = Vec::new();
 3144        let mut rows = Vec::new();
 3145        let mut rows_inserted = 0;
 3146
 3147        for selection in self.selections.all_adjusted(cx) {
 3148            let cursor = selection.head();
 3149            let row = cursor.row;
 3150
 3151            let point = Point::new(row + 1, 0);
 3152            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3153
 3154            let newline = "\n".to_string();
 3155            edits.push((start_of_line..start_of_line, newline));
 3156
 3157            rows_inserted += 1;
 3158            rows.push(row + rows_inserted);
 3159        }
 3160
 3161        self.transact(cx, |editor, cx| {
 3162            editor.edit(edits, cx);
 3163
 3164            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3165                let mut index = 0;
 3166                s.move_cursors_with(|map, _, _| {
 3167                    let row = rows[index];
 3168                    index += 1;
 3169
 3170                    let point = Point::new(row, 0);
 3171                    let boundary = map.next_line_boundary(point).1;
 3172                    let clipped = map.clip_point(boundary, Bias::Left);
 3173
 3174                    (clipped, SelectionGoal::None)
 3175                });
 3176            });
 3177
 3178            let mut indent_edits = Vec::new();
 3179            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3180            for row in rows {
 3181                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3182                for (row, indent) in indents {
 3183                    if indent.len == 0 {
 3184                        continue;
 3185                    }
 3186
 3187                    let text = match indent.kind {
 3188                        IndentKind::Space => " ".repeat(indent.len as usize),
 3189                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3190                    };
 3191                    let point = Point::new(row.0, 0);
 3192                    indent_edits.push((point..point, text));
 3193                }
 3194            }
 3195            editor.edit(indent_edits, cx);
 3196        });
 3197    }
 3198
 3199    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3200        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3201            original_indent_columns: Vec::new(),
 3202        });
 3203        self.insert_with_autoindent_mode(text, autoindent, cx);
 3204    }
 3205
 3206    fn insert_with_autoindent_mode(
 3207        &mut self,
 3208        text: &str,
 3209        autoindent_mode: Option<AutoindentMode>,
 3210        cx: &mut ViewContext<Self>,
 3211    ) {
 3212        if self.read_only(cx) {
 3213            return;
 3214        }
 3215
 3216        let text: Arc<str> = text.into();
 3217        self.transact(cx, |this, cx| {
 3218            let old_selections = this.selections.all_adjusted(cx);
 3219            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3220                let anchors = {
 3221                    let snapshot = buffer.read(cx);
 3222                    old_selections
 3223                        .iter()
 3224                        .map(|s| {
 3225                            let anchor = snapshot.anchor_after(s.head());
 3226                            s.map(|_| anchor)
 3227                        })
 3228                        .collect::<Vec<_>>()
 3229                };
 3230                buffer.edit(
 3231                    old_selections
 3232                        .iter()
 3233                        .map(|s| (s.start..s.end, text.clone())),
 3234                    autoindent_mode,
 3235                    cx,
 3236                );
 3237                anchors
 3238            });
 3239
 3240            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3241                s.select_anchors(selection_anchors);
 3242            })
 3243        });
 3244    }
 3245
 3246    fn trigger_completion_on_input(
 3247        &mut self,
 3248        text: &str,
 3249        trigger_in_words: bool,
 3250        cx: &mut ViewContext<Self>,
 3251    ) {
 3252        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3253            self.show_completions(
 3254                &ShowCompletions {
 3255                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3256                },
 3257                cx,
 3258            );
 3259        } else {
 3260            self.hide_context_menu(cx);
 3261        }
 3262    }
 3263
 3264    fn is_completion_trigger(
 3265        &self,
 3266        text: &str,
 3267        trigger_in_words: bool,
 3268        cx: &mut ViewContext<Self>,
 3269    ) -> bool {
 3270        let position = self.selections.newest_anchor().head();
 3271        let multibuffer = self.buffer.read(cx);
 3272        let Some(buffer) = position
 3273            .buffer_id
 3274            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3275        else {
 3276            return false;
 3277        };
 3278
 3279        if let Some(completion_provider) = &self.completion_provider {
 3280            completion_provider.is_completion_trigger(
 3281                &buffer,
 3282                position.text_anchor,
 3283                text,
 3284                trigger_in_words,
 3285                cx,
 3286            )
 3287        } else {
 3288            false
 3289        }
 3290    }
 3291
 3292    /// If any empty selections is touching the start of its innermost containing autoclose
 3293    /// region, expand it to select the brackets.
 3294    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3295        let selections = self.selections.all::<usize>(cx);
 3296        let buffer = self.buffer.read(cx).read(cx);
 3297        let new_selections = self
 3298            .selections_with_autoclose_regions(selections, &buffer)
 3299            .map(|(mut selection, region)| {
 3300                if !selection.is_empty() {
 3301                    return selection;
 3302                }
 3303
 3304                if let Some(region) = region {
 3305                    let mut range = region.range.to_offset(&buffer);
 3306                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3307                        range.start -= region.pair.start.len();
 3308                        if buffer.contains_str_at(range.start, &region.pair.start)
 3309                            && buffer.contains_str_at(range.end, &region.pair.end)
 3310                        {
 3311                            range.end += region.pair.end.len();
 3312                            selection.start = range.start;
 3313                            selection.end = range.end;
 3314
 3315                            return selection;
 3316                        }
 3317                    }
 3318                }
 3319
 3320                let always_treat_brackets_as_autoclosed = buffer
 3321                    .settings_at(selection.start, cx)
 3322                    .always_treat_brackets_as_autoclosed;
 3323
 3324                if !always_treat_brackets_as_autoclosed {
 3325                    return selection;
 3326                }
 3327
 3328                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3329                    for (pair, enabled) in scope.brackets() {
 3330                        if !enabled || !pair.close {
 3331                            continue;
 3332                        }
 3333
 3334                        if buffer.contains_str_at(selection.start, &pair.end) {
 3335                            let pair_start_len = pair.start.len();
 3336                            if buffer.contains_str_at(
 3337                                selection.start.saturating_sub(pair_start_len),
 3338                                &pair.start,
 3339                            ) {
 3340                                selection.start -= pair_start_len;
 3341                                selection.end += pair.end.len();
 3342
 3343                                return selection;
 3344                            }
 3345                        }
 3346                    }
 3347                }
 3348
 3349                selection
 3350            })
 3351            .collect();
 3352
 3353        drop(buffer);
 3354        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3355    }
 3356
 3357    /// Iterate the given selections, and for each one, find the smallest surrounding
 3358    /// autoclose region. This uses the ordering of the selections and the autoclose
 3359    /// regions to avoid repeated comparisons.
 3360    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3361        &'a self,
 3362        selections: impl IntoIterator<Item = Selection<D>>,
 3363        buffer: &'a MultiBufferSnapshot,
 3364    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3365        let mut i = 0;
 3366        let mut regions = self.autoclose_regions.as_slice();
 3367        selections.into_iter().map(move |selection| {
 3368            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3369
 3370            let mut enclosing = None;
 3371            while let Some(pair_state) = regions.get(i) {
 3372                if pair_state.range.end.to_offset(buffer) < range.start {
 3373                    regions = &regions[i + 1..];
 3374                    i = 0;
 3375                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3376                    break;
 3377                } else {
 3378                    if pair_state.selection_id == selection.id {
 3379                        enclosing = Some(pair_state);
 3380                    }
 3381                    i += 1;
 3382                }
 3383            }
 3384
 3385            (selection, enclosing)
 3386        })
 3387    }
 3388
 3389    /// Remove any autoclose regions that no longer contain their selection.
 3390    fn invalidate_autoclose_regions(
 3391        &mut self,
 3392        mut selections: &[Selection<Anchor>],
 3393        buffer: &MultiBufferSnapshot,
 3394    ) {
 3395        self.autoclose_regions.retain(|state| {
 3396            let mut i = 0;
 3397            while let Some(selection) = selections.get(i) {
 3398                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3399                    selections = &selections[1..];
 3400                    continue;
 3401                }
 3402                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3403                    break;
 3404                }
 3405                if selection.id == state.selection_id {
 3406                    return true;
 3407                } else {
 3408                    i += 1;
 3409                }
 3410            }
 3411            false
 3412        });
 3413    }
 3414
 3415    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3416        let offset = position.to_offset(buffer);
 3417        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3418        if offset > word_range.start && kind == Some(CharKind::Word) {
 3419            Some(
 3420                buffer
 3421                    .text_for_range(word_range.start..offset)
 3422                    .collect::<String>(),
 3423            )
 3424        } else {
 3425            None
 3426        }
 3427    }
 3428
 3429    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3430        self.refresh_inlay_hints(
 3431            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3432            cx,
 3433        );
 3434    }
 3435
 3436    pub fn inlay_hints_enabled(&self) -> bool {
 3437        self.inlay_hint_cache.enabled
 3438    }
 3439
 3440    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3441        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3442            return;
 3443        }
 3444
 3445        let reason_description = reason.description();
 3446        let ignore_debounce = matches!(
 3447            reason,
 3448            InlayHintRefreshReason::SettingsChange(_)
 3449                | InlayHintRefreshReason::Toggle(_)
 3450                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3451        );
 3452        let (invalidate_cache, required_languages) = match reason {
 3453            InlayHintRefreshReason::Toggle(enabled) => {
 3454                self.inlay_hint_cache.enabled = enabled;
 3455                if enabled {
 3456                    (InvalidationStrategy::RefreshRequested, None)
 3457                } else {
 3458                    self.inlay_hint_cache.clear();
 3459                    self.splice_inlays(
 3460                        self.visible_inlay_hints(cx)
 3461                            .iter()
 3462                            .map(|inlay| inlay.id)
 3463                            .collect(),
 3464                        Vec::new(),
 3465                        cx,
 3466                    );
 3467                    return;
 3468                }
 3469            }
 3470            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3471                match self.inlay_hint_cache.update_settings(
 3472                    &self.buffer,
 3473                    new_settings,
 3474                    self.visible_inlay_hints(cx),
 3475                    cx,
 3476                ) {
 3477                    ControlFlow::Break(Some(InlaySplice {
 3478                        to_remove,
 3479                        to_insert,
 3480                    })) => {
 3481                        self.splice_inlays(to_remove, to_insert, cx);
 3482                        return;
 3483                    }
 3484                    ControlFlow::Break(None) => return,
 3485                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3486                }
 3487            }
 3488            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3489                if let Some(InlaySplice {
 3490                    to_remove,
 3491                    to_insert,
 3492                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3493                {
 3494                    self.splice_inlays(to_remove, to_insert, cx);
 3495                }
 3496                return;
 3497            }
 3498            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3499            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3500                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3501            }
 3502            InlayHintRefreshReason::RefreshRequested => {
 3503                (InvalidationStrategy::RefreshRequested, None)
 3504            }
 3505        };
 3506
 3507        if let Some(InlaySplice {
 3508            to_remove,
 3509            to_insert,
 3510        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3511            reason_description,
 3512            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3513            invalidate_cache,
 3514            ignore_debounce,
 3515            cx,
 3516        ) {
 3517            self.splice_inlays(to_remove, to_insert, cx);
 3518        }
 3519    }
 3520
 3521    fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
 3522        self.display_map
 3523            .read(cx)
 3524            .current_inlays()
 3525            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3526            .cloned()
 3527            .collect()
 3528    }
 3529
 3530    pub fn excerpts_for_inlay_hints_query(
 3531        &self,
 3532        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3533        cx: &mut ViewContext<Editor>,
 3534    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3535        let Some(project) = self.project.as_ref() else {
 3536            return HashMap::default();
 3537        };
 3538        let project = project.read(cx);
 3539        let multi_buffer = self.buffer().read(cx);
 3540        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3541        let multi_buffer_visible_start = self
 3542            .scroll_manager
 3543            .anchor()
 3544            .anchor
 3545            .to_point(&multi_buffer_snapshot);
 3546        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3547            multi_buffer_visible_start
 3548                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3549            Bias::Left,
 3550        );
 3551        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3552        multi_buffer
 3553            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3554            .into_iter()
 3555            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3556            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3557                let buffer = buffer_handle.read(cx);
 3558                let buffer_file = project::File::from_dyn(buffer.file())?;
 3559                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3560                let worktree_entry = buffer_worktree
 3561                    .read(cx)
 3562                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3563                if worktree_entry.is_ignored {
 3564                    return None;
 3565                }
 3566
 3567                let language = buffer.language()?;
 3568                if let Some(restrict_to_languages) = restrict_to_languages {
 3569                    if !restrict_to_languages.contains(language) {
 3570                        return None;
 3571                    }
 3572                }
 3573                Some((
 3574                    excerpt_id,
 3575                    (
 3576                        buffer_handle,
 3577                        buffer.version().clone(),
 3578                        excerpt_visible_range,
 3579                    ),
 3580                ))
 3581            })
 3582            .collect()
 3583    }
 3584
 3585    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3586        TextLayoutDetails {
 3587            text_system: cx.text_system().clone(),
 3588            editor_style: self.style.clone().unwrap(),
 3589            rem_size: cx.rem_size(),
 3590            scroll_anchor: self.scroll_manager.anchor(),
 3591            visible_rows: self.visible_line_count(),
 3592            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3593        }
 3594    }
 3595
 3596    fn splice_inlays(
 3597        &self,
 3598        to_remove: Vec<InlayId>,
 3599        to_insert: Vec<Inlay>,
 3600        cx: &mut ViewContext<Self>,
 3601    ) {
 3602        self.display_map.update(cx, |display_map, cx| {
 3603            display_map.splice_inlays(to_remove, to_insert, cx)
 3604        });
 3605        cx.notify();
 3606    }
 3607
 3608    fn trigger_on_type_formatting(
 3609        &self,
 3610        input: String,
 3611        cx: &mut ViewContext<Self>,
 3612    ) -> Option<Task<Result<()>>> {
 3613        if input.len() != 1 {
 3614            return None;
 3615        }
 3616
 3617        let project = self.project.as_ref()?;
 3618        let position = self.selections.newest_anchor().head();
 3619        let (buffer, buffer_position) = self
 3620            .buffer
 3621            .read(cx)
 3622            .text_anchor_for_position(position, cx)?;
 3623
 3624        let settings = language_settings::language_settings(
 3625            buffer
 3626                .read(cx)
 3627                .language_at(buffer_position)
 3628                .map(|l| l.name()),
 3629            buffer.read(cx).file(),
 3630            cx,
 3631        );
 3632        if !settings.use_on_type_format {
 3633            return None;
 3634        }
 3635
 3636        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3637        // hence we do LSP request & edit on host side only — add formats to host's history.
 3638        let push_to_lsp_host_history = true;
 3639        // If this is not the host, append its history with new edits.
 3640        let push_to_client_history = project.read(cx).is_via_collab();
 3641
 3642        let on_type_formatting = project.update(cx, |project, cx| {
 3643            project.on_type_format(
 3644                buffer.clone(),
 3645                buffer_position,
 3646                input,
 3647                push_to_lsp_host_history,
 3648                cx,
 3649            )
 3650        });
 3651        Some(cx.spawn(|editor, mut cx| async move {
 3652            if let Some(transaction) = on_type_formatting.await? {
 3653                if push_to_client_history {
 3654                    buffer
 3655                        .update(&mut cx, |buffer, _| {
 3656                            buffer.push_transaction(transaction, Instant::now());
 3657                        })
 3658                        .ok();
 3659                }
 3660                editor.update(&mut cx, |editor, cx| {
 3661                    editor.refresh_document_highlights(cx);
 3662                })?;
 3663            }
 3664            Ok(())
 3665        }))
 3666    }
 3667
 3668    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3669        if self.pending_rename.is_some() {
 3670            return;
 3671        }
 3672
 3673        let Some(provider) = self.completion_provider.as_ref() else {
 3674            return;
 3675        };
 3676
 3677        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3678            return;
 3679        }
 3680
 3681        let position = self.selections.newest_anchor().head();
 3682        let (buffer, buffer_position) =
 3683            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3684                output
 3685            } else {
 3686                return;
 3687            };
 3688        let show_completion_documentation = buffer
 3689            .read(cx)
 3690            .snapshot()
 3691            .settings_at(buffer_position, cx)
 3692            .show_completion_documentation;
 3693
 3694        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3695
 3696        let trigger_kind = match &options.trigger {
 3697            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3698                CompletionTriggerKind::TRIGGER_CHARACTER
 3699            }
 3700            _ => CompletionTriggerKind::INVOKED,
 3701        };
 3702        let completion_context = CompletionContext {
 3703            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3704                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3705                    Some(String::from(trigger))
 3706                } else {
 3707                    None
 3708                }
 3709            }),
 3710            trigger_kind,
 3711        };
 3712        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3713        let sort_completions = provider.sort_completions();
 3714
 3715        let id = post_inc(&mut self.next_completion_id);
 3716        let task = cx.spawn(|editor, mut cx| {
 3717            async move {
 3718                editor.update(&mut cx, |this, _| {
 3719                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3720                })?;
 3721                let completions = completions.await.log_err();
 3722                let menu = if let Some(completions) = completions {
 3723                    let mut menu = CompletionsMenu::new(
 3724                        id,
 3725                        sort_completions,
 3726                        show_completion_documentation,
 3727                        position,
 3728                        buffer.clone(),
 3729                        completions.into(),
 3730                    );
 3731
 3732                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3733                        .await;
 3734
 3735                    menu.visible().then_some(menu)
 3736                } else {
 3737                    None
 3738                };
 3739
 3740                editor.update(&mut cx, |editor, cx| {
 3741                    match editor.context_menu.borrow().as_ref() {
 3742                        None => {}
 3743                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3744                            if prev_menu.id > id {
 3745                                return;
 3746                            }
 3747                        }
 3748                        _ => return,
 3749                    }
 3750
 3751                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3752                        let mut menu = menu.unwrap();
 3753                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3754
 3755                        if editor.show_inline_completions_in_menu(cx) {
 3756                            if let Some(hint) = editor.inline_completion_menu_hint(cx) {
 3757                                menu.show_inline_completion_hint(hint);
 3758                            }
 3759                        } else {
 3760                            editor.discard_inline_completion(false, cx);
 3761                        }
 3762
 3763                        *editor.context_menu.borrow_mut() =
 3764                            Some(CodeContextMenu::Completions(menu));
 3765
 3766                        cx.notify();
 3767                    } else if editor.completion_tasks.len() <= 1 {
 3768                        // If there are no more completion tasks and the last menu was
 3769                        // empty, we should hide it.
 3770                        let was_hidden = editor.hide_context_menu(cx).is_none();
 3771                        // If it was already hidden and we don't show inline
 3772                        // completions in the menu, we should also show the
 3773                        // inline-completion when available.
 3774                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3775                            editor.update_visible_inline_completion(cx);
 3776                        }
 3777                    }
 3778                })?;
 3779
 3780                Ok::<_, anyhow::Error>(())
 3781            }
 3782            .log_err()
 3783        });
 3784
 3785        self.completion_tasks.push((id, task));
 3786    }
 3787
 3788    pub fn confirm_completion(
 3789        &mut self,
 3790        action: &ConfirmCompletion,
 3791        cx: &mut ViewContext<Self>,
 3792    ) -> Option<Task<Result<()>>> {
 3793        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3794    }
 3795
 3796    pub fn compose_completion(
 3797        &mut self,
 3798        action: &ComposeCompletion,
 3799        cx: &mut ViewContext<Self>,
 3800    ) -> Option<Task<Result<()>>> {
 3801        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3802    }
 3803
 3804    fn do_completion(
 3805        &mut self,
 3806        item_ix: Option<usize>,
 3807        intent: CompletionIntent,
 3808        cx: &mut ViewContext<Editor>,
 3809    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3810        use language::ToOffset as _;
 3811
 3812        let completions_menu =
 3813            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3814                menu
 3815            } else {
 3816                return None;
 3817            };
 3818
 3819        let mat = completions_menu
 3820            .entries
 3821            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3822
 3823        let mat = match mat {
 3824            CompletionEntry::InlineCompletionHint { .. } => {
 3825                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3826                cx.stop_propagation();
 3827                return Some(Task::ready(Ok(())));
 3828            }
 3829            CompletionEntry::Match(mat) => {
 3830                if self.show_inline_completions_in_menu(cx) {
 3831                    self.discard_inline_completion(true, cx);
 3832                }
 3833                mat
 3834            }
 3835        };
 3836
 3837        let buffer_handle = completions_menu.buffer;
 3838        let completion = completions_menu
 3839            .completions
 3840            .borrow()
 3841            .get(mat.candidate_id)?
 3842            .clone();
 3843        cx.stop_propagation();
 3844
 3845        let snippet;
 3846        let text;
 3847
 3848        if completion.is_snippet() {
 3849            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3850            text = snippet.as_ref().unwrap().text.clone();
 3851        } else {
 3852            snippet = None;
 3853            text = completion.new_text.clone();
 3854        };
 3855        let selections = self.selections.all::<usize>(cx);
 3856        let buffer = buffer_handle.read(cx);
 3857        let old_range = completion.old_range.to_offset(buffer);
 3858        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3859
 3860        let newest_selection = self.selections.newest_anchor();
 3861        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3862            return None;
 3863        }
 3864
 3865        let lookbehind = newest_selection
 3866            .start
 3867            .text_anchor
 3868            .to_offset(buffer)
 3869            .saturating_sub(old_range.start);
 3870        let lookahead = old_range
 3871            .end
 3872            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3873        let mut common_prefix_len = old_text
 3874            .bytes()
 3875            .zip(text.bytes())
 3876            .take_while(|(a, b)| a == b)
 3877            .count();
 3878
 3879        let snapshot = self.buffer.read(cx).snapshot(cx);
 3880        let mut range_to_replace: Option<Range<isize>> = None;
 3881        let mut ranges = Vec::new();
 3882        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3883        for selection in &selections {
 3884            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3885                let start = selection.start.saturating_sub(lookbehind);
 3886                let end = selection.end + lookahead;
 3887                if selection.id == newest_selection.id {
 3888                    range_to_replace = Some(
 3889                        ((start + common_prefix_len) as isize - selection.start as isize)
 3890                            ..(end as isize - selection.start as isize),
 3891                    );
 3892                }
 3893                ranges.push(start + common_prefix_len..end);
 3894            } else {
 3895                common_prefix_len = 0;
 3896                ranges.clear();
 3897                ranges.extend(selections.iter().map(|s| {
 3898                    if s.id == newest_selection.id {
 3899                        range_to_replace = Some(
 3900                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3901                                - selection.start as isize
 3902                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3903                                    - selection.start as isize,
 3904                        );
 3905                        old_range.clone()
 3906                    } else {
 3907                        s.start..s.end
 3908                    }
 3909                }));
 3910                break;
 3911            }
 3912            if !self.linked_edit_ranges.is_empty() {
 3913                let start_anchor = snapshot.anchor_before(selection.head());
 3914                let end_anchor = snapshot.anchor_after(selection.tail());
 3915                if let Some(ranges) = self
 3916                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3917                {
 3918                    for (buffer, edits) in ranges {
 3919                        linked_edits.entry(buffer.clone()).or_default().extend(
 3920                            edits
 3921                                .into_iter()
 3922                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3923                        );
 3924                    }
 3925                }
 3926            }
 3927        }
 3928        let text = &text[common_prefix_len..];
 3929
 3930        cx.emit(EditorEvent::InputHandled {
 3931            utf16_range_to_replace: range_to_replace,
 3932            text: text.into(),
 3933        });
 3934
 3935        self.transact(cx, |this, cx| {
 3936            if let Some(mut snippet) = snippet {
 3937                snippet.text = text.to_string();
 3938                for tabstop in snippet
 3939                    .tabstops
 3940                    .iter_mut()
 3941                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3942                {
 3943                    tabstop.start -= common_prefix_len as isize;
 3944                    tabstop.end -= common_prefix_len as isize;
 3945                }
 3946
 3947                this.insert_snippet(&ranges, snippet, cx).log_err();
 3948            } else {
 3949                this.buffer.update(cx, |buffer, cx| {
 3950                    buffer.edit(
 3951                        ranges.iter().map(|range| (range.clone(), text)),
 3952                        this.autoindent_mode.clone(),
 3953                        cx,
 3954                    );
 3955                });
 3956            }
 3957            for (buffer, edits) in linked_edits {
 3958                buffer.update(cx, |buffer, cx| {
 3959                    let snapshot = buffer.snapshot();
 3960                    let edits = edits
 3961                        .into_iter()
 3962                        .map(|(range, text)| {
 3963                            use text::ToPoint as TP;
 3964                            let end_point = TP::to_point(&range.end, &snapshot);
 3965                            let start_point = TP::to_point(&range.start, &snapshot);
 3966                            (start_point..end_point, text)
 3967                        })
 3968                        .sorted_by_key(|(range, _)| range.start)
 3969                        .collect::<Vec<_>>();
 3970                    buffer.edit(edits, None, cx);
 3971                })
 3972            }
 3973
 3974            this.refresh_inline_completion(true, false, cx);
 3975        });
 3976
 3977        let show_new_completions_on_confirm = completion
 3978            .confirm
 3979            .as_ref()
 3980            .map_or(false, |confirm| confirm(intent, cx));
 3981        if show_new_completions_on_confirm {
 3982            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3983        }
 3984
 3985        let provider = self.completion_provider.as_ref()?;
 3986        drop(completion);
 3987        let apply_edits = provider.apply_additional_edits_for_completion(
 3988            buffer_handle,
 3989            completions_menu.completions.clone(),
 3990            mat.candidate_id,
 3991            true,
 3992            cx,
 3993        );
 3994
 3995        let editor_settings = EditorSettings::get_global(cx);
 3996        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 3997            // After the code completion is finished, users often want to know what signatures are needed.
 3998            // so we should automatically call signature_help
 3999            self.show_signature_help(&ShowSignatureHelp, cx);
 4000        }
 4001
 4002        Some(cx.foreground_executor().spawn(async move {
 4003            apply_edits.await?;
 4004            Ok(())
 4005        }))
 4006    }
 4007
 4008    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4009        let mut context_menu = self.context_menu.borrow_mut();
 4010        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4011            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4012                // Toggle if we're selecting the same one
 4013                *context_menu = None;
 4014                cx.notify();
 4015                return;
 4016            } else {
 4017                // Otherwise, clear it and start a new one
 4018                *context_menu = None;
 4019                cx.notify();
 4020            }
 4021        }
 4022        drop(context_menu);
 4023        let snapshot = self.snapshot(cx);
 4024        let deployed_from_indicator = action.deployed_from_indicator;
 4025        let mut task = self.code_actions_task.take();
 4026        let action = action.clone();
 4027        cx.spawn(|editor, mut cx| async move {
 4028            while let Some(prev_task) = task {
 4029                prev_task.await.log_err();
 4030                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4031            }
 4032
 4033            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4034                if editor.focus_handle.is_focused(cx) {
 4035                    let multibuffer_point = action
 4036                        .deployed_from_indicator
 4037                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4038                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4039                    let (buffer, buffer_row) = snapshot
 4040                        .buffer_snapshot
 4041                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4042                        .and_then(|(buffer_snapshot, range)| {
 4043                            editor
 4044                                .buffer
 4045                                .read(cx)
 4046                                .buffer(buffer_snapshot.remote_id())
 4047                                .map(|buffer| (buffer, range.start.row))
 4048                        })?;
 4049                    let (_, code_actions) = editor
 4050                        .available_code_actions
 4051                        .clone()
 4052                        .and_then(|(location, code_actions)| {
 4053                            let snapshot = location.buffer.read(cx).snapshot();
 4054                            let point_range = location.range.to_point(&snapshot);
 4055                            let point_range = point_range.start.row..=point_range.end.row;
 4056                            if point_range.contains(&buffer_row) {
 4057                                Some((location, code_actions))
 4058                            } else {
 4059                                None
 4060                            }
 4061                        })
 4062                        .unzip();
 4063                    let buffer_id = buffer.read(cx).remote_id();
 4064                    let tasks = editor
 4065                        .tasks
 4066                        .get(&(buffer_id, buffer_row))
 4067                        .map(|t| Arc::new(t.to_owned()));
 4068                    if tasks.is_none() && code_actions.is_none() {
 4069                        return None;
 4070                    }
 4071
 4072                    editor.completion_tasks.clear();
 4073                    editor.discard_inline_completion(false, cx);
 4074                    let task_context =
 4075                        tasks
 4076                            .as_ref()
 4077                            .zip(editor.project.clone())
 4078                            .map(|(tasks, project)| {
 4079                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4080                            });
 4081
 4082                    Some(cx.spawn(|editor, mut cx| async move {
 4083                        let task_context = match task_context {
 4084                            Some(task_context) => task_context.await,
 4085                            None => None,
 4086                        };
 4087                        let resolved_tasks =
 4088                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4089                                Rc::new(ResolvedTasks {
 4090                                    templates: tasks.resolve(&task_context).collect(),
 4091                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4092                                        multibuffer_point.row,
 4093                                        tasks.column,
 4094                                    )),
 4095                                })
 4096                            });
 4097                        let spawn_straight_away = resolved_tasks
 4098                            .as_ref()
 4099                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4100                            && code_actions
 4101                                .as_ref()
 4102                                .map_or(true, |actions| actions.is_empty());
 4103                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4104                            *editor.context_menu.borrow_mut() =
 4105                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4106                                    buffer,
 4107                                    actions: CodeActionContents {
 4108                                        tasks: resolved_tasks,
 4109                                        actions: code_actions,
 4110                                    },
 4111                                    selected_item: Default::default(),
 4112                                    scroll_handle: UniformListScrollHandle::default(),
 4113                                    deployed_from_indicator,
 4114                                }));
 4115                            if spawn_straight_away {
 4116                                if let Some(task) = editor.confirm_code_action(
 4117                                    &ConfirmCodeAction { item_ix: Some(0) },
 4118                                    cx,
 4119                                ) {
 4120                                    cx.notify();
 4121                                    return task;
 4122                                }
 4123                            }
 4124                            cx.notify();
 4125                            Task::ready(Ok(()))
 4126                        }) {
 4127                            task.await
 4128                        } else {
 4129                            Ok(())
 4130                        }
 4131                    }))
 4132                } else {
 4133                    Some(Task::ready(Ok(())))
 4134                }
 4135            })?;
 4136            if let Some(task) = spawned_test_task {
 4137                task.await?;
 4138            }
 4139
 4140            Ok::<_, anyhow::Error>(())
 4141        })
 4142        .detach_and_log_err(cx);
 4143    }
 4144
 4145    pub fn confirm_code_action(
 4146        &mut self,
 4147        action: &ConfirmCodeAction,
 4148        cx: &mut ViewContext<Self>,
 4149    ) -> Option<Task<Result<()>>> {
 4150        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4151            menu
 4152        } else {
 4153            return None;
 4154        };
 4155        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4156        let action = actions_menu.actions.get(action_ix)?;
 4157        let title = action.label();
 4158        let buffer = actions_menu.buffer;
 4159        let workspace = self.workspace()?;
 4160
 4161        match action {
 4162            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4163                workspace.update(cx, |workspace, cx| {
 4164                    workspace::tasks::schedule_resolved_task(
 4165                        workspace,
 4166                        task_source_kind,
 4167                        resolved_task,
 4168                        false,
 4169                        cx,
 4170                    );
 4171
 4172                    Some(Task::ready(Ok(())))
 4173                })
 4174            }
 4175            CodeActionsItem::CodeAction {
 4176                excerpt_id,
 4177                action,
 4178                provider,
 4179            } => {
 4180                let apply_code_action =
 4181                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4182                let workspace = workspace.downgrade();
 4183                Some(cx.spawn(|editor, cx| async move {
 4184                    let project_transaction = apply_code_action.await?;
 4185                    Self::open_project_transaction(
 4186                        &editor,
 4187                        workspace,
 4188                        project_transaction,
 4189                        title,
 4190                        cx,
 4191                    )
 4192                    .await
 4193                }))
 4194            }
 4195        }
 4196    }
 4197
 4198    pub async fn open_project_transaction(
 4199        this: &WeakView<Editor>,
 4200        workspace: WeakView<Workspace>,
 4201        transaction: ProjectTransaction,
 4202        title: String,
 4203        mut cx: AsyncWindowContext,
 4204    ) -> Result<()> {
 4205        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4206        cx.update(|cx| {
 4207            entries.sort_unstable_by_key(|(buffer, _)| {
 4208                buffer.read(cx).file().map(|f| f.path().clone())
 4209            });
 4210        })?;
 4211
 4212        // If the project transaction's edits are all contained within this editor, then
 4213        // avoid opening a new editor to display them.
 4214
 4215        if let Some((buffer, transaction)) = entries.first() {
 4216            if entries.len() == 1 {
 4217                let excerpt = this.update(&mut cx, |editor, cx| {
 4218                    editor
 4219                        .buffer()
 4220                        .read(cx)
 4221                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4222                })?;
 4223                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4224                    if excerpted_buffer == *buffer {
 4225                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4226                            let excerpt_range = excerpt_range.to_offset(buffer);
 4227                            buffer
 4228                                .edited_ranges_for_transaction::<usize>(transaction)
 4229                                .all(|range| {
 4230                                    excerpt_range.start <= range.start
 4231                                        && excerpt_range.end >= range.end
 4232                                })
 4233                        })?;
 4234
 4235                        if all_edits_within_excerpt {
 4236                            return Ok(());
 4237                        }
 4238                    }
 4239                }
 4240            }
 4241        } else {
 4242            return Ok(());
 4243        }
 4244
 4245        let mut ranges_to_highlight = Vec::new();
 4246        let excerpt_buffer = cx.new_model(|cx| {
 4247            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4248            for (buffer_handle, transaction) in &entries {
 4249                let buffer = buffer_handle.read(cx);
 4250                ranges_to_highlight.extend(
 4251                    multibuffer.push_excerpts_with_context_lines(
 4252                        buffer_handle.clone(),
 4253                        buffer
 4254                            .edited_ranges_for_transaction::<usize>(transaction)
 4255                            .collect(),
 4256                        DEFAULT_MULTIBUFFER_CONTEXT,
 4257                        cx,
 4258                    ),
 4259                );
 4260            }
 4261            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4262            multibuffer
 4263        })?;
 4264
 4265        workspace.update(&mut cx, |workspace, cx| {
 4266            let project = workspace.project().clone();
 4267            let editor =
 4268                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4269            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4270            editor.update(cx, |editor, cx| {
 4271                editor.highlight_background::<Self>(
 4272                    &ranges_to_highlight,
 4273                    |theme| theme.editor_highlighted_line_background,
 4274                    cx,
 4275                );
 4276            });
 4277        })?;
 4278
 4279        Ok(())
 4280    }
 4281
 4282    pub fn clear_code_action_providers(&mut self) {
 4283        self.code_action_providers.clear();
 4284        self.available_code_actions.take();
 4285    }
 4286
 4287    pub fn push_code_action_provider(
 4288        &mut self,
 4289        provider: Rc<dyn CodeActionProvider>,
 4290        cx: &mut ViewContext<Self>,
 4291    ) {
 4292        self.code_action_providers.push(provider);
 4293        self.refresh_code_actions(cx);
 4294    }
 4295
 4296    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4297        let buffer = self.buffer.read(cx);
 4298        let newest_selection = self.selections.newest_anchor().clone();
 4299        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4300        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4301        if start_buffer != end_buffer {
 4302            return None;
 4303        }
 4304
 4305        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4306            cx.background_executor()
 4307                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4308                .await;
 4309
 4310            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4311                let providers = this.code_action_providers.clone();
 4312                let tasks = this
 4313                    .code_action_providers
 4314                    .iter()
 4315                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4316                    .collect::<Vec<_>>();
 4317                (providers, tasks)
 4318            })?;
 4319
 4320            let mut actions = Vec::new();
 4321            for (provider, provider_actions) in
 4322                providers.into_iter().zip(future::join_all(tasks).await)
 4323            {
 4324                if let Some(provider_actions) = provider_actions.log_err() {
 4325                    actions.extend(provider_actions.into_iter().map(|action| {
 4326                        AvailableCodeAction {
 4327                            excerpt_id: newest_selection.start.excerpt_id,
 4328                            action,
 4329                            provider: provider.clone(),
 4330                        }
 4331                    }));
 4332                }
 4333            }
 4334
 4335            this.update(&mut cx, |this, cx| {
 4336                this.available_code_actions = if actions.is_empty() {
 4337                    None
 4338                } else {
 4339                    Some((
 4340                        Location {
 4341                            buffer: start_buffer,
 4342                            range: start..end,
 4343                        },
 4344                        actions.into(),
 4345                    ))
 4346                };
 4347                cx.notify();
 4348            })
 4349        }));
 4350        None
 4351    }
 4352
 4353    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4354        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4355            self.show_git_blame_inline = false;
 4356
 4357            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4358                cx.background_executor().timer(delay).await;
 4359
 4360                this.update(&mut cx, |this, cx| {
 4361                    this.show_git_blame_inline = true;
 4362                    cx.notify();
 4363                })
 4364                .log_err();
 4365            }));
 4366        }
 4367    }
 4368
 4369    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4370        if self.pending_rename.is_some() {
 4371            return None;
 4372        }
 4373
 4374        let provider = self.semantics_provider.clone()?;
 4375        let buffer = self.buffer.read(cx);
 4376        let newest_selection = self.selections.newest_anchor().clone();
 4377        let cursor_position = newest_selection.head();
 4378        let (cursor_buffer, cursor_buffer_position) =
 4379            buffer.text_anchor_for_position(cursor_position, cx)?;
 4380        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4381        if cursor_buffer != tail_buffer {
 4382            return None;
 4383        }
 4384        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4385        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4386            cx.background_executor()
 4387                .timer(Duration::from_millis(debounce))
 4388                .await;
 4389
 4390            let highlights = if let Some(highlights) = cx
 4391                .update(|cx| {
 4392                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4393                })
 4394                .ok()
 4395                .flatten()
 4396            {
 4397                highlights.await.log_err()
 4398            } else {
 4399                None
 4400            };
 4401
 4402            if let Some(highlights) = highlights {
 4403                this.update(&mut cx, |this, cx| {
 4404                    if this.pending_rename.is_some() {
 4405                        return;
 4406                    }
 4407
 4408                    let buffer_id = cursor_position.buffer_id;
 4409                    let buffer = this.buffer.read(cx);
 4410                    if !buffer
 4411                        .text_anchor_for_position(cursor_position, cx)
 4412                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4413                    {
 4414                        return;
 4415                    }
 4416
 4417                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4418                    let mut write_ranges = Vec::new();
 4419                    let mut read_ranges = Vec::new();
 4420                    for highlight in highlights {
 4421                        for (excerpt_id, excerpt_range) in
 4422                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4423                        {
 4424                            let start = highlight
 4425                                .range
 4426                                .start
 4427                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4428                            let end = highlight
 4429                                .range
 4430                                .end
 4431                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4432                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4433                                continue;
 4434                            }
 4435
 4436                            let range = Anchor {
 4437                                buffer_id,
 4438                                excerpt_id,
 4439                                text_anchor: start,
 4440                            }..Anchor {
 4441                                buffer_id,
 4442                                excerpt_id,
 4443                                text_anchor: end,
 4444                            };
 4445                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4446                                write_ranges.push(range);
 4447                            } else {
 4448                                read_ranges.push(range);
 4449                            }
 4450                        }
 4451                    }
 4452
 4453                    this.highlight_background::<DocumentHighlightRead>(
 4454                        &read_ranges,
 4455                        |theme| theme.editor_document_highlight_read_background,
 4456                        cx,
 4457                    );
 4458                    this.highlight_background::<DocumentHighlightWrite>(
 4459                        &write_ranges,
 4460                        |theme| theme.editor_document_highlight_write_background,
 4461                        cx,
 4462                    );
 4463                    cx.notify();
 4464                })
 4465                .log_err();
 4466            }
 4467        }));
 4468        None
 4469    }
 4470
 4471    pub fn refresh_inline_completion(
 4472        &mut self,
 4473        debounce: bool,
 4474        user_requested: bool,
 4475        cx: &mut ViewContext<Self>,
 4476    ) -> Option<()> {
 4477        let provider = self.inline_completion_provider()?;
 4478        let cursor = self.selections.newest_anchor().head();
 4479        let (buffer, cursor_buffer_position) =
 4480            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4481
 4482        if !user_requested
 4483            && (!self.enable_inline_completions
 4484                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4485                || !self.is_focused(cx))
 4486        {
 4487            self.discard_inline_completion(false, cx);
 4488            return None;
 4489        }
 4490
 4491        self.update_visible_inline_completion(cx);
 4492        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4493        Some(())
 4494    }
 4495
 4496    fn cycle_inline_completion(
 4497        &mut self,
 4498        direction: Direction,
 4499        cx: &mut ViewContext<Self>,
 4500    ) -> Option<()> {
 4501        let provider = self.inline_completion_provider()?;
 4502        let cursor = self.selections.newest_anchor().head();
 4503        let (buffer, cursor_buffer_position) =
 4504            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4505        if !self.enable_inline_completions
 4506            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4507        {
 4508            return None;
 4509        }
 4510
 4511        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4512        self.update_visible_inline_completion(cx);
 4513
 4514        Some(())
 4515    }
 4516
 4517    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4518        if !self.has_active_inline_completion() {
 4519            self.refresh_inline_completion(false, true, cx);
 4520            return;
 4521        }
 4522
 4523        self.update_visible_inline_completion(cx);
 4524    }
 4525
 4526    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4527        self.show_cursor_names(cx);
 4528    }
 4529
 4530    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4531        self.show_cursor_names = true;
 4532        cx.notify();
 4533        cx.spawn(|this, mut cx| async move {
 4534            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4535            this.update(&mut cx, |this, cx| {
 4536                this.show_cursor_names = false;
 4537                cx.notify()
 4538            })
 4539            .ok()
 4540        })
 4541        .detach();
 4542    }
 4543
 4544    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4545        if self.has_active_inline_completion() {
 4546            self.cycle_inline_completion(Direction::Next, cx);
 4547        } else {
 4548            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4549            if is_copilot_disabled {
 4550                cx.propagate();
 4551            }
 4552        }
 4553    }
 4554
 4555    pub fn previous_inline_completion(
 4556        &mut self,
 4557        _: &PreviousInlineCompletion,
 4558        cx: &mut ViewContext<Self>,
 4559    ) {
 4560        if self.has_active_inline_completion() {
 4561            self.cycle_inline_completion(Direction::Prev, cx);
 4562        } else {
 4563            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4564            if is_copilot_disabled {
 4565                cx.propagate();
 4566            }
 4567        }
 4568    }
 4569
 4570    pub fn accept_inline_completion(
 4571        &mut self,
 4572        _: &AcceptInlineCompletion,
 4573        cx: &mut ViewContext<Self>,
 4574    ) {
 4575        if self.show_inline_completions_in_menu(cx) {
 4576            self.hide_context_menu(cx);
 4577        }
 4578
 4579        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4580            return;
 4581        };
 4582
 4583        self.report_inline_completion_event(true, cx);
 4584
 4585        match &active_inline_completion.completion {
 4586            InlineCompletion::Move(position) => {
 4587                let position = *position;
 4588                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4589                    selections.select_anchor_ranges([position..position]);
 4590                });
 4591            }
 4592            InlineCompletion::Edit(edits) => {
 4593                if let Some(provider) = self.inline_completion_provider() {
 4594                    provider.accept(cx);
 4595                }
 4596
 4597                let snapshot = self.buffer.read(cx).snapshot(cx);
 4598                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4599
 4600                self.buffer.update(cx, |buffer, cx| {
 4601                    buffer.edit(edits.iter().cloned(), None, cx)
 4602                });
 4603
 4604                self.change_selections(None, cx, |s| {
 4605                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4606                });
 4607
 4608                self.update_visible_inline_completion(cx);
 4609                if self.active_inline_completion.is_none() {
 4610                    self.refresh_inline_completion(true, true, cx);
 4611                }
 4612
 4613                cx.notify();
 4614            }
 4615        }
 4616    }
 4617
 4618    pub fn accept_partial_inline_completion(
 4619        &mut self,
 4620        _: &AcceptPartialInlineCompletion,
 4621        cx: &mut ViewContext<Self>,
 4622    ) {
 4623        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4624            return;
 4625        };
 4626        if self.selections.count() != 1 {
 4627            return;
 4628        }
 4629
 4630        self.report_inline_completion_event(true, cx);
 4631
 4632        match &active_inline_completion.completion {
 4633            InlineCompletion::Move(position) => {
 4634                let position = *position;
 4635                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4636                    selections.select_anchor_ranges([position..position]);
 4637                });
 4638            }
 4639            InlineCompletion::Edit(edits) => {
 4640                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4641                    let text = edits[0].1.as_str();
 4642                    let mut partial_completion = text
 4643                        .chars()
 4644                        .by_ref()
 4645                        .take_while(|c| c.is_alphabetic())
 4646                        .collect::<String>();
 4647                    if partial_completion.is_empty() {
 4648                        partial_completion = text
 4649                            .chars()
 4650                            .by_ref()
 4651                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4652                            .collect::<String>();
 4653                    }
 4654
 4655                    cx.emit(EditorEvent::InputHandled {
 4656                        utf16_range_to_replace: None,
 4657                        text: partial_completion.clone().into(),
 4658                    });
 4659
 4660                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4661
 4662                    self.refresh_inline_completion(true, true, cx);
 4663                    cx.notify();
 4664                }
 4665            }
 4666        }
 4667    }
 4668
 4669    fn discard_inline_completion(
 4670        &mut self,
 4671        should_report_inline_completion_event: bool,
 4672        cx: &mut ViewContext<Self>,
 4673    ) -> bool {
 4674        if should_report_inline_completion_event {
 4675            self.report_inline_completion_event(false, cx);
 4676        }
 4677
 4678        if let Some(provider) = self.inline_completion_provider() {
 4679            provider.discard(cx);
 4680        }
 4681
 4682        self.take_active_inline_completion(cx).is_some()
 4683    }
 4684
 4685    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4686        let Some(provider) = self.inline_completion_provider() else {
 4687            return;
 4688        };
 4689        let Some(project) = self.project.as_ref() else {
 4690            return;
 4691        };
 4692        let Some((_, buffer, _)) = self
 4693            .buffer
 4694            .read(cx)
 4695            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4696        else {
 4697            return;
 4698        };
 4699
 4700        let project = project.read(cx);
 4701        let extension = buffer
 4702            .read(cx)
 4703            .file()
 4704            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4705        project.client().telemetry().report_inline_completion_event(
 4706            provider.name().into(),
 4707            accepted,
 4708            extension,
 4709        );
 4710    }
 4711
 4712    pub fn has_active_inline_completion(&self) -> bool {
 4713        self.active_inline_completion.is_some()
 4714    }
 4715
 4716    fn take_active_inline_completion(
 4717        &mut self,
 4718        cx: &mut ViewContext<Self>,
 4719    ) -> Option<InlineCompletion> {
 4720        let active_inline_completion = self.active_inline_completion.take()?;
 4721        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4722        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4723        Some(active_inline_completion.completion)
 4724    }
 4725
 4726    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4727        let selection = self.selections.newest_anchor();
 4728        let cursor = selection.head();
 4729        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4730        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4731        let excerpt_id = cursor.excerpt_id;
 4732
 4733        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 4734            && (self.context_menu.borrow().is_some()
 4735                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 4736        if completions_menu_has_precedence
 4737            || !offset_selection.is_empty()
 4738            || self
 4739                .active_inline_completion
 4740                .as_ref()
 4741                .map_or(false, |completion| {
 4742                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4743                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4744                    !invalidation_range.contains(&offset_selection.head())
 4745                })
 4746        {
 4747            self.discard_inline_completion(false, cx);
 4748            return None;
 4749        }
 4750
 4751        self.take_active_inline_completion(cx);
 4752        let provider = self.inline_completion_provider()?;
 4753
 4754        let (buffer, cursor_buffer_position) =
 4755            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4756
 4757        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4758        let edits = completion
 4759            .edits
 4760            .into_iter()
 4761            .flat_map(|(range, new_text)| {
 4762                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4763                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4764                Some((start..end, new_text))
 4765            })
 4766            .collect::<Vec<_>>();
 4767        if edits.is_empty() {
 4768            return None;
 4769        }
 4770
 4771        let first_edit_start = edits.first().unwrap().0.start;
 4772        let edit_start_row = first_edit_start
 4773            .to_point(&multibuffer)
 4774            .row
 4775            .saturating_sub(2);
 4776
 4777        let last_edit_end = edits.last().unwrap().0.end;
 4778        let edit_end_row = cmp::min(
 4779            multibuffer.max_point().row,
 4780            last_edit_end.to_point(&multibuffer).row + 2,
 4781        );
 4782
 4783        let cursor_row = cursor.to_point(&multibuffer).row;
 4784
 4785        let mut inlay_ids = Vec::new();
 4786        let invalidation_row_range;
 4787        let completion;
 4788        if cursor_row < edit_start_row {
 4789            invalidation_row_range = cursor_row..edit_end_row;
 4790            completion = InlineCompletion::Move(first_edit_start);
 4791        } else if cursor_row > edit_end_row {
 4792            invalidation_row_range = edit_start_row..cursor_row;
 4793            completion = InlineCompletion::Move(first_edit_start);
 4794        } else {
 4795            if edits
 4796                .iter()
 4797                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4798            {
 4799                let mut inlays = Vec::new();
 4800                for (range, new_text) in &edits {
 4801                    let inlay = Inlay::inline_completion(
 4802                        post_inc(&mut self.next_inlay_id),
 4803                        range.start,
 4804                        new_text.as_str(),
 4805                    );
 4806                    inlay_ids.push(inlay.id);
 4807                    inlays.push(inlay);
 4808                }
 4809
 4810                self.splice_inlays(vec![], inlays, cx);
 4811            } else {
 4812                let background_color = cx.theme().status().deleted_background;
 4813                self.highlight_text::<InlineCompletionHighlight>(
 4814                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4815                    HighlightStyle {
 4816                        background_color: Some(background_color),
 4817                        ..Default::default()
 4818                    },
 4819                    cx,
 4820                );
 4821            }
 4822
 4823            invalidation_row_range = edit_start_row..edit_end_row;
 4824            completion = InlineCompletion::Edit(edits);
 4825        };
 4826
 4827        let invalidation_range = multibuffer
 4828            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4829            ..multibuffer.anchor_after(Point::new(
 4830                invalidation_row_range.end,
 4831                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4832            ));
 4833
 4834        self.active_inline_completion = Some(InlineCompletionState {
 4835            inlay_ids,
 4836            completion,
 4837            invalidation_range,
 4838        });
 4839
 4840        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 4841            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4842                match self.context_menu.borrow_mut().as_mut() {
 4843                    Some(CodeContextMenu::Completions(menu)) => {
 4844                        menu.show_inline_completion_hint(hint);
 4845                    }
 4846                    _ => {}
 4847                }
 4848            }
 4849        }
 4850
 4851        cx.notify();
 4852
 4853        Some(())
 4854    }
 4855
 4856    fn inline_completion_menu_hint(
 4857        &mut self,
 4858        cx: &mut ViewContext<Self>,
 4859    ) -> Option<InlineCompletionMenuHint> {
 4860        if self.has_active_inline_completion() {
 4861            let provider_name = self.inline_completion_provider()?.display_name();
 4862            let editor_snapshot = self.snapshot(cx);
 4863
 4864            let text = match &self.active_inline_completion.as_ref()?.completion {
 4865                InlineCompletion::Edit(edits) => {
 4866                    inline_completion_edit_text(&editor_snapshot, edits, true, cx)
 4867                }
 4868                InlineCompletion::Move(target) => {
 4869                    let target_point =
 4870                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4871                    let target_line = target_point.row + 1;
 4872                    InlineCompletionText::Move(
 4873                        format!("Jump to edit in line {}", target_line).into(),
 4874                    )
 4875                }
 4876            };
 4877
 4878            Some(InlineCompletionMenuHint {
 4879                provider_name,
 4880                text,
 4881            })
 4882        } else {
 4883            None
 4884        }
 4885    }
 4886
 4887    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4888        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4889    }
 4890
 4891    fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
 4892        EditorSettings::get_global(cx).show_inline_completions_in_menu
 4893            && self
 4894                .inline_completion_provider()
 4895                .map_or(false, |provider| provider.show_completions_in_menu())
 4896    }
 4897
 4898    fn render_code_actions_indicator(
 4899        &self,
 4900        _style: &EditorStyle,
 4901        row: DisplayRow,
 4902        is_active: bool,
 4903        cx: &mut ViewContext<Self>,
 4904    ) -> Option<IconButton> {
 4905        if self.available_code_actions.is_some() {
 4906            Some(
 4907                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4908                    .shape(ui::IconButtonShape::Square)
 4909                    .icon_size(IconSize::XSmall)
 4910                    .icon_color(Color::Muted)
 4911                    .toggle_state(is_active)
 4912                    .tooltip({
 4913                        let focus_handle = self.focus_handle.clone();
 4914                        move |cx| {
 4915                            Tooltip::for_action_in(
 4916                                "Toggle Code Actions",
 4917                                &ToggleCodeActions {
 4918                                    deployed_from_indicator: None,
 4919                                },
 4920                                &focus_handle,
 4921                                cx,
 4922                            )
 4923                        }
 4924                    })
 4925                    .on_click(cx.listener(move |editor, _e, cx| {
 4926                        editor.focus(cx);
 4927                        editor.toggle_code_actions(
 4928                            &ToggleCodeActions {
 4929                                deployed_from_indicator: Some(row),
 4930                            },
 4931                            cx,
 4932                        );
 4933                    })),
 4934            )
 4935        } else {
 4936            None
 4937        }
 4938    }
 4939
 4940    fn clear_tasks(&mut self) {
 4941        self.tasks.clear()
 4942    }
 4943
 4944    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4945        if self.tasks.insert(key, value).is_some() {
 4946            // This case should hopefully be rare, but just in case...
 4947            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4948        }
 4949    }
 4950
 4951    fn build_tasks_context(
 4952        project: &Model<Project>,
 4953        buffer: &Model<Buffer>,
 4954        buffer_row: u32,
 4955        tasks: &Arc<RunnableTasks>,
 4956        cx: &mut ViewContext<Self>,
 4957    ) -> Task<Option<task::TaskContext>> {
 4958        let position = Point::new(buffer_row, tasks.column);
 4959        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4960        let location = Location {
 4961            buffer: buffer.clone(),
 4962            range: range_start..range_start,
 4963        };
 4964        // Fill in the environmental variables from the tree-sitter captures
 4965        let mut captured_task_variables = TaskVariables::default();
 4966        for (capture_name, value) in tasks.extra_variables.clone() {
 4967            captured_task_variables.insert(
 4968                task::VariableName::Custom(capture_name.into()),
 4969                value.clone(),
 4970            );
 4971        }
 4972        project.update(cx, |project, cx| {
 4973            project.task_store().update(cx, |task_store, cx| {
 4974                task_store.task_context_for_location(captured_task_variables, location, cx)
 4975            })
 4976        })
 4977    }
 4978
 4979    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 4980        let Some((workspace, _)) = self.workspace.clone() else {
 4981            return;
 4982        };
 4983        let Some(project) = self.project.clone() else {
 4984            return;
 4985        };
 4986
 4987        // Try to find a closest, enclosing node using tree-sitter that has a
 4988        // task
 4989        let Some((buffer, buffer_row, tasks)) = self
 4990            .find_enclosing_node_task(cx)
 4991            // Or find the task that's closest in row-distance.
 4992            .or_else(|| self.find_closest_task(cx))
 4993        else {
 4994            return;
 4995        };
 4996
 4997        let reveal_strategy = action.reveal;
 4998        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 4999        cx.spawn(|_, mut cx| async move {
 5000            let context = task_context.await?;
 5001            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5002
 5003            let resolved = resolved_task.resolved.as_mut()?;
 5004            resolved.reveal = reveal_strategy;
 5005
 5006            workspace
 5007                .update(&mut cx, |workspace, cx| {
 5008                    workspace::tasks::schedule_resolved_task(
 5009                        workspace,
 5010                        task_source_kind,
 5011                        resolved_task,
 5012                        false,
 5013                        cx,
 5014                    );
 5015                })
 5016                .ok()
 5017        })
 5018        .detach();
 5019    }
 5020
 5021    fn find_closest_task(
 5022        &mut self,
 5023        cx: &mut ViewContext<Self>,
 5024    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5025        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5026
 5027        let ((buffer_id, row), tasks) = self
 5028            .tasks
 5029            .iter()
 5030            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5031
 5032        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5033        let tasks = Arc::new(tasks.to_owned());
 5034        Some((buffer, *row, tasks))
 5035    }
 5036
 5037    fn find_enclosing_node_task(
 5038        &mut self,
 5039        cx: &mut ViewContext<Self>,
 5040    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5041        let snapshot = self.buffer.read(cx).snapshot(cx);
 5042        let offset = self.selections.newest::<usize>(cx).head();
 5043        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5044        let buffer_id = excerpt.buffer().remote_id();
 5045
 5046        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5047        let mut cursor = layer.node().walk();
 5048
 5049        while cursor.goto_first_child_for_byte(offset).is_some() {
 5050            if cursor.node().end_byte() == offset {
 5051                cursor.goto_next_sibling();
 5052            }
 5053        }
 5054
 5055        // Ascend to the smallest ancestor that contains the range and has a task.
 5056        loop {
 5057            let node = cursor.node();
 5058            let node_range = node.byte_range();
 5059            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5060
 5061            // Check if this node contains our offset
 5062            if node_range.start <= offset && node_range.end >= offset {
 5063                // If it contains offset, check for task
 5064                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5065                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5066                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5067                }
 5068            }
 5069
 5070            if !cursor.goto_parent() {
 5071                break;
 5072            }
 5073        }
 5074        None
 5075    }
 5076
 5077    fn render_run_indicator(
 5078        &self,
 5079        _style: &EditorStyle,
 5080        is_active: bool,
 5081        row: DisplayRow,
 5082        cx: &mut ViewContext<Self>,
 5083    ) -> IconButton {
 5084        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5085            .shape(ui::IconButtonShape::Square)
 5086            .icon_size(IconSize::XSmall)
 5087            .icon_color(Color::Muted)
 5088            .toggle_state(is_active)
 5089            .on_click(cx.listener(move |editor, _e, cx| {
 5090                editor.focus(cx);
 5091                editor.toggle_code_actions(
 5092                    &ToggleCodeActions {
 5093                        deployed_from_indicator: Some(row),
 5094                    },
 5095                    cx,
 5096                );
 5097            }))
 5098    }
 5099
 5100    #[cfg(any(feature = "test-support", test))]
 5101    pub fn context_menu_visible(&self) -> bool {
 5102        self.context_menu
 5103            .borrow()
 5104            .as_ref()
 5105            .map_or(false, |menu| menu.visible())
 5106    }
 5107
 5108    #[cfg(feature = "test-support")]
 5109    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5110        self.context_menu
 5111            .borrow()
 5112            .as_ref()
 5113            .map_or(false, |menu| match menu {
 5114                CodeContextMenu::Completions(menu) => menu.entries.first().map_or(false, |entry| {
 5115                    matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5116                }),
 5117                CodeContextMenu::CodeActions(_) => false,
 5118            })
 5119    }
 5120
 5121    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5122        self.context_menu
 5123            .borrow()
 5124            .as_ref()
 5125            .map(|menu| menu.origin(cursor_position))
 5126    }
 5127
 5128    fn render_context_menu(
 5129        &self,
 5130        style: &EditorStyle,
 5131        max_height_in_lines: u32,
 5132        cx: &mut ViewContext<Editor>,
 5133    ) -> Option<AnyElement> {
 5134        self.context_menu.borrow().as_ref().and_then(|menu| {
 5135            if menu.visible() {
 5136                Some(menu.render(style, max_height_in_lines, cx))
 5137            } else {
 5138                None
 5139            }
 5140        })
 5141    }
 5142
 5143    fn render_context_menu_aside(
 5144        &self,
 5145        style: &EditorStyle,
 5146        max_size: Size<Pixels>,
 5147        cx: &mut ViewContext<Editor>,
 5148    ) -> Option<AnyElement> {
 5149        self.context_menu.borrow().as_ref().and_then(|menu| {
 5150            if menu.visible() {
 5151                menu.render_aside(
 5152                    style,
 5153                    max_size,
 5154                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5155                    cx,
 5156                )
 5157            } else {
 5158                None
 5159            }
 5160        })
 5161    }
 5162
 5163    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5164        cx.notify();
 5165        self.completion_tasks.clear();
 5166        let context_menu = self.context_menu.borrow_mut().take();
 5167        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5168            self.update_visible_inline_completion(cx);
 5169        }
 5170        context_menu
 5171    }
 5172
 5173    fn show_snippet_choices(
 5174        &mut self,
 5175        choices: &Vec<String>,
 5176        selection: Range<Anchor>,
 5177        cx: &mut ViewContext<Self>,
 5178    ) {
 5179        if selection.start.buffer_id.is_none() {
 5180            return;
 5181        }
 5182        let buffer_id = selection.start.buffer_id.unwrap();
 5183        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5184        let id = post_inc(&mut self.next_completion_id);
 5185
 5186        if let Some(buffer) = buffer {
 5187            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5188                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5189            ));
 5190        }
 5191    }
 5192
 5193    pub fn insert_snippet(
 5194        &mut self,
 5195        insertion_ranges: &[Range<usize>],
 5196        snippet: Snippet,
 5197        cx: &mut ViewContext<Self>,
 5198    ) -> Result<()> {
 5199        struct Tabstop<T> {
 5200            is_end_tabstop: bool,
 5201            ranges: Vec<Range<T>>,
 5202            choices: Option<Vec<String>>,
 5203        }
 5204
 5205        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5206            let snippet_text: Arc<str> = snippet.text.clone().into();
 5207            buffer.edit(
 5208                insertion_ranges
 5209                    .iter()
 5210                    .cloned()
 5211                    .map(|range| (range, snippet_text.clone())),
 5212                Some(AutoindentMode::EachLine),
 5213                cx,
 5214            );
 5215
 5216            let snapshot = &*buffer.read(cx);
 5217            let snippet = &snippet;
 5218            snippet
 5219                .tabstops
 5220                .iter()
 5221                .map(|tabstop| {
 5222                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5223                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5224                    });
 5225                    let mut tabstop_ranges = tabstop
 5226                        .ranges
 5227                        .iter()
 5228                        .flat_map(|tabstop_range| {
 5229                            let mut delta = 0_isize;
 5230                            insertion_ranges.iter().map(move |insertion_range| {
 5231                                let insertion_start = insertion_range.start as isize + delta;
 5232                                delta +=
 5233                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5234
 5235                                let start = ((insertion_start + tabstop_range.start) as usize)
 5236                                    .min(snapshot.len());
 5237                                let end = ((insertion_start + tabstop_range.end) as usize)
 5238                                    .min(snapshot.len());
 5239                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5240                            })
 5241                        })
 5242                        .collect::<Vec<_>>();
 5243                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5244
 5245                    Tabstop {
 5246                        is_end_tabstop,
 5247                        ranges: tabstop_ranges,
 5248                        choices: tabstop.choices.clone(),
 5249                    }
 5250                })
 5251                .collect::<Vec<_>>()
 5252        });
 5253        if let Some(tabstop) = tabstops.first() {
 5254            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5255                s.select_ranges(tabstop.ranges.iter().cloned());
 5256            });
 5257
 5258            if let Some(choices) = &tabstop.choices {
 5259                if let Some(selection) = tabstop.ranges.first() {
 5260                    self.show_snippet_choices(choices, selection.clone(), cx)
 5261                }
 5262            }
 5263
 5264            // If we're already at the last tabstop and it's at the end of the snippet,
 5265            // we're done, we don't need to keep the state around.
 5266            if !tabstop.is_end_tabstop {
 5267                let choices = tabstops
 5268                    .iter()
 5269                    .map(|tabstop| tabstop.choices.clone())
 5270                    .collect();
 5271
 5272                let ranges = tabstops
 5273                    .into_iter()
 5274                    .map(|tabstop| tabstop.ranges)
 5275                    .collect::<Vec<_>>();
 5276
 5277                self.snippet_stack.push(SnippetState {
 5278                    active_index: 0,
 5279                    ranges,
 5280                    choices,
 5281                });
 5282            }
 5283
 5284            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5285            if self.autoclose_regions.is_empty() {
 5286                let snapshot = self.buffer.read(cx).snapshot(cx);
 5287                for selection in &mut self.selections.all::<Point>(cx) {
 5288                    let selection_head = selection.head();
 5289                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5290                        continue;
 5291                    };
 5292
 5293                    let mut bracket_pair = None;
 5294                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5295                    let prev_chars = snapshot
 5296                        .reversed_chars_at(selection_head)
 5297                        .collect::<String>();
 5298                    for (pair, enabled) in scope.brackets() {
 5299                        if enabled
 5300                            && pair.close
 5301                            && prev_chars.starts_with(pair.start.as_str())
 5302                            && next_chars.starts_with(pair.end.as_str())
 5303                        {
 5304                            bracket_pair = Some(pair.clone());
 5305                            break;
 5306                        }
 5307                    }
 5308                    if let Some(pair) = bracket_pair {
 5309                        let start = snapshot.anchor_after(selection_head);
 5310                        let end = snapshot.anchor_after(selection_head);
 5311                        self.autoclose_regions.push(AutocloseRegion {
 5312                            selection_id: selection.id,
 5313                            range: start..end,
 5314                            pair,
 5315                        });
 5316                    }
 5317                }
 5318            }
 5319        }
 5320        Ok(())
 5321    }
 5322
 5323    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5324        self.move_to_snippet_tabstop(Bias::Right, cx)
 5325    }
 5326
 5327    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5328        self.move_to_snippet_tabstop(Bias::Left, cx)
 5329    }
 5330
 5331    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5332        if let Some(mut snippet) = self.snippet_stack.pop() {
 5333            match bias {
 5334                Bias::Left => {
 5335                    if snippet.active_index > 0 {
 5336                        snippet.active_index -= 1;
 5337                    } else {
 5338                        self.snippet_stack.push(snippet);
 5339                        return false;
 5340                    }
 5341                }
 5342                Bias::Right => {
 5343                    if snippet.active_index + 1 < snippet.ranges.len() {
 5344                        snippet.active_index += 1;
 5345                    } else {
 5346                        self.snippet_stack.push(snippet);
 5347                        return false;
 5348                    }
 5349                }
 5350            }
 5351            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5352                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5353                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5354                });
 5355
 5356                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5357                    if let Some(selection) = current_ranges.first() {
 5358                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5359                    }
 5360                }
 5361
 5362                // If snippet state is not at the last tabstop, push it back on the stack
 5363                if snippet.active_index + 1 < snippet.ranges.len() {
 5364                    self.snippet_stack.push(snippet);
 5365                }
 5366                return true;
 5367            }
 5368        }
 5369
 5370        false
 5371    }
 5372
 5373    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5374        self.transact(cx, |this, cx| {
 5375            this.select_all(&SelectAll, cx);
 5376            this.insert("", cx);
 5377        });
 5378    }
 5379
 5380    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5381        self.transact(cx, |this, cx| {
 5382            this.select_autoclose_pair(cx);
 5383            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5384            if !this.linked_edit_ranges.is_empty() {
 5385                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5386                let snapshot = this.buffer.read(cx).snapshot(cx);
 5387
 5388                for selection in selections.iter() {
 5389                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5390                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5391                    if selection_start.buffer_id != selection_end.buffer_id {
 5392                        continue;
 5393                    }
 5394                    if let Some(ranges) =
 5395                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5396                    {
 5397                        for (buffer, entries) in ranges {
 5398                            linked_ranges.entry(buffer).or_default().extend(entries);
 5399                        }
 5400                    }
 5401                }
 5402            }
 5403
 5404            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5405            if !this.selections.line_mode {
 5406                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5407                for selection in &mut selections {
 5408                    if selection.is_empty() {
 5409                        let old_head = selection.head();
 5410                        let mut new_head =
 5411                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5412                                .to_point(&display_map);
 5413                        if let Some((buffer, line_buffer_range)) = display_map
 5414                            .buffer_snapshot
 5415                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5416                        {
 5417                            let indent_size =
 5418                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5419                            let indent_len = match indent_size.kind {
 5420                                IndentKind::Space => {
 5421                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5422                                }
 5423                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5424                            };
 5425                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5426                                let indent_len = indent_len.get();
 5427                                new_head = cmp::min(
 5428                                    new_head,
 5429                                    MultiBufferPoint::new(
 5430                                        old_head.row,
 5431                                        ((old_head.column - 1) / indent_len) * indent_len,
 5432                                    ),
 5433                                );
 5434                            }
 5435                        }
 5436
 5437                        selection.set_head(new_head, SelectionGoal::None);
 5438                    }
 5439                }
 5440            }
 5441
 5442            this.signature_help_state.set_backspace_pressed(true);
 5443            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5444            this.insert("", cx);
 5445            let empty_str: Arc<str> = Arc::from("");
 5446            for (buffer, edits) in linked_ranges {
 5447                let snapshot = buffer.read(cx).snapshot();
 5448                use text::ToPoint as TP;
 5449
 5450                let edits = edits
 5451                    .into_iter()
 5452                    .map(|range| {
 5453                        let end_point = TP::to_point(&range.end, &snapshot);
 5454                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5455
 5456                        if end_point == start_point {
 5457                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5458                                .saturating_sub(1);
 5459                            start_point =
 5460                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5461                        };
 5462
 5463                        (start_point..end_point, empty_str.clone())
 5464                    })
 5465                    .sorted_by_key(|(range, _)| range.start)
 5466                    .collect::<Vec<_>>();
 5467                buffer.update(cx, |this, cx| {
 5468                    this.edit(edits, None, cx);
 5469                })
 5470            }
 5471            this.refresh_inline_completion(true, false, cx);
 5472            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5473        });
 5474    }
 5475
 5476    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5477        self.transact(cx, |this, cx| {
 5478            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5479                let line_mode = s.line_mode;
 5480                s.move_with(|map, selection| {
 5481                    if selection.is_empty() && !line_mode {
 5482                        let cursor = movement::right(map, selection.head());
 5483                        selection.end = cursor;
 5484                        selection.reversed = true;
 5485                        selection.goal = SelectionGoal::None;
 5486                    }
 5487                })
 5488            });
 5489            this.insert("", cx);
 5490            this.refresh_inline_completion(true, false, cx);
 5491        });
 5492    }
 5493
 5494    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5495        if self.move_to_prev_snippet_tabstop(cx) {
 5496            return;
 5497        }
 5498
 5499        self.outdent(&Outdent, cx);
 5500    }
 5501
 5502    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5503        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5504            return;
 5505        }
 5506
 5507        let mut selections = self.selections.all_adjusted(cx);
 5508        let buffer = self.buffer.read(cx);
 5509        let snapshot = buffer.snapshot(cx);
 5510        let rows_iter = selections.iter().map(|s| s.head().row);
 5511        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5512
 5513        let mut edits = Vec::new();
 5514        let mut prev_edited_row = 0;
 5515        let mut row_delta = 0;
 5516        for selection in &mut selections {
 5517            if selection.start.row != prev_edited_row {
 5518                row_delta = 0;
 5519            }
 5520            prev_edited_row = selection.end.row;
 5521
 5522            // If the selection is non-empty, then increase the indentation of the selected lines.
 5523            if !selection.is_empty() {
 5524                row_delta =
 5525                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5526                continue;
 5527            }
 5528
 5529            // If the selection is empty and the cursor is in the leading whitespace before the
 5530            // suggested indentation, then auto-indent the line.
 5531            let cursor = selection.head();
 5532            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5533            if let Some(suggested_indent) =
 5534                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5535            {
 5536                if cursor.column < suggested_indent.len
 5537                    && cursor.column <= current_indent.len
 5538                    && current_indent.len <= suggested_indent.len
 5539                {
 5540                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5541                    selection.end = selection.start;
 5542                    if row_delta == 0 {
 5543                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5544                            cursor.row,
 5545                            current_indent,
 5546                            suggested_indent,
 5547                        ));
 5548                        row_delta = suggested_indent.len - current_indent.len;
 5549                    }
 5550                    continue;
 5551                }
 5552            }
 5553
 5554            // Otherwise, insert a hard or soft tab.
 5555            let settings = buffer.settings_at(cursor, cx);
 5556            let tab_size = if settings.hard_tabs {
 5557                IndentSize::tab()
 5558            } else {
 5559                let tab_size = settings.tab_size.get();
 5560                let char_column = snapshot
 5561                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5562                    .flat_map(str::chars)
 5563                    .count()
 5564                    + row_delta as usize;
 5565                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5566                IndentSize::spaces(chars_to_next_tab_stop)
 5567            };
 5568            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5569            selection.end = selection.start;
 5570            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5571            row_delta += tab_size.len;
 5572        }
 5573
 5574        self.transact(cx, |this, cx| {
 5575            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5576            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5577            this.refresh_inline_completion(true, false, cx);
 5578        });
 5579    }
 5580
 5581    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5582        if self.read_only(cx) {
 5583            return;
 5584        }
 5585        let mut selections = self.selections.all::<Point>(cx);
 5586        let mut prev_edited_row = 0;
 5587        let mut row_delta = 0;
 5588        let mut edits = Vec::new();
 5589        let buffer = self.buffer.read(cx);
 5590        let snapshot = buffer.snapshot(cx);
 5591        for selection in &mut selections {
 5592            if selection.start.row != prev_edited_row {
 5593                row_delta = 0;
 5594            }
 5595            prev_edited_row = selection.end.row;
 5596
 5597            row_delta =
 5598                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5599        }
 5600
 5601        self.transact(cx, |this, cx| {
 5602            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5603            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5604        });
 5605    }
 5606
 5607    fn indent_selection(
 5608        buffer: &MultiBuffer,
 5609        snapshot: &MultiBufferSnapshot,
 5610        selection: &mut Selection<Point>,
 5611        edits: &mut Vec<(Range<Point>, String)>,
 5612        delta_for_start_row: u32,
 5613        cx: &AppContext,
 5614    ) -> u32 {
 5615        let settings = buffer.settings_at(selection.start, cx);
 5616        let tab_size = settings.tab_size.get();
 5617        let indent_kind = if settings.hard_tabs {
 5618            IndentKind::Tab
 5619        } else {
 5620            IndentKind::Space
 5621        };
 5622        let mut start_row = selection.start.row;
 5623        let mut end_row = selection.end.row + 1;
 5624
 5625        // If a selection ends at the beginning of a line, don't indent
 5626        // that last line.
 5627        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5628            end_row -= 1;
 5629        }
 5630
 5631        // Avoid re-indenting a row that has already been indented by a
 5632        // previous selection, but still update this selection's column
 5633        // to reflect that indentation.
 5634        if delta_for_start_row > 0 {
 5635            start_row += 1;
 5636            selection.start.column += delta_for_start_row;
 5637            if selection.end.row == selection.start.row {
 5638                selection.end.column += delta_for_start_row;
 5639            }
 5640        }
 5641
 5642        let mut delta_for_end_row = 0;
 5643        let has_multiple_rows = start_row + 1 != end_row;
 5644        for row in start_row..end_row {
 5645            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5646            let indent_delta = match (current_indent.kind, indent_kind) {
 5647                (IndentKind::Space, IndentKind::Space) => {
 5648                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5649                    IndentSize::spaces(columns_to_next_tab_stop)
 5650                }
 5651                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5652                (_, IndentKind::Tab) => IndentSize::tab(),
 5653            };
 5654
 5655            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5656                0
 5657            } else {
 5658                selection.start.column
 5659            };
 5660            let row_start = Point::new(row, start);
 5661            edits.push((
 5662                row_start..row_start,
 5663                indent_delta.chars().collect::<String>(),
 5664            ));
 5665
 5666            // Update this selection's endpoints to reflect the indentation.
 5667            if row == selection.start.row {
 5668                selection.start.column += indent_delta.len;
 5669            }
 5670            if row == selection.end.row {
 5671                selection.end.column += indent_delta.len;
 5672                delta_for_end_row = indent_delta.len;
 5673            }
 5674        }
 5675
 5676        if selection.start.row == selection.end.row {
 5677            delta_for_start_row + delta_for_end_row
 5678        } else {
 5679            delta_for_end_row
 5680        }
 5681    }
 5682
 5683    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5684        if self.read_only(cx) {
 5685            return;
 5686        }
 5687        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5688        let selections = self.selections.all::<Point>(cx);
 5689        let mut deletion_ranges = Vec::new();
 5690        let mut last_outdent = None;
 5691        {
 5692            let buffer = self.buffer.read(cx);
 5693            let snapshot = buffer.snapshot(cx);
 5694            for selection in &selections {
 5695                let settings = buffer.settings_at(selection.start, cx);
 5696                let tab_size = settings.tab_size.get();
 5697                let mut rows = selection.spanned_rows(false, &display_map);
 5698
 5699                // Avoid re-outdenting a row that has already been outdented by a
 5700                // previous selection.
 5701                if let Some(last_row) = last_outdent {
 5702                    if last_row == rows.start {
 5703                        rows.start = rows.start.next_row();
 5704                    }
 5705                }
 5706                let has_multiple_rows = rows.len() > 1;
 5707                for row in rows.iter_rows() {
 5708                    let indent_size = snapshot.indent_size_for_line(row);
 5709                    if indent_size.len > 0 {
 5710                        let deletion_len = match indent_size.kind {
 5711                            IndentKind::Space => {
 5712                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5713                                if columns_to_prev_tab_stop == 0 {
 5714                                    tab_size
 5715                                } else {
 5716                                    columns_to_prev_tab_stop
 5717                                }
 5718                            }
 5719                            IndentKind::Tab => 1,
 5720                        };
 5721                        let start = if has_multiple_rows
 5722                            || deletion_len > selection.start.column
 5723                            || indent_size.len < selection.start.column
 5724                        {
 5725                            0
 5726                        } else {
 5727                            selection.start.column - deletion_len
 5728                        };
 5729                        deletion_ranges.push(
 5730                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5731                        );
 5732                        last_outdent = Some(row);
 5733                    }
 5734                }
 5735            }
 5736        }
 5737
 5738        self.transact(cx, |this, cx| {
 5739            this.buffer.update(cx, |buffer, cx| {
 5740                let empty_str: Arc<str> = Arc::default();
 5741                buffer.edit(
 5742                    deletion_ranges
 5743                        .into_iter()
 5744                        .map(|range| (range, empty_str.clone())),
 5745                    None,
 5746                    cx,
 5747                );
 5748            });
 5749            let selections = this.selections.all::<usize>(cx);
 5750            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5751        });
 5752    }
 5753
 5754    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5755        if self.read_only(cx) {
 5756            return;
 5757        }
 5758        let selections = self
 5759            .selections
 5760            .all::<usize>(cx)
 5761            .into_iter()
 5762            .map(|s| s.range());
 5763
 5764        self.transact(cx, |this, cx| {
 5765            this.buffer.update(cx, |buffer, cx| {
 5766                buffer.autoindent_ranges(selections, cx);
 5767            });
 5768            let selections = this.selections.all::<usize>(cx);
 5769            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5770        });
 5771    }
 5772
 5773    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5774        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5775        let selections = self.selections.all::<Point>(cx);
 5776
 5777        let mut new_cursors = Vec::new();
 5778        let mut edit_ranges = Vec::new();
 5779        let mut selections = selections.iter().peekable();
 5780        while let Some(selection) = selections.next() {
 5781            let mut rows = selection.spanned_rows(false, &display_map);
 5782            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5783
 5784            // Accumulate contiguous regions of rows that we want to delete.
 5785            while let Some(next_selection) = selections.peek() {
 5786                let next_rows = next_selection.spanned_rows(false, &display_map);
 5787                if next_rows.start <= rows.end {
 5788                    rows.end = next_rows.end;
 5789                    selections.next().unwrap();
 5790                } else {
 5791                    break;
 5792                }
 5793            }
 5794
 5795            let buffer = &display_map.buffer_snapshot;
 5796            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5797            let edit_end;
 5798            let cursor_buffer_row;
 5799            if buffer.max_point().row >= rows.end.0 {
 5800                // If there's a line after the range, delete the \n from the end of the row range
 5801                // and position the cursor on the next line.
 5802                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5803                cursor_buffer_row = rows.end;
 5804            } else {
 5805                // If there isn't a line after the range, delete the \n from the line before the
 5806                // start of the row range and position the cursor there.
 5807                edit_start = edit_start.saturating_sub(1);
 5808                edit_end = buffer.len();
 5809                cursor_buffer_row = rows.start.previous_row();
 5810            }
 5811
 5812            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5813            *cursor.column_mut() =
 5814                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5815
 5816            new_cursors.push((
 5817                selection.id,
 5818                buffer.anchor_after(cursor.to_point(&display_map)),
 5819            ));
 5820            edit_ranges.push(edit_start..edit_end);
 5821        }
 5822
 5823        self.transact(cx, |this, cx| {
 5824            let buffer = this.buffer.update(cx, |buffer, cx| {
 5825                let empty_str: Arc<str> = Arc::default();
 5826                buffer.edit(
 5827                    edit_ranges
 5828                        .into_iter()
 5829                        .map(|range| (range, empty_str.clone())),
 5830                    None,
 5831                    cx,
 5832                );
 5833                buffer.snapshot(cx)
 5834            });
 5835            let new_selections = new_cursors
 5836                .into_iter()
 5837                .map(|(id, cursor)| {
 5838                    let cursor = cursor.to_point(&buffer);
 5839                    Selection {
 5840                        id,
 5841                        start: cursor,
 5842                        end: cursor,
 5843                        reversed: false,
 5844                        goal: SelectionGoal::None,
 5845                    }
 5846                })
 5847                .collect();
 5848
 5849            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5850                s.select(new_selections);
 5851            });
 5852        });
 5853    }
 5854
 5855    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5856        if self.read_only(cx) {
 5857            return;
 5858        }
 5859        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5860        for selection in self.selections.all::<Point>(cx) {
 5861            let start = MultiBufferRow(selection.start.row);
 5862            // Treat single line selections as if they include the next line. Otherwise this action
 5863            // would do nothing for single line selections individual cursors.
 5864            let end = if selection.start.row == selection.end.row {
 5865                MultiBufferRow(selection.start.row + 1)
 5866            } else {
 5867                MultiBufferRow(selection.end.row)
 5868            };
 5869
 5870            if let Some(last_row_range) = row_ranges.last_mut() {
 5871                if start <= last_row_range.end {
 5872                    last_row_range.end = end;
 5873                    continue;
 5874                }
 5875            }
 5876            row_ranges.push(start..end);
 5877        }
 5878
 5879        let snapshot = self.buffer.read(cx).snapshot(cx);
 5880        let mut cursor_positions = Vec::new();
 5881        for row_range in &row_ranges {
 5882            let anchor = snapshot.anchor_before(Point::new(
 5883                row_range.end.previous_row().0,
 5884                snapshot.line_len(row_range.end.previous_row()),
 5885            ));
 5886            cursor_positions.push(anchor..anchor);
 5887        }
 5888
 5889        self.transact(cx, |this, cx| {
 5890            for row_range in row_ranges.into_iter().rev() {
 5891                for row in row_range.iter_rows().rev() {
 5892                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5893                    let next_line_row = row.next_row();
 5894                    let indent = snapshot.indent_size_for_line(next_line_row);
 5895                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5896
 5897                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5898                        " "
 5899                    } else {
 5900                        ""
 5901                    };
 5902
 5903                    this.buffer.update(cx, |buffer, cx| {
 5904                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5905                    });
 5906                }
 5907            }
 5908
 5909            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5910                s.select_anchor_ranges(cursor_positions)
 5911            });
 5912        });
 5913    }
 5914
 5915    pub fn sort_lines_case_sensitive(
 5916        &mut self,
 5917        _: &SortLinesCaseSensitive,
 5918        cx: &mut ViewContext<Self>,
 5919    ) {
 5920        self.manipulate_lines(cx, |lines| lines.sort())
 5921    }
 5922
 5923    pub fn sort_lines_case_insensitive(
 5924        &mut self,
 5925        _: &SortLinesCaseInsensitive,
 5926        cx: &mut ViewContext<Self>,
 5927    ) {
 5928        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5929    }
 5930
 5931    pub fn unique_lines_case_insensitive(
 5932        &mut self,
 5933        _: &UniqueLinesCaseInsensitive,
 5934        cx: &mut ViewContext<Self>,
 5935    ) {
 5936        self.manipulate_lines(cx, |lines| {
 5937            let mut seen = HashSet::default();
 5938            lines.retain(|line| seen.insert(line.to_lowercase()));
 5939        })
 5940    }
 5941
 5942    pub fn unique_lines_case_sensitive(
 5943        &mut self,
 5944        _: &UniqueLinesCaseSensitive,
 5945        cx: &mut ViewContext<Self>,
 5946    ) {
 5947        self.manipulate_lines(cx, |lines| {
 5948            let mut seen = HashSet::default();
 5949            lines.retain(|line| seen.insert(*line));
 5950        })
 5951    }
 5952
 5953    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 5954        let mut revert_changes = HashMap::default();
 5955        let snapshot = self.snapshot(cx);
 5956        for hunk in hunks_for_ranges(
 5957            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 5958            &snapshot,
 5959        ) {
 5960            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5961        }
 5962        if !revert_changes.is_empty() {
 5963            self.transact(cx, |editor, cx| {
 5964                editor.revert(revert_changes, cx);
 5965            });
 5966        }
 5967    }
 5968
 5969    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 5970        let Some(project) = self.project.clone() else {
 5971            return;
 5972        };
 5973        self.reload(project, cx).detach_and_notify_err(cx);
 5974    }
 5975
 5976    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5977        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 5978        if !revert_changes.is_empty() {
 5979            self.transact(cx, |editor, cx| {
 5980                editor.revert(revert_changes, cx);
 5981            });
 5982        }
 5983    }
 5984
 5985    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 5986        let snapshot = self.buffer.read(cx).read(cx);
 5987        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 5988            drop(snapshot);
 5989            let mut revert_changes = HashMap::default();
 5990            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5991            if !revert_changes.is_empty() {
 5992                self.revert(revert_changes, cx)
 5993            }
 5994        }
 5995    }
 5996
 5997    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5998        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5999            let project_path = buffer.read(cx).project_path(cx)?;
 6000            let project = self.project.as_ref()?.read(cx);
 6001            let entry = project.entry_for_path(&project_path, cx)?;
 6002            let parent = match &entry.canonical_path {
 6003                Some(canonical_path) => canonical_path.to_path_buf(),
 6004                None => project.absolute_path(&project_path, cx)?,
 6005            }
 6006            .parent()?
 6007            .to_path_buf();
 6008            Some(parent)
 6009        }) {
 6010            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6011        }
 6012    }
 6013
 6014    fn gather_revert_changes(
 6015        &mut self,
 6016        selections: &[Selection<Point>],
 6017        cx: &mut ViewContext<Editor>,
 6018    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6019        let mut revert_changes = HashMap::default();
 6020        let snapshot = self.snapshot(cx);
 6021        for hunk in hunks_for_selections(&snapshot, selections) {
 6022            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6023        }
 6024        revert_changes
 6025    }
 6026
 6027    pub fn prepare_revert_change(
 6028        &mut self,
 6029        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6030        hunk: &MultiBufferDiffHunk,
 6031        cx: &AppContext,
 6032    ) -> Option<()> {
 6033        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6034        let buffer = buffer.read(cx);
 6035        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6036        let original_text = change_set
 6037            .read(cx)
 6038            .base_text
 6039            .as_ref()?
 6040            .read(cx)
 6041            .as_rope()
 6042            .slice(hunk.diff_base_byte_range.clone());
 6043        let buffer_snapshot = buffer.snapshot();
 6044        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6045        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6046            probe
 6047                .0
 6048                .start
 6049                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6050                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6051        }) {
 6052            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6053            Some(())
 6054        } else {
 6055            None
 6056        }
 6057    }
 6058
 6059    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6060        self.manipulate_lines(cx, |lines| lines.reverse())
 6061    }
 6062
 6063    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6064        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6065    }
 6066
 6067    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6068    where
 6069        Fn: FnMut(&mut Vec<&str>),
 6070    {
 6071        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6072        let buffer = self.buffer.read(cx).snapshot(cx);
 6073
 6074        let mut edits = Vec::new();
 6075
 6076        let selections = self.selections.all::<Point>(cx);
 6077        let mut selections = selections.iter().peekable();
 6078        let mut contiguous_row_selections = Vec::new();
 6079        let mut new_selections = Vec::new();
 6080        let mut added_lines = 0;
 6081        let mut removed_lines = 0;
 6082
 6083        while let Some(selection) = selections.next() {
 6084            let (start_row, end_row) = consume_contiguous_rows(
 6085                &mut contiguous_row_selections,
 6086                selection,
 6087                &display_map,
 6088                &mut selections,
 6089            );
 6090
 6091            let start_point = Point::new(start_row.0, 0);
 6092            let end_point = Point::new(
 6093                end_row.previous_row().0,
 6094                buffer.line_len(end_row.previous_row()),
 6095            );
 6096            let text = buffer
 6097                .text_for_range(start_point..end_point)
 6098                .collect::<String>();
 6099
 6100            let mut lines = text.split('\n').collect_vec();
 6101
 6102            let lines_before = lines.len();
 6103            callback(&mut lines);
 6104            let lines_after = lines.len();
 6105
 6106            edits.push((start_point..end_point, lines.join("\n")));
 6107
 6108            // Selections must change based on added and removed line count
 6109            let start_row =
 6110                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6111            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6112            new_selections.push(Selection {
 6113                id: selection.id,
 6114                start: start_row,
 6115                end: end_row,
 6116                goal: SelectionGoal::None,
 6117                reversed: selection.reversed,
 6118            });
 6119
 6120            if lines_after > lines_before {
 6121                added_lines += lines_after - lines_before;
 6122            } else if lines_before > lines_after {
 6123                removed_lines += lines_before - lines_after;
 6124            }
 6125        }
 6126
 6127        self.transact(cx, |this, cx| {
 6128            let buffer = this.buffer.update(cx, |buffer, cx| {
 6129                buffer.edit(edits, None, cx);
 6130                buffer.snapshot(cx)
 6131            });
 6132
 6133            // Recalculate offsets on newly edited buffer
 6134            let new_selections = new_selections
 6135                .iter()
 6136                .map(|s| {
 6137                    let start_point = Point::new(s.start.0, 0);
 6138                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6139                    Selection {
 6140                        id: s.id,
 6141                        start: buffer.point_to_offset(start_point),
 6142                        end: buffer.point_to_offset(end_point),
 6143                        goal: s.goal,
 6144                        reversed: s.reversed,
 6145                    }
 6146                })
 6147                .collect();
 6148
 6149            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6150                s.select(new_selections);
 6151            });
 6152
 6153            this.request_autoscroll(Autoscroll::fit(), cx);
 6154        });
 6155    }
 6156
 6157    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6158        self.manipulate_text(cx, |text| text.to_uppercase())
 6159    }
 6160
 6161    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6162        self.manipulate_text(cx, |text| text.to_lowercase())
 6163    }
 6164
 6165    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6166        self.manipulate_text(cx, |text| {
 6167            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6168            // https://github.com/rutrum/convert-case/issues/16
 6169            text.split('\n')
 6170                .map(|line| line.to_case(Case::Title))
 6171                .join("\n")
 6172        })
 6173    }
 6174
 6175    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6176        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6177    }
 6178
 6179    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6180        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6181    }
 6182
 6183    pub fn convert_to_upper_camel_case(
 6184        &mut self,
 6185        _: &ConvertToUpperCamelCase,
 6186        cx: &mut ViewContext<Self>,
 6187    ) {
 6188        self.manipulate_text(cx, |text| {
 6189            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6190            // https://github.com/rutrum/convert-case/issues/16
 6191            text.split('\n')
 6192                .map(|line| line.to_case(Case::UpperCamel))
 6193                .join("\n")
 6194        })
 6195    }
 6196
 6197    pub fn convert_to_lower_camel_case(
 6198        &mut self,
 6199        _: &ConvertToLowerCamelCase,
 6200        cx: &mut ViewContext<Self>,
 6201    ) {
 6202        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6203    }
 6204
 6205    pub fn convert_to_opposite_case(
 6206        &mut self,
 6207        _: &ConvertToOppositeCase,
 6208        cx: &mut ViewContext<Self>,
 6209    ) {
 6210        self.manipulate_text(cx, |text| {
 6211            text.chars()
 6212                .fold(String::with_capacity(text.len()), |mut t, c| {
 6213                    if c.is_uppercase() {
 6214                        t.extend(c.to_lowercase());
 6215                    } else {
 6216                        t.extend(c.to_uppercase());
 6217                    }
 6218                    t
 6219                })
 6220        })
 6221    }
 6222
 6223    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6224    where
 6225        Fn: FnMut(&str) -> String,
 6226    {
 6227        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6228        let buffer = self.buffer.read(cx).snapshot(cx);
 6229
 6230        let mut new_selections = Vec::new();
 6231        let mut edits = Vec::new();
 6232        let mut selection_adjustment = 0i32;
 6233
 6234        for selection in self.selections.all::<usize>(cx) {
 6235            let selection_is_empty = selection.is_empty();
 6236
 6237            let (start, end) = if selection_is_empty {
 6238                let word_range = movement::surrounding_word(
 6239                    &display_map,
 6240                    selection.start.to_display_point(&display_map),
 6241                );
 6242                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6243                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6244                (start, end)
 6245            } else {
 6246                (selection.start, selection.end)
 6247            };
 6248
 6249            let text = buffer.text_for_range(start..end).collect::<String>();
 6250            let old_length = text.len() as i32;
 6251            let text = callback(&text);
 6252
 6253            new_selections.push(Selection {
 6254                start: (start as i32 - selection_adjustment) as usize,
 6255                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6256                goal: SelectionGoal::None,
 6257                ..selection
 6258            });
 6259
 6260            selection_adjustment += old_length - text.len() as i32;
 6261
 6262            edits.push((start..end, text));
 6263        }
 6264
 6265        self.transact(cx, |this, cx| {
 6266            this.buffer.update(cx, |buffer, cx| {
 6267                buffer.edit(edits, None, cx);
 6268            });
 6269
 6270            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6271                s.select(new_selections);
 6272            });
 6273
 6274            this.request_autoscroll(Autoscroll::fit(), cx);
 6275        });
 6276    }
 6277
 6278    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6279        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6280        let buffer = &display_map.buffer_snapshot;
 6281        let selections = self.selections.all::<Point>(cx);
 6282
 6283        let mut edits = Vec::new();
 6284        let mut selections_iter = selections.iter().peekable();
 6285        while let Some(selection) = selections_iter.next() {
 6286            let mut rows = selection.spanned_rows(false, &display_map);
 6287            // duplicate line-wise
 6288            if whole_lines || selection.start == selection.end {
 6289                // Avoid duplicating the same lines twice.
 6290                while let Some(next_selection) = selections_iter.peek() {
 6291                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6292                    if next_rows.start < rows.end {
 6293                        rows.end = next_rows.end;
 6294                        selections_iter.next().unwrap();
 6295                    } else {
 6296                        break;
 6297                    }
 6298                }
 6299
 6300                // Copy the text from the selected row region and splice it either at the start
 6301                // or end of the region.
 6302                let start = Point::new(rows.start.0, 0);
 6303                let end = Point::new(
 6304                    rows.end.previous_row().0,
 6305                    buffer.line_len(rows.end.previous_row()),
 6306                );
 6307                let text = buffer
 6308                    .text_for_range(start..end)
 6309                    .chain(Some("\n"))
 6310                    .collect::<String>();
 6311                let insert_location = if upwards {
 6312                    Point::new(rows.end.0, 0)
 6313                } else {
 6314                    start
 6315                };
 6316                edits.push((insert_location..insert_location, text));
 6317            } else {
 6318                // duplicate character-wise
 6319                let start = selection.start;
 6320                let end = selection.end;
 6321                let text = buffer.text_for_range(start..end).collect::<String>();
 6322                edits.push((selection.end..selection.end, text));
 6323            }
 6324        }
 6325
 6326        self.transact(cx, |this, cx| {
 6327            this.buffer.update(cx, |buffer, cx| {
 6328                buffer.edit(edits, None, cx);
 6329            });
 6330
 6331            this.request_autoscroll(Autoscroll::fit(), cx);
 6332        });
 6333    }
 6334
 6335    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6336        self.duplicate(true, true, cx);
 6337    }
 6338
 6339    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6340        self.duplicate(false, true, cx);
 6341    }
 6342
 6343    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6344        self.duplicate(false, false, cx);
 6345    }
 6346
 6347    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6348        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6349        let buffer = self.buffer.read(cx).snapshot(cx);
 6350
 6351        let mut edits = Vec::new();
 6352        let mut unfold_ranges = Vec::new();
 6353        let mut refold_creases = Vec::new();
 6354
 6355        let selections = self.selections.all::<Point>(cx);
 6356        let mut selections = selections.iter().peekable();
 6357        let mut contiguous_row_selections = Vec::new();
 6358        let mut new_selections = Vec::new();
 6359
 6360        while let Some(selection) = selections.next() {
 6361            // Find all the selections that span a contiguous row range
 6362            let (start_row, end_row) = consume_contiguous_rows(
 6363                &mut contiguous_row_selections,
 6364                selection,
 6365                &display_map,
 6366                &mut selections,
 6367            );
 6368
 6369            // Move the text spanned by the row range to be before the line preceding the row range
 6370            if start_row.0 > 0 {
 6371                let range_to_move = Point::new(
 6372                    start_row.previous_row().0,
 6373                    buffer.line_len(start_row.previous_row()),
 6374                )
 6375                    ..Point::new(
 6376                        end_row.previous_row().0,
 6377                        buffer.line_len(end_row.previous_row()),
 6378                    );
 6379                let insertion_point = display_map
 6380                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6381                    .0;
 6382
 6383                // Don't move lines across excerpts
 6384                if buffer
 6385                    .excerpt_boundaries_in_range((
 6386                        Bound::Excluded(insertion_point),
 6387                        Bound::Included(range_to_move.end),
 6388                    ))
 6389                    .next()
 6390                    .is_none()
 6391                {
 6392                    let text = buffer
 6393                        .text_for_range(range_to_move.clone())
 6394                        .flat_map(|s| s.chars())
 6395                        .skip(1)
 6396                        .chain(['\n'])
 6397                        .collect::<String>();
 6398
 6399                    edits.push((
 6400                        buffer.anchor_after(range_to_move.start)
 6401                            ..buffer.anchor_before(range_to_move.end),
 6402                        String::new(),
 6403                    ));
 6404                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6405                    edits.push((insertion_anchor..insertion_anchor, text));
 6406
 6407                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6408
 6409                    // Move selections up
 6410                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6411                        |mut selection| {
 6412                            selection.start.row -= row_delta;
 6413                            selection.end.row -= row_delta;
 6414                            selection
 6415                        },
 6416                    ));
 6417
 6418                    // Move folds up
 6419                    unfold_ranges.push(range_to_move.clone());
 6420                    for fold in display_map.folds_in_range(
 6421                        buffer.anchor_before(range_to_move.start)
 6422                            ..buffer.anchor_after(range_to_move.end),
 6423                    ) {
 6424                        let mut start = fold.range.start.to_point(&buffer);
 6425                        let mut end = fold.range.end.to_point(&buffer);
 6426                        start.row -= row_delta;
 6427                        end.row -= row_delta;
 6428                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6429                    }
 6430                }
 6431            }
 6432
 6433            // If we didn't move line(s), preserve the existing selections
 6434            new_selections.append(&mut contiguous_row_selections);
 6435        }
 6436
 6437        self.transact(cx, |this, cx| {
 6438            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6439            this.buffer.update(cx, |buffer, cx| {
 6440                for (range, text) in edits {
 6441                    buffer.edit([(range, text)], None, cx);
 6442                }
 6443            });
 6444            this.fold_creases(refold_creases, true, cx);
 6445            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6446                s.select(new_selections);
 6447            })
 6448        });
 6449    }
 6450
 6451    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6452        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6453        let buffer = self.buffer.read(cx).snapshot(cx);
 6454
 6455        let mut edits = Vec::new();
 6456        let mut unfold_ranges = Vec::new();
 6457        let mut refold_creases = Vec::new();
 6458
 6459        let selections = self.selections.all::<Point>(cx);
 6460        let mut selections = selections.iter().peekable();
 6461        let mut contiguous_row_selections = Vec::new();
 6462        let mut new_selections = Vec::new();
 6463
 6464        while let Some(selection) = selections.next() {
 6465            // Find all the selections that span a contiguous row range
 6466            let (start_row, end_row) = consume_contiguous_rows(
 6467                &mut contiguous_row_selections,
 6468                selection,
 6469                &display_map,
 6470                &mut selections,
 6471            );
 6472
 6473            // Move the text spanned by the row range to be after the last line of the row range
 6474            if end_row.0 <= buffer.max_point().row {
 6475                let range_to_move =
 6476                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6477                let insertion_point = display_map
 6478                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6479                    .0;
 6480
 6481                // Don't move lines across excerpt boundaries
 6482                if buffer
 6483                    .excerpt_boundaries_in_range((
 6484                        Bound::Excluded(range_to_move.start),
 6485                        Bound::Included(insertion_point),
 6486                    ))
 6487                    .next()
 6488                    .is_none()
 6489                {
 6490                    let mut text = String::from("\n");
 6491                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6492                    text.pop(); // Drop trailing newline
 6493                    edits.push((
 6494                        buffer.anchor_after(range_to_move.start)
 6495                            ..buffer.anchor_before(range_to_move.end),
 6496                        String::new(),
 6497                    ));
 6498                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6499                    edits.push((insertion_anchor..insertion_anchor, text));
 6500
 6501                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6502
 6503                    // Move selections down
 6504                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6505                        |mut selection| {
 6506                            selection.start.row += row_delta;
 6507                            selection.end.row += row_delta;
 6508                            selection
 6509                        },
 6510                    ));
 6511
 6512                    // Move folds down
 6513                    unfold_ranges.push(range_to_move.clone());
 6514                    for fold in display_map.folds_in_range(
 6515                        buffer.anchor_before(range_to_move.start)
 6516                            ..buffer.anchor_after(range_to_move.end),
 6517                    ) {
 6518                        let mut start = fold.range.start.to_point(&buffer);
 6519                        let mut end = fold.range.end.to_point(&buffer);
 6520                        start.row += row_delta;
 6521                        end.row += row_delta;
 6522                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6523                    }
 6524                }
 6525            }
 6526
 6527            // If we didn't move line(s), preserve the existing selections
 6528            new_selections.append(&mut contiguous_row_selections);
 6529        }
 6530
 6531        self.transact(cx, |this, cx| {
 6532            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6533            this.buffer.update(cx, |buffer, cx| {
 6534                for (range, text) in edits {
 6535                    buffer.edit([(range, text)], None, cx);
 6536                }
 6537            });
 6538            this.fold_creases(refold_creases, true, cx);
 6539            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6540        });
 6541    }
 6542
 6543    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6544        let text_layout_details = &self.text_layout_details(cx);
 6545        self.transact(cx, |this, cx| {
 6546            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6547                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6548                let line_mode = s.line_mode;
 6549                s.move_with(|display_map, selection| {
 6550                    if !selection.is_empty() || line_mode {
 6551                        return;
 6552                    }
 6553
 6554                    let mut head = selection.head();
 6555                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6556                    if head.column() == display_map.line_len(head.row()) {
 6557                        transpose_offset = display_map
 6558                            .buffer_snapshot
 6559                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6560                    }
 6561
 6562                    if transpose_offset == 0 {
 6563                        return;
 6564                    }
 6565
 6566                    *head.column_mut() += 1;
 6567                    head = display_map.clip_point(head, Bias::Right);
 6568                    let goal = SelectionGoal::HorizontalPosition(
 6569                        display_map
 6570                            .x_for_display_point(head, text_layout_details)
 6571                            .into(),
 6572                    );
 6573                    selection.collapse_to(head, goal);
 6574
 6575                    let transpose_start = display_map
 6576                        .buffer_snapshot
 6577                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6578                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6579                        let transpose_end = display_map
 6580                            .buffer_snapshot
 6581                            .clip_offset(transpose_offset + 1, Bias::Right);
 6582                        if let Some(ch) =
 6583                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6584                        {
 6585                            edits.push((transpose_start..transpose_offset, String::new()));
 6586                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6587                        }
 6588                    }
 6589                });
 6590                edits
 6591            });
 6592            this.buffer
 6593                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6594            let selections = this.selections.all::<usize>(cx);
 6595            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6596                s.select(selections);
 6597            });
 6598        });
 6599    }
 6600
 6601    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6602        self.rewrap_impl(IsVimMode::No, cx)
 6603    }
 6604
 6605    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6606        let buffer = self.buffer.read(cx).snapshot(cx);
 6607        let selections = self.selections.all::<Point>(cx);
 6608        let mut selections = selections.iter().peekable();
 6609
 6610        let mut edits = Vec::new();
 6611        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6612
 6613        while let Some(selection) = selections.next() {
 6614            let mut start_row = selection.start.row;
 6615            let mut end_row = selection.end.row;
 6616
 6617            // Skip selections that overlap with a range that has already been rewrapped.
 6618            let selection_range = start_row..end_row;
 6619            if rewrapped_row_ranges
 6620                .iter()
 6621                .any(|range| range.overlaps(&selection_range))
 6622            {
 6623                continue;
 6624            }
 6625
 6626            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6627
 6628            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6629                match language_scope.language_name().0.as_ref() {
 6630                    "Markdown" | "Plain Text" => {
 6631                        should_rewrap = true;
 6632                    }
 6633                    _ => {}
 6634                }
 6635            }
 6636
 6637            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6638
 6639            // Since not all lines in the selection may be at the same indent
 6640            // level, choose the indent size that is the most common between all
 6641            // of the lines.
 6642            //
 6643            // If there is a tie, we use the deepest indent.
 6644            let (indent_size, indent_end) = {
 6645                let mut indent_size_occurrences = HashMap::default();
 6646                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6647
 6648                for row in start_row..=end_row {
 6649                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6650                    rows_by_indent_size.entry(indent).or_default().push(row);
 6651                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6652                }
 6653
 6654                let indent_size = indent_size_occurrences
 6655                    .into_iter()
 6656                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6657                    .map(|(indent, _)| indent)
 6658                    .unwrap_or_default();
 6659                let row = rows_by_indent_size[&indent_size][0];
 6660                let indent_end = Point::new(row, indent_size.len);
 6661
 6662                (indent_size, indent_end)
 6663            };
 6664
 6665            let mut line_prefix = indent_size.chars().collect::<String>();
 6666
 6667            if let Some(comment_prefix) =
 6668                buffer
 6669                    .language_scope_at(selection.head())
 6670                    .and_then(|language| {
 6671                        language
 6672                            .line_comment_prefixes()
 6673                            .iter()
 6674                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6675                            .cloned()
 6676                    })
 6677            {
 6678                line_prefix.push_str(&comment_prefix);
 6679                should_rewrap = true;
 6680            }
 6681
 6682            if !should_rewrap {
 6683                continue;
 6684            }
 6685
 6686            if selection.is_empty() {
 6687                'expand_upwards: while start_row > 0 {
 6688                    let prev_row = start_row - 1;
 6689                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6690                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6691                    {
 6692                        start_row = prev_row;
 6693                    } else {
 6694                        break 'expand_upwards;
 6695                    }
 6696                }
 6697
 6698                'expand_downwards: while end_row < buffer.max_point().row {
 6699                    let next_row = end_row + 1;
 6700                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6701                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6702                    {
 6703                        end_row = next_row;
 6704                    } else {
 6705                        break 'expand_downwards;
 6706                    }
 6707                }
 6708            }
 6709
 6710            let start = Point::new(start_row, 0);
 6711            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6712            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6713            let Some(lines_without_prefixes) = selection_text
 6714                .lines()
 6715                .map(|line| {
 6716                    line.strip_prefix(&line_prefix)
 6717                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6718                        .ok_or_else(|| {
 6719                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6720                        })
 6721                })
 6722                .collect::<Result<Vec<_>, _>>()
 6723                .log_err()
 6724            else {
 6725                continue;
 6726            };
 6727
 6728            let wrap_column = buffer
 6729                .settings_at(Point::new(start_row, 0), cx)
 6730                .preferred_line_length as usize;
 6731            let wrapped_text = wrap_with_prefix(
 6732                line_prefix,
 6733                lines_without_prefixes.join(" "),
 6734                wrap_column,
 6735                tab_size,
 6736            );
 6737
 6738            // TODO: should always use char-based diff while still supporting cursor behavior that
 6739            // matches vim.
 6740            let diff = match is_vim_mode {
 6741                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6742                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6743            };
 6744            let mut offset = start.to_offset(&buffer);
 6745            let mut moved_since_edit = true;
 6746
 6747            for change in diff.iter_all_changes() {
 6748                let value = change.value();
 6749                match change.tag() {
 6750                    ChangeTag::Equal => {
 6751                        offset += value.len();
 6752                        moved_since_edit = true;
 6753                    }
 6754                    ChangeTag::Delete => {
 6755                        let start = buffer.anchor_after(offset);
 6756                        let end = buffer.anchor_before(offset + value.len());
 6757
 6758                        if moved_since_edit {
 6759                            edits.push((start..end, String::new()));
 6760                        } else {
 6761                            edits.last_mut().unwrap().0.end = end;
 6762                        }
 6763
 6764                        offset += value.len();
 6765                        moved_since_edit = false;
 6766                    }
 6767                    ChangeTag::Insert => {
 6768                        if moved_since_edit {
 6769                            let anchor = buffer.anchor_after(offset);
 6770                            edits.push((anchor..anchor, value.to_string()));
 6771                        } else {
 6772                            edits.last_mut().unwrap().1.push_str(value);
 6773                        }
 6774
 6775                        moved_since_edit = false;
 6776                    }
 6777                }
 6778            }
 6779
 6780            rewrapped_row_ranges.push(start_row..=end_row);
 6781        }
 6782
 6783        self.buffer
 6784            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6785    }
 6786
 6787    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6788        let mut text = String::new();
 6789        let buffer = self.buffer.read(cx).snapshot(cx);
 6790        let mut selections = self.selections.all::<Point>(cx);
 6791        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6792        {
 6793            let max_point = buffer.max_point();
 6794            let mut is_first = true;
 6795            for selection in &mut selections {
 6796                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6797                if is_entire_line {
 6798                    selection.start = Point::new(selection.start.row, 0);
 6799                    if !selection.is_empty() && selection.end.column == 0 {
 6800                        selection.end = cmp::min(max_point, selection.end);
 6801                    } else {
 6802                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6803                    }
 6804                    selection.goal = SelectionGoal::None;
 6805                }
 6806                if is_first {
 6807                    is_first = false;
 6808                } else {
 6809                    text += "\n";
 6810                }
 6811                let mut len = 0;
 6812                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6813                    text.push_str(chunk);
 6814                    len += chunk.len();
 6815                }
 6816                clipboard_selections.push(ClipboardSelection {
 6817                    len,
 6818                    is_entire_line,
 6819                    first_line_indent: buffer
 6820                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6821                        .len,
 6822                });
 6823            }
 6824        }
 6825
 6826        self.transact(cx, |this, cx| {
 6827            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6828                s.select(selections);
 6829            });
 6830            this.insert("", cx);
 6831        });
 6832        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6833    }
 6834
 6835    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6836        let item = self.cut_common(cx);
 6837        cx.write_to_clipboard(item);
 6838    }
 6839
 6840    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6841        self.change_selections(None, cx, |s| {
 6842            s.move_with(|snapshot, sel| {
 6843                if sel.is_empty() {
 6844                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6845                }
 6846            });
 6847        });
 6848        let item = self.cut_common(cx);
 6849        cx.set_global(KillRing(item))
 6850    }
 6851
 6852    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6853        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6854            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6855                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6856            } else {
 6857                return;
 6858            }
 6859        } else {
 6860            return;
 6861        };
 6862        self.do_paste(&text, metadata, false, cx);
 6863    }
 6864
 6865    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6866        let selections = self.selections.all::<Point>(cx);
 6867        let buffer = self.buffer.read(cx).read(cx);
 6868        let mut text = String::new();
 6869
 6870        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6871        {
 6872            let max_point = buffer.max_point();
 6873            let mut is_first = true;
 6874            for selection in selections.iter() {
 6875                let mut start = selection.start;
 6876                let mut end = selection.end;
 6877                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6878                if is_entire_line {
 6879                    start = Point::new(start.row, 0);
 6880                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6881                }
 6882                if is_first {
 6883                    is_first = false;
 6884                } else {
 6885                    text += "\n";
 6886                }
 6887                let mut len = 0;
 6888                for chunk in buffer.text_for_range(start..end) {
 6889                    text.push_str(chunk);
 6890                    len += chunk.len();
 6891                }
 6892                clipboard_selections.push(ClipboardSelection {
 6893                    len,
 6894                    is_entire_line,
 6895                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6896                });
 6897            }
 6898        }
 6899
 6900        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6901            text,
 6902            clipboard_selections,
 6903        ));
 6904    }
 6905
 6906    pub fn do_paste(
 6907        &mut self,
 6908        text: &String,
 6909        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6910        handle_entire_lines: bool,
 6911        cx: &mut ViewContext<Self>,
 6912    ) {
 6913        if self.read_only(cx) {
 6914            return;
 6915        }
 6916
 6917        let clipboard_text = Cow::Borrowed(text);
 6918
 6919        self.transact(cx, |this, cx| {
 6920            if let Some(mut clipboard_selections) = clipboard_selections {
 6921                let old_selections = this.selections.all::<usize>(cx);
 6922                let all_selections_were_entire_line =
 6923                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6924                let first_selection_indent_column =
 6925                    clipboard_selections.first().map(|s| s.first_line_indent);
 6926                if clipboard_selections.len() != old_selections.len() {
 6927                    clipboard_selections.drain(..);
 6928                }
 6929                let cursor_offset = this.selections.last::<usize>(cx).head();
 6930                let mut auto_indent_on_paste = true;
 6931
 6932                this.buffer.update(cx, |buffer, cx| {
 6933                    let snapshot = buffer.read(cx);
 6934                    auto_indent_on_paste =
 6935                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6936
 6937                    let mut start_offset = 0;
 6938                    let mut edits = Vec::new();
 6939                    let mut original_indent_columns = Vec::new();
 6940                    for (ix, selection) in old_selections.iter().enumerate() {
 6941                        let to_insert;
 6942                        let entire_line;
 6943                        let original_indent_column;
 6944                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6945                            let end_offset = start_offset + clipboard_selection.len;
 6946                            to_insert = &clipboard_text[start_offset..end_offset];
 6947                            entire_line = clipboard_selection.is_entire_line;
 6948                            start_offset = end_offset + 1;
 6949                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6950                        } else {
 6951                            to_insert = clipboard_text.as_str();
 6952                            entire_line = all_selections_were_entire_line;
 6953                            original_indent_column = first_selection_indent_column
 6954                        }
 6955
 6956                        // If the corresponding selection was empty when this slice of the
 6957                        // clipboard text was written, then the entire line containing the
 6958                        // selection was copied. If this selection is also currently empty,
 6959                        // then paste the line before the current line of the buffer.
 6960                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6961                            let column = selection.start.to_point(&snapshot).column as usize;
 6962                            let line_start = selection.start - column;
 6963                            line_start..line_start
 6964                        } else {
 6965                            selection.range()
 6966                        };
 6967
 6968                        edits.push((range, to_insert));
 6969                        original_indent_columns.extend(original_indent_column);
 6970                    }
 6971                    drop(snapshot);
 6972
 6973                    buffer.edit(
 6974                        edits,
 6975                        if auto_indent_on_paste {
 6976                            Some(AutoindentMode::Block {
 6977                                original_indent_columns,
 6978                            })
 6979                        } else {
 6980                            None
 6981                        },
 6982                        cx,
 6983                    );
 6984                });
 6985
 6986                let selections = this.selections.all::<usize>(cx);
 6987                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6988            } else {
 6989                this.insert(&clipboard_text, cx);
 6990            }
 6991        });
 6992    }
 6993
 6994    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6995        if let Some(item) = cx.read_from_clipboard() {
 6996            let entries = item.entries();
 6997
 6998            match entries.first() {
 6999                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7000                // of all the pasted entries.
 7001                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7002                    .do_paste(
 7003                        clipboard_string.text(),
 7004                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7005                        true,
 7006                        cx,
 7007                    ),
 7008                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7009            }
 7010        }
 7011    }
 7012
 7013    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7014        if self.read_only(cx) {
 7015            return;
 7016        }
 7017
 7018        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7019            if let Some((selections, _)) =
 7020                self.selection_history.transaction(transaction_id).cloned()
 7021            {
 7022                self.change_selections(None, cx, |s| {
 7023                    s.select_anchors(selections.to_vec());
 7024                });
 7025            }
 7026            self.request_autoscroll(Autoscroll::fit(), cx);
 7027            self.unmark_text(cx);
 7028            self.refresh_inline_completion(true, false, cx);
 7029            cx.emit(EditorEvent::Edited { transaction_id });
 7030            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7031        }
 7032    }
 7033
 7034    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7035        if self.read_only(cx) {
 7036            return;
 7037        }
 7038
 7039        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7040            if let Some((_, Some(selections))) =
 7041                self.selection_history.transaction(transaction_id).cloned()
 7042            {
 7043                self.change_selections(None, cx, |s| {
 7044                    s.select_anchors(selections.to_vec());
 7045                });
 7046            }
 7047            self.request_autoscroll(Autoscroll::fit(), cx);
 7048            self.unmark_text(cx);
 7049            self.refresh_inline_completion(true, false, cx);
 7050            cx.emit(EditorEvent::Edited { transaction_id });
 7051        }
 7052    }
 7053
 7054    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7055        self.buffer
 7056            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7057    }
 7058
 7059    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7060        self.buffer
 7061            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7062    }
 7063
 7064    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7065        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7066            let line_mode = s.line_mode;
 7067            s.move_with(|map, selection| {
 7068                let cursor = if selection.is_empty() && !line_mode {
 7069                    movement::left(map, selection.start)
 7070                } else {
 7071                    selection.start
 7072                };
 7073                selection.collapse_to(cursor, SelectionGoal::None);
 7074            });
 7075        })
 7076    }
 7077
 7078    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7079        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7080            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7081        })
 7082    }
 7083
 7084    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7085        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7086            let line_mode = s.line_mode;
 7087            s.move_with(|map, selection| {
 7088                let cursor = if selection.is_empty() && !line_mode {
 7089                    movement::right(map, selection.end)
 7090                } else {
 7091                    selection.end
 7092                };
 7093                selection.collapse_to(cursor, SelectionGoal::None)
 7094            });
 7095        })
 7096    }
 7097
 7098    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7099        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7100            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7101        })
 7102    }
 7103
 7104    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7105        if self.take_rename(true, cx).is_some() {
 7106            return;
 7107        }
 7108
 7109        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7110            cx.propagate();
 7111            return;
 7112        }
 7113
 7114        let text_layout_details = &self.text_layout_details(cx);
 7115        let selection_count = self.selections.count();
 7116        let first_selection = self.selections.first_anchor();
 7117
 7118        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7119            let line_mode = s.line_mode;
 7120            s.move_with(|map, selection| {
 7121                if !selection.is_empty() && !line_mode {
 7122                    selection.goal = SelectionGoal::None;
 7123                }
 7124                let (cursor, goal) = movement::up(
 7125                    map,
 7126                    selection.start,
 7127                    selection.goal,
 7128                    false,
 7129                    text_layout_details,
 7130                );
 7131                selection.collapse_to(cursor, goal);
 7132            });
 7133        });
 7134
 7135        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7136        {
 7137            cx.propagate();
 7138        }
 7139    }
 7140
 7141    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7142        if self.take_rename(true, cx).is_some() {
 7143            return;
 7144        }
 7145
 7146        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7147            cx.propagate();
 7148            return;
 7149        }
 7150
 7151        let text_layout_details = &self.text_layout_details(cx);
 7152
 7153        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7154            let line_mode = s.line_mode;
 7155            s.move_with(|map, selection| {
 7156                if !selection.is_empty() && !line_mode {
 7157                    selection.goal = SelectionGoal::None;
 7158                }
 7159                let (cursor, goal) = movement::up_by_rows(
 7160                    map,
 7161                    selection.start,
 7162                    action.lines,
 7163                    selection.goal,
 7164                    false,
 7165                    text_layout_details,
 7166                );
 7167                selection.collapse_to(cursor, goal);
 7168            });
 7169        })
 7170    }
 7171
 7172    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7173        if self.take_rename(true, cx).is_some() {
 7174            return;
 7175        }
 7176
 7177        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7178            cx.propagate();
 7179            return;
 7180        }
 7181
 7182        let text_layout_details = &self.text_layout_details(cx);
 7183
 7184        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7185            let line_mode = s.line_mode;
 7186            s.move_with(|map, selection| {
 7187                if !selection.is_empty() && !line_mode {
 7188                    selection.goal = SelectionGoal::None;
 7189                }
 7190                let (cursor, goal) = movement::down_by_rows(
 7191                    map,
 7192                    selection.start,
 7193                    action.lines,
 7194                    selection.goal,
 7195                    false,
 7196                    text_layout_details,
 7197                );
 7198                selection.collapse_to(cursor, goal);
 7199            });
 7200        })
 7201    }
 7202
 7203    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7204        let text_layout_details = &self.text_layout_details(cx);
 7205        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7206            s.move_heads_with(|map, head, goal| {
 7207                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7208            })
 7209        })
 7210    }
 7211
 7212    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7213        let text_layout_details = &self.text_layout_details(cx);
 7214        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7215            s.move_heads_with(|map, head, goal| {
 7216                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7217            })
 7218        })
 7219    }
 7220
 7221    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7222        let Some(row_count) = self.visible_row_count() else {
 7223            return;
 7224        };
 7225
 7226        let text_layout_details = &self.text_layout_details(cx);
 7227
 7228        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7229            s.move_heads_with(|map, head, goal| {
 7230                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7231            })
 7232        })
 7233    }
 7234
 7235    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7236        if self.take_rename(true, cx).is_some() {
 7237            return;
 7238        }
 7239
 7240        if self
 7241            .context_menu
 7242            .borrow_mut()
 7243            .as_mut()
 7244            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7245            .unwrap_or(false)
 7246        {
 7247            return;
 7248        }
 7249
 7250        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7251            cx.propagate();
 7252            return;
 7253        }
 7254
 7255        let Some(row_count) = self.visible_row_count() else {
 7256            return;
 7257        };
 7258
 7259        let autoscroll = if action.center_cursor {
 7260            Autoscroll::center()
 7261        } else {
 7262            Autoscroll::fit()
 7263        };
 7264
 7265        let text_layout_details = &self.text_layout_details(cx);
 7266
 7267        self.change_selections(Some(autoscroll), cx, |s| {
 7268            let line_mode = s.line_mode;
 7269            s.move_with(|map, selection| {
 7270                if !selection.is_empty() && !line_mode {
 7271                    selection.goal = SelectionGoal::None;
 7272                }
 7273                let (cursor, goal) = movement::up_by_rows(
 7274                    map,
 7275                    selection.end,
 7276                    row_count,
 7277                    selection.goal,
 7278                    false,
 7279                    text_layout_details,
 7280                );
 7281                selection.collapse_to(cursor, goal);
 7282            });
 7283        });
 7284    }
 7285
 7286    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7287        let text_layout_details = &self.text_layout_details(cx);
 7288        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7289            s.move_heads_with(|map, head, goal| {
 7290                movement::up(map, head, goal, false, text_layout_details)
 7291            })
 7292        })
 7293    }
 7294
 7295    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7296        self.take_rename(true, cx);
 7297
 7298        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7299            cx.propagate();
 7300            return;
 7301        }
 7302
 7303        let text_layout_details = &self.text_layout_details(cx);
 7304        let selection_count = self.selections.count();
 7305        let first_selection = self.selections.first_anchor();
 7306
 7307        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7308            let line_mode = s.line_mode;
 7309            s.move_with(|map, selection| {
 7310                if !selection.is_empty() && !line_mode {
 7311                    selection.goal = SelectionGoal::None;
 7312                }
 7313                let (cursor, goal) = movement::down(
 7314                    map,
 7315                    selection.end,
 7316                    selection.goal,
 7317                    false,
 7318                    text_layout_details,
 7319                );
 7320                selection.collapse_to(cursor, goal);
 7321            });
 7322        });
 7323
 7324        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7325        {
 7326            cx.propagate();
 7327        }
 7328    }
 7329
 7330    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7331        let Some(row_count) = self.visible_row_count() else {
 7332            return;
 7333        };
 7334
 7335        let text_layout_details = &self.text_layout_details(cx);
 7336
 7337        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7338            s.move_heads_with(|map, head, goal| {
 7339                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7340            })
 7341        })
 7342    }
 7343
 7344    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7345        if self.take_rename(true, cx).is_some() {
 7346            return;
 7347        }
 7348
 7349        if self
 7350            .context_menu
 7351            .borrow_mut()
 7352            .as_mut()
 7353            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7354            .unwrap_or(false)
 7355        {
 7356            return;
 7357        }
 7358
 7359        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7360            cx.propagate();
 7361            return;
 7362        }
 7363
 7364        let Some(row_count) = self.visible_row_count() else {
 7365            return;
 7366        };
 7367
 7368        let autoscroll = if action.center_cursor {
 7369            Autoscroll::center()
 7370        } else {
 7371            Autoscroll::fit()
 7372        };
 7373
 7374        let text_layout_details = &self.text_layout_details(cx);
 7375        self.change_selections(Some(autoscroll), cx, |s| {
 7376            let line_mode = s.line_mode;
 7377            s.move_with(|map, selection| {
 7378                if !selection.is_empty() && !line_mode {
 7379                    selection.goal = SelectionGoal::None;
 7380                }
 7381                let (cursor, goal) = movement::down_by_rows(
 7382                    map,
 7383                    selection.end,
 7384                    row_count,
 7385                    selection.goal,
 7386                    false,
 7387                    text_layout_details,
 7388                );
 7389                selection.collapse_to(cursor, goal);
 7390            });
 7391        });
 7392    }
 7393
 7394    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7395        let text_layout_details = &self.text_layout_details(cx);
 7396        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7397            s.move_heads_with(|map, head, goal| {
 7398                movement::down(map, head, goal, false, text_layout_details)
 7399            })
 7400        });
 7401    }
 7402
 7403    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7404        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7405            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7406        }
 7407    }
 7408
 7409    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7410        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7411            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7412        }
 7413    }
 7414
 7415    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7416        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7417            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7418        }
 7419    }
 7420
 7421    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7422        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7423            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7424        }
 7425    }
 7426
 7427    pub fn move_to_previous_word_start(
 7428        &mut self,
 7429        _: &MoveToPreviousWordStart,
 7430        cx: &mut ViewContext<Self>,
 7431    ) {
 7432        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7433            s.move_cursors_with(|map, head, _| {
 7434                (
 7435                    movement::previous_word_start(map, head),
 7436                    SelectionGoal::None,
 7437                )
 7438            });
 7439        })
 7440    }
 7441
 7442    pub fn move_to_previous_subword_start(
 7443        &mut self,
 7444        _: &MoveToPreviousSubwordStart,
 7445        cx: &mut ViewContext<Self>,
 7446    ) {
 7447        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7448            s.move_cursors_with(|map, head, _| {
 7449                (
 7450                    movement::previous_subword_start(map, head),
 7451                    SelectionGoal::None,
 7452                )
 7453            });
 7454        })
 7455    }
 7456
 7457    pub fn select_to_previous_word_start(
 7458        &mut self,
 7459        _: &SelectToPreviousWordStart,
 7460        cx: &mut ViewContext<Self>,
 7461    ) {
 7462        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7463            s.move_heads_with(|map, head, _| {
 7464                (
 7465                    movement::previous_word_start(map, head),
 7466                    SelectionGoal::None,
 7467                )
 7468            });
 7469        })
 7470    }
 7471
 7472    pub fn select_to_previous_subword_start(
 7473        &mut self,
 7474        _: &SelectToPreviousSubwordStart,
 7475        cx: &mut ViewContext<Self>,
 7476    ) {
 7477        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7478            s.move_heads_with(|map, head, _| {
 7479                (
 7480                    movement::previous_subword_start(map, head),
 7481                    SelectionGoal::None,
 7482                )
 7483            });
 7484        })
 7485    }
 7486
 7487    pub fn delete_to_previous_word_start(
 7488        &mut self,
 7489        action: &DeleteToPreviousWordStart,
 7490        cx: &mut ViewContext<Self>,
 7491    ) {
 7492        self.transact(cx, |this, cx| {
 7493            this.select_autoclose_pair(cx);
 7494            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7495                let line_mode = s.line_mode;
 7496                s.move_with(|map, selection| {
 7497                    if selection.is_empty() && !line_mode {
 7498                        let cursor = if action.ignore_newlines {
 7499                            movement::previous_word_start(map, selection.head())
 7500                        } else {
 7501                            movement::previous_word_start_or_newline(map, selection.head())
 7502                        };
 7503                        selection.set_head(cursor, SelectionGoal::None);
 7504                    }
 7505                });
 7506            });
 7507            this.insert("", cx);
 7508        });
 7509    }
 7510
 7511    pub fn delete_to_previous_subword_start(
 7512        &mut self,
 7513        _: &DeleteToPreviousSubwordStart,
 7514        cx: &mut ViewContext<Self>,
 7515    ) {
 7516        self.transact(cx, |this, cx| {
 7517            this.select_autoclose_pair(cx);
 7518            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7519                let line_mode = s.line_mode;
 7520                s.move_with(|map, selection| {
 7521                    if selection.is_empty() && !line_mode {
 7522                        let cursor = movement::previous_subword_start(map, selection.head());
 7523                        selection.set_head(cursor, SelectionGoal::None);
 7524                    }
 7525                });
 7526            });
 7527            this.insert("", cx);
 7528        });
 7529    }
 7530
 7531    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7532        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7533            s.move_cursors_with(|map, head, _| {
 7534                (movement::next_word_end(map, head), SelectionGoal::None)
 7535            });
 7536        })
 7537    }
 7538
 7539    pub fn move_to_next_subword_end(
 7540        &mut self,
 7541        _: &MoveToNextSubwordEnd,
 7542        cx: &mut ViewContext<Self>,
 7543    ) {
 7544        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7545            s.move_cursors_with(|map, head, _| {
 7546                (movement::next_subword_end(map, head), SelectionGoal::None)
 7547            });
 7548        })
 7549    }
 7550
 7551    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7552        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7553            s.move_heads_with(|map, head, _| {
 7554                (movement::next_word_end(map, head), SelectionGoal::None)
 7555            });
 7556        })
 7557    }
 7558
 7559    pub fn select_to_next_subword_end(
 7560        &mut self,
 7561        _: &SelectToNextSubwordEnd,
 7562        cx: &mut ViewContext<Self>,
 7563    ) {
 7564        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7565            s.move_heads_with(|map, head, _| {
 7566                (movement::next_subword_end(map, head), SelectionGoal::None)
 7567            });
 7568        })
 7569    }
 7570
 7571    pub fn delete_to_next_word_end(
 7572        &mut self,
 7573        action: &DeleteToNextWordEnd,
 7574        cx: &mut ViewContext<Self>,
 7575    ) {
 7576        self.transact(cx, |this, cx| {
 7577            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7578                let line_mode = s.line_mode;
 7579                s.move_with(|map, selection| {
 7580                    if selection.is_empty() && !line_mode {
 7581                        let cursor = if action.ignore_newlines {
 7582                            movement::next_word_end(map, selection.head())
 7583                        } else {
 7584                            movement::next_word_end_or_newline(map, selection.head())
 7585                        };
 7586                        selection.set_head(cursor, SelectionGoal::None);
 7587                    }
 7588                });
 7589            });
 7590            this.insert("", cx);
 7591        });
 7592    }
 7593
 7594    pub fn delete_to_next_subword_end(
 7595        &mut self,
 7596        _: &DeleteToNextSubwordEnd,
 7597        cx: &mut ViewContext<Self>,
 7598    ) {
 7599        self.transact(cx, |this, cx| {
 7600            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7601                s.move_with(|map, selection| {
 7602                    if selection.is_empty() {
 7603                        let cursor = movement::next_subword_end(map, selection.head());
 7604                        selection.set_head(cursor, SelectionGoal::None);
 7605                    }
 7606                });
 7607            });
 7608            this.insert("", cx);
 7609        });
 7610    }
 7611
 7612    pub fn move_to_beginning_of_line(
 7613        &mut self,
 7614        action: &MoveToBeginningOfLine,
 7615        cx: &mut ViewContext<Self>,
 7616    ) {
 7617        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7618            s.move_cursors_with(|map, head, _| {
 7619                (
 7620                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7621                    SelectionGoal::None,
 7622                )
 7623            });
 7624        })
 7625    }
 7626
 7627    pub fn select_to_beginning_of_line(
 7628        &mut self,
 7629        action: &SelectToBeginningOfLine,
 7630        cx: &mut ViewContext<Self>,
 7631    ) {
 7632        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7633            s.move_heads_with(|map, head, _| {
 7634                (
 7635                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7636                    SelectionGoal::None,
 7637                )
 7638            });
 7639        });
 7640    }
 7641
 7642    pub fn delete_to_beginning_of_line(
 7643        &mut self,
 7644        _: &DeleteToBeginningOfLine,
 7645        cx: &mut ViewContext<Self>,
 7646    ) {
 7647        self.transact(cx, |this, cx| {
 7648            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7649                s.move_with(|_, selection| {
 7650                    selection.reversed = true;
 7651                });
 7652            });
 7653
 7654            this.select_to_beginning_of_line(
 7655                &SelectToBeginningOfLine {
 7656                    stop_at_soft_wraps: false,
 7657                },
 7658                cx,
 7659            );
 7660            this.backspace(&Backspace, cx);
 7661        });
 7662    }
 7663
 7664    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7665        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7666            s.move_cursors_with(|map, head, _| {
 7667                (
 7668                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7669                    SelectionGoal::None,
 7670                )
 7671            });
 7672        })
 7673    }
 7674
 7675    pub fn select_to_end_of_line(
 7676        &mut self,
 7677        action: &SelectToEndOfLine,
 7678        cx: &mut ViewContext<Self>,
 7679    ) {
 7680        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7681            s.move_heads_with(|map, head, _| {
 7682                (
 7683                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7684                    SelectionGoal::None,
 7685                )
 7686            });
 7687        })
 7688    }
 7689
 7690    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7691        self.transact(cx, |this, cx| {
 7692            this.select_to_end_of_line(
 7693                &SelectToEndOfLine {
 7694                    stop_at_soft_wraps: false,
 7695                },
 7696                cx,
 7697            );
 7698            this.delete(&Delete, cx);
 7699        });
 7700    }
 7701
 7702    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7703        self.transact(cx, |this, cx| {
 7704            this.select_to_end_of_line(
 7705                &SelectToEndOfLine {
 7706                    stop_at_soft_wraps: false,
 7707                },
 7708                cx,
 7709            );
 7710            this.cut(&Cut, cx);
 7711        });
 7712    }
 7713
 7714    pub fn move_to_start_of_paragraph(
 7715        &mut self,
 7716        _: &MoveToStartOfParagraph,
 7717        cx: &mut ViewContext<Self>,
 7718    ) {
 7719        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7720            cx.propagate();
 7721            return;
 7722        }
 7723
 7724        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7725            s.move_with(|map, selection| {
 7726                selection.collapse_to(
 7727                    movement::start_of_paragraph(map, selection.head(), 1),
 7728                    SelectionGoal::None,
 7729                )
 7730            });
 7731        })
 7732    }
 7733
 7734    pub fn move_to_end_of_paragraph(
 7735        &mut self,
 7736        _: &MoveToEndOfParagraph,
 7737        cx: &mut ViewContext<Self>,
 7738    ) {
 7739        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7740            cx.propagate();
 7741            return;
 7742        }
 7743
 7744        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7745            s.move_with(|map, selection| {
 7746                selection.collapse_to(
 7747                    movement::end_of_paragraph(map, selection.head(), 1),
 7748                    SelectionGoal::None,
 7749                )
 7750            });
 7751        })
 7752    }
 7753
 7754    pub fn select_to_start_of_paragraph(
 7755        &mut self,
 7756        _: &SelectToStartOfParagraph,
 7757        cx: &mut ViewContext<Self>,
 7758    ) {
 7759        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7760            cx.propagate();
 7761            return;
 7762        }
 7763
 7764        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7765            s.move_heads_with(|map, head, _| {
 7766                (
 7767                    movement::start_of_paragraph(map, head, 1),
 7768                    SelectionGoal::None,
 7769                )
 7770            });
 7771        })
 7772    }
 7773
 7774    pub fn select_to_end_of_paragraph(
 7775        &mut self,
 7776        _: &SelectToEndOfParagraph,
 7777        cx: &mut ViewContext<Self>,
 7778    ) {
 7779        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7780            cx.propagate();
 7781            return;
 7782        }
 7783
 7784        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7785            s.move_heads_with(|map, head, _| {
 7786                (
 7787                    movement::end_of_paragraph(map, head, 1),
 7788                    SelectionGoal::None,
 7789                )
 7790            });
 7791        })
 7792    }
 7793
 7794    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7795        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7796            cx.propagate();
 7797            return;
 7798        }
 7799
 7800        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7801            s.select_ranges(vec![0..0]);
 7802        });
 7803    }
 7804
 7805    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7806        let mut selection = self.selections.last::<Point>(cx);
 7807        selection.set_head(Point::zero(), SelectionGoal::None);
 7808
 7809        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7810            s.select(vec![selection]);
 7811        });
 7812    }
 7813
 7814    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7815        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7816            cx.propagate();
 7817            return;
 7818        }
 7819
 7820        let cursor = self.buffer.read(cx).read(cx).len();
 7821        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7822            s.select_ranges(vec![cursor..cursor])
 7823        });
 7824    }
 7825
 7826    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7827        self.nav_history = nav_history;
 7828    }
 7829
 7830    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7831        self.nav_history.as_ref()
 7832    }
 7833
 7834    fn push_to_nav_history(
 7835        &mut self,
 7836        cursor_anchor: Anchor,
 7837        new_position: Option<Point>,
 7838        cx: &mut ViewContext<Self>,
 7839    ) {
 7840        if let Some(nav_history) = self.nav_history.as_mut() {
 7841            let buffer = self.buffer.read(cx).read(cx);
 7842            let cursor_position = cursor_anchor.to_point(&buffer);
 7843            let scroll_state = self.scroll_manager.anchor();
 7844            let scroll_top_row = scroll_state.top_row(&buffer);
 7845            drop(buffer);
 7846
 7847            if let Some(new_position) = new_position {
 7848                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7849                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7850                    return;
 7851                }
 7852            }
 7853
 7854            nav_history.push(
 7855                Some(NavigationData {
 7856                    cursor_anchor,
 7857                    cursor_position,
 7858                    scroll_anchor: scroll_state,
 7859                    scroll_top_row,
 7860                }),
 7861                cx,
 7862            );
 7863        }
 7864    }
 7865
 7866    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7867        let buffer = self.buffer.read(cx).snapshot(cx);
 7868        let mut selection = self.selections.first::<usize>(cx);
 7869        selection.set_head(buffer.len(), SelectionGoal::None);
 7870        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7871            s.select(vec![selection]);
 7872        });
 7873    }
 7874
 7875    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7876        let end = self.buffer.read(cx).read(cx).len();
 7877        self.change_selections(None, cx, |s| {
 7878            s.select_ranges(vec![0..end]);
 7879        });
 7880    }
 7881
 7882    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7883        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7884        let mut selections = self.selections.all::<Point>(cx);
 7885        let max_point = display_map.buffer_snapshot.max_point();
 7886        for selection in &mut selections {
 7887            let rows = selection.spanned_rows(true, &display_map);
 7888            selection.start = Point::new(rows.start.0, 0);
 7889            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7890            selection.reversed = false;
 7891        }
 7892        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7893            s.select(selections);
 7894        });
 7895    }
 7896
 7897    pub fn split_selection_into_lines(
 7898        &mut self,
 7899        _: &SplitSelectionIntoLines,
 7900        cx: &mut ViewContext<Self>,
 7901    ) {
 7902        let mut to_unfold = Vec::new();
 7903        let mut new_selection_ranges = Vec::new();
 7904        {
 7905            let selections = self.selections.all::<Point>(cx);
 7906            let buffer = self.buffer.read(cx).read(cx);
 7907            for selection in selections {
 7908                for row in selection.start.row..selection.end.row {
 7909                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7910                    new_selection_ranges.push(cursor..cursor);
 7911                }
 7912                new_selection_ranges.push(selection.end..selection.end);
 7913                to_unfold.push(selection.start..selection.end);
 7914            }
 7915        }
 7916        self.unfold_ranges(&to_unfold, true, true, cx);
 7917        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7918            s.select_ranges(new_selection_ranges);
 7919        });
 7920    }
 7921
 7922    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7923        self.add_selection(true, cx);
 7924    }
 7925
 7926    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7927        self.add_selection(false, cx);
 7928    }
 7929
 7930    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7931        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7932        let mut selections = self.selections.all::<Point>(cx);
 7933        let text_layout_details = self.text_layout_details(cx);
 7934        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7935            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7936            let range = oldest_selection.display_range(&display_map).sorted();
 7937
 7938            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7939            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7940            let positions = start_x.min(end_x)..start_x.max(end_x);
 7941
 7942            selections.clear();
 7943            let mut stack = Vec::new();
 7944            for row in range.start.row().0..=range.end.row().0 {
 7945                if let Some(selection) = self.selections.build_columnar_selection(
 7946                    &display_map,
 7947                    DisplayRow(row),
 7948                    &positions,
 7949                    oldest_selection.reversed,
 7950                    &text_layout_details,
 7951                ) {
 7952                    stack.push(selection.id);
 7953                    selections.push(selection);
 7954                }
 7955            }
 7956
 7957            if above {
 7958                stack.reverse();
 7959            }
 7960
 7961            AddSelectionsState { above, stack }
 7962        });
 7963
 7964        let last_added_selection = *state.stack.last().unwrap();
 7965        let mut new_selections = Vec::new();
 7966        if above == state.above {
 7967            let end_row = if above {
 7968                DisplayRow(0)
 7969            } else {
 7970                display_map.max_point().row()
 7971            };
 7972
 7973            'outer: for selection in selections {
 7974                if selection.id == last_added_selection {
 7975                    let range = selection.display_range(&display_map).sorted();
 7976                    debug_assert_eq!(range.start.row(), range.end.row());
 7977                    let mut row = range.start.row();
 7978                    let positions =
 7979                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7980                            px(start)..px(end)
 7981                        } else {
 7982                            let start_x =
 7983                                display_map.x_for_display_point(range.start, &text_layout_details);
 7984                            let end_x =
 7985                                display_map.x_for_display_point(range.end, &text_layout_details);
 7986                            start_x.min(end_x)..start_x.max(end_x)
 7987                        };
 7988
 7989                    while row != end_row {
 7990                        if above {
 7991                            row.0 -= 1;
 7992                        } else {
 7993                            row.0 += 1;
 7994                        }
 7995
 7996                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7997                            &display_map,
 7998                            row,
 7999                            &positions,
 8000                            selection.reversed,
 8001                            &text_layout_details,
 8002                        ) {
 8003                            state.stack.push(new_selection.id);
 8004                            if above {
 8005                                new_selections.push(new_selection);
 8006                                new_selections.push(selection);
 8007                            } else {
 8008                                new_selections.push(selection);
 8009                                new_selections.push(new_selection);
 8010                            }
 8011
 8012                            continue 'outer;
 8013                        }
 8014                    }
 8015                }
 8016
 8017                new_selections.push(selection);
 8018            }
 8019        } else {
 8020            new_selections = selections;
 8021            new_selections.retain(|s| s.id != last_added_selection);
 8022            state.stack.pop();
 8023        }
 8024
 8025        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8026            s.select(new_selections);
 8027        });
 8028        if state.stack.len() > 1 {
 8029            self.add_selections_state = Some(state);
 8030        }
 8031    }
 8032
 8033    pub fn select_next_match_internal(
 8034        &mut self,
 8035        display_map: &DisplaySnapshot,
 8036        replace_newest: bool,
 8037        autoscroll: Option<Autoscroll>,
 8038        cx: &mut ViewContext<Self>,
 8039    ) -> Result<()> {
 8040        fn select_next_match_ranges(
 8041            this: &mut Editor,
 8042            range: Range<usize>,
 8043            replace_newest: bool,
 8044            auto_scroll: Option<Autoscroll>,
 8045            cx: &mut ViewContext<Editor>,
 8046        ) {
 8047            this.unfold_ranges(&[range.clone()], false, true, cx);
 8048            this.change_selections(auto_scroll, cx, |s| {
 8049                if replace_newest {
 8050                    s.delete(s.newest_anchor().id);
 8051                }
 8052                s.insert_range(range.clone());
 8053            });
 8054        }
 8055
 8056        let buffer = &display_map.buffer_snapshot;
 8057        let mut selections = self.selections.all::<usize>(cx);
 8058        if let Some(mut select_next_state) = self.select_next_state.take() {
 8059            let query = &select_next_state.query;
 8060            if !select_next_state.done {
 8061                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8062                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8063                let mut next_selected_range = None;
 8064
 8065                let bytes_after_last_selection =
 8066                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8067                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8068                let query_matches = query
 8069                    .stream_find_iter(bytes_after_last_selection)
 8070                    .map(|result| (last_selection.end, result))
 8071                    .chain(
 8072                        query
 8073                            .stream_find_iter(bytes_before_first_selection)
 8074                            .map(|result| (0, result)),
 8075                    );
 8076
 8077                for (start_offset, query_match) in query_matches {
 8078                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8079                    let offset_range =
 8080                        start_offset + query_match.start()..start_offset + query_match.end();
 8081                    let display_range = offset_range.start.to_display_point(display_map)
 8082                        ..offset_range.end.to_display_point(display_map);
 8083
 8084                    if !select_next_state.wordwise
 8085                        || (!movement::is_inside_word(display_map, display_range.start)
 8086                            && !movement::is_inside_word(display_map, display_range.end))
 8087                    {
 8088                        // TODO: This is n^2, because we might check all the selections
 8089                        if !selections
 8090                            .iter()
 8091                            .any(|selection| selection.range().overlaps(&offset_range))
 8092                        {
 8093                            next_selected_range = Some(offset_range);
 8094                            break;
 8095                        }
 8096                    }
 8097                }
 8098
 8099                if let Some(next_selected_range) = next_selected_range {
 8100                    select_next_match_ranges(
 8101                        self,
 8102                        next_selected_range,
 8103                        replace_newest,
 8104                        autoscroll,
 8105                        cx,
 8106                    );
 8107                } else {
 8108                    select_next_state.done = true;
 8109                }
 8110            }
 8111
 8112            self.select_next_state = Some(select_next_state);
 8113        } else {
 8114            let mut only_carets = true;
 8115            let mut same_text_selected = true;
 8116            let mut selected_text = None;
 8117
 8118            let mut selections_iter = selections.iter().peekable();
 8119            while let Some(selection) = selections_iter.next() {
 8120                if selection.start != selection.end {
 8121                    only_carets = false;
 8122                }
 8123
 8124                if same_text_selected {
 8125                    if selected_text.is_none() {
 8126                        selected_text =
 8127                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8128                    }
 8129
 8130                    if let Some(next_selection) = selections_iter.peek() {
 8131                        if next_selection.range().len() == selection.range().len() {
 8132                            let next_selected_text = buffer
 8133                                .text_for_range(next_selection.range())
 8134                                .collect::<String>();
 8135                            if Some(next_selected_text) != selected_text {
 8136                                same_text_selected = false;
 8137                                selected_text = None;
 8138                            }
 8139                        } else {
 8140                            same_text_selected = false;
 8141                            selected_text = None;
 8142                        }
 8143                    }
 8144                }
 8145            }
 8146
 8147            if only_carets {
 8148                for selection in &mut selections {
 8149                    let word_range = movement::surrounding_word(
 8150                        display_map,
 8151                        selection.start.to_display_point(display_map),
 8152                    );
 8153                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8154                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8155                    selection.goal = SelectionGoal::None;
 8156                    selection.reversed = false;
 8157                    select_next_match_ranges(
 8158                        self,
 8159                        selection.start..selection.end,
 8160                        replace_newest,
 8161                        autoscroll,
 8162                        cx,
 8163                    );
 8164                }
 8165
 8166                if selections.len() == 1 {
 8167                    let selection = selections
 8168                        .last()
 8169                        .expect("ensured that there's only one selection");
 8170                    let query = buffer
 8171                        .text_for_range(selection.start..selection.end)
 8172                        .collect::<String>();
 8173                    let is_empty = query.is_empty();
 8174                    let select_state = SelectNextState {
 8175                        query: AhoCorasick::new(&[query])?,
 8176                        wordwise: true,
 8177                        done: is_empty,
 8178                    };
 8179                    self.select_next_state = Some(select_state);
 8180                } else {
 8181                    self.select_next_state = None;
 8182                }
 8183            } else if let Some(selected_text) = selected_text {
 8184                self.select_next_state = Some(SelectNextState {
 8185                    query: AhoCorasick::new(&[selected_text])?,
 8186                    wordwise: false,
 8187                    done: false,
 8188                });
 8189                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8190            }
 8191        }
 8192        Ok(())
 8193    }
 8194
 8195    pub fn select_all_matches(
 8196        &mut self,
 8197        _action: &SelectAllMatches,
 8198        cx: &mut ViewContext<Self>,
 8199    ) -> Result<()> {
 8200        self.push_to_selection_history();
 8201        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8202
 8203        self.select_next_match_internal(&display_map, false, None, cx)?;
 8204        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8205            return Ok(());
 8206        };
 8207        if select_next_state.done {
 8208            return Ok(());
 8209        }
 8210
 8211        let mut new_selections = self.selections.all::<usize>(cx);
 8212
 8213        let buffer = &display_map.buffer_snapshot;
 8214        let query_matches = select_next_state
 8215            .query
 8216            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8217
 8218        for query_match in query_matches {
 8219            let query_match = query_match.unwrap(); // can only fail due to I/O
 8220            let offset_range = query_match.start()..query_match.end();
 8221            let display_range = offset_range.start.to_display_point(&display_map)
 8222                ..offset_range.end.to_display_point(&display_map);
 8223
 8224            if !select_next_state.wordwise
 8225                || (!movement::is_inside_word(&display_map, display_range.start)
 8226                    && !movement::is_inside_word(&display_map, display_range.end))
 8227            {
 8228                self.selections.change_with(cx, |selections| {
 8229                    new_selections.push(Selection {
 8230                        id: selections.new_selection_id(),
 8231                        start: offset_range.start,
 8232                        end: offset_range.end,
 8233                        reversed: false,
 8234                        goal: SelectionGoal::None,
 8235                    });
 8236                });
 8237            }
 8238        }
 8239
 8240        new_selections.sort_by_key(|selection| selection.start);
 8241        let mut ix = 0;
 8242        while ix + 1 < new_selections.len() {
 8243            let current_selection = &new_selections[ix];
 8244            let next_selection = &new_selections[ix + 1];
 8245            if current_selection.range().overlaps(&next_selection.range()) {
 8246                if current_selection.id < next_selection.id {
 8247                    new_selections.remove(ix + 1);
 8248                } else {
 8249                    new_selections.remove(ix);
 8250                }
 8251            } else {
 8252                ix += 1;
 8253            }
 8254        }
 8255
 8256        select_next_state.done = true;
 8257        self.unfold_ranges(
 8258            &new_selections
 8259                .iter()
 8260                .map(|selection| selection.range())
 8261                .collect::<Vec<_>>(),
 8262            false,
 8263            false,
 8264            cx,
 8265        );
 8266        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8267            selections.select(new_selections)
 8268        });
 8269
 8270        Ok(())
 8271    }
 8272
 8273    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8274        self.push_to_selection_history();
 8275        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8276        self.select_next_match_internal(
 8277            &display_map,
 8278            action.replace_newest,
 8279            Some(Autoscroll::newest()),
 8280            cx,
 8281        )?;
 8282        Ok(())
 8283    }
 8284
 8285    pub fn select_previous(
 8286        &mut self,
 8287        action: &SelectPrevious,
 8288        cx: &mut ViewContext<Self>,
 8289    ) -> Result<()> {
 8290        self.push_to_selection_history();
 8291        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8292        let buffer = &display_map.buffer_snapshot;
 8293        let mut selections = self.selections.all::<usize>(cx);
 8294        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8295            let query = &select_prev_state.query;
 8296            if !select_prev_state.done {
 8297                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8298                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8299                let mut next_selected_range = None;
 8300                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8301                let bytes_before_last_selection =
 8302                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8303                let bytes_after_first_selection =
 8304                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8305                let query_matches = query
 8306                    .stream_find_iter(bytes_before_last_selection)
 8307                    .map(|result| (last_selection.start, result))
 8308                    .chain(
 8309                        query
 8310                            .stream_find_iter(bytes_after_first_selection)
 8311                            .map(|result| (buffer.len(), result)),
 8312                    );
 8313                for (end_offset, query_match) in query_matches {
 8314                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8315                    let offset_range =
 8316                        end_offset - query_match.end()..end_offset - query_match.start();
 8317                    let display_range = offset_range.start.to_display_point(&display_map)
 8318                        ..offset_range.end.to_display_point(&display_map);
 8319
 8320                    if !select_prev_state.wordwise
 8321                        || (!movement::is_inside_word(&display_map, display_range.start)
 8322                            && !movement::is_inside_word(&display_map, display_range.end))
 8323                    {
 8324                        next_selected_range = Some(offset_range);
 8325                        break;
 8326                    }
 8327                }
 8328
 8329                if let Some(next_selected_range) = next_selected_range {
 8330                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8331                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8332                        if action.replace_newest {
 8333                            s.delete(s.newest_anchor().id);
 8334                        }
 8335                        s.insert_range(next_selected_range);
 8336                    });
 8337                } else {
 8338                    select_prev_state.done = true;
 8339                }
 8340            }
 8341
 8342            self.select_prev_state = Some(select_prev_state);
 8343        } else {
 8344            let mut only_carets = true;
 8345            let mut same_text_selected = true;
 8346            let mut selected_text = None;
 8347
 8348            let mut selections_iter = selections.iter().peekable();
 8349            while let Some(selection) = selections_iter.next() {
 8350                if selection.start != selection.end {
 8351                    only_carets = false;
 8352                }
 8353
 8354                if same_text_selected {
 8355                    if selected_text.is_none() {
 8356                        selected_text =
 8357                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8358                    }
 8359
 8360                    if let Some(next_selection) = selections_iter.peek() {
 8361                        if next_selection.range().len() == selection.range().len() {
 8362                            let next_selected_text = buffer
 8363                                .text_for_range(next_selection.range())
 8364                                .collect::<String>();
 8365                            if Some(next_selected_text) != selected_text {
 8366                                same_text_selected = false;
 8367                                selected_text = None;
 8368                            }
 8369                        } else {
 8370                            same_text_selected = false;
 8371                            selected_text = None;
 8372                        }
 8373                    }
 8374                }
 8375            }
 8376
 8377            if only_carets {
 8378                for selection in &mut selections {
 8379                    let word_range = movement::surrounding_word(
 8380                        &display_map,
 8381                        selection.start.to_display_point(&display_map),
 8382                    );
 8383                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8384                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8385                    selection.goal = SelectionGoal::None;
 8386                    selection.reversed = false;
 8387                }
 8388                if selections.len() == 1 {
 8389                    let selection = selections
 8390                        .last()
 8391                        .expect("ensured that there's only one selection");
 8392                    let query = buffer
 8393                        .text_for_range(selection.start..selection.end)
 8394                        .collect::<String>();
 8395                    let is_empty = query.is_empty();
 8396                    let select_state = SelectNextState {
 8397                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8398                        wordwise: true,
 8399                        done: is_empty,
 8400                    };
 8401                    self.select_prev_state = Some(select_state);
 8402                } else {
 8403                    self.select_prev_state = None;
 8404                }
 8405
 8406                self.unfold_ranges(
 8407                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8408                    false,
 8409                    true,
 8410                    cx,
 8411                );
 8412                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8413                    s.select(selections);
 8414                });
 8415            } else if let Some(selected_text) = selected_text {
 8416                self.select_prev_state = Some(SelectNextState {
 8417                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8418                    wordwise: false,
 8419                    done: false,
 8420                });
 8421                self.select_previous(action, cx)?;
 8422            }
 8423        }
 8424        Ok(())
 8425    }
 8426
 8427    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8428        if self.read_only(cx) {
 8429            return;
 8430        }
 8431        let text_layout_details = &self.text_layout_details(cx);
 8432        self.transact(cx, |this, cx| {
 8433            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8434            let mut edits = Vec::new();
 8435            let mut selection_edit_ranges = Vec::new();
 8436            let mut last_toggled_row = None;
 8437            let snapshot = this.buffer.read(cx).read(cx);
 8438            let empty_str: Arc<str> = Arc::default();
 8439            let mut suffixes_inserted = Vec::new();
 8440            let ignore_indent = action.ignore_indent;
 8441
 8442            fn comment_prefix_range(
 8443                snapshot: &MultiBufferSnapshot,
 8444                row: MultiBufferRow,
 8445                comment_prefix: &str,
 8446                comment_prefix_whitespace: &str,
 8447                ignore_indent: bool,
 8448            ) -> Range<Point> {
 8449                let indent_size = if ignore_indent {
 8450                    0
 8451                } else {
 8452                    snapshot.indent_size_for_line(row).len
 8453                };
 8454
 8455                let start = Point::new(row.0, indent_size);
 8456
 8457                let mut line_bytes = snapshot
 8458                    .bytes_in_range(start..snapshot.max_point())
 8459                    .flatten()
 8460                    .copied();
 8461
 8462                // If this line currently begins with the line comment prefix, then record
 8463                // the range containing the prefix.
 8464                if line_bytes
 8465                    .by_ref()
 8466                    .take(comment_prefix.len())
 8467                    .eq(comment_prefix.bytes())
 8468                {
 8469                    // Include any whitespace that matches the comment prefix.
 8470                    let matching_whitespace_len = line_bytes
 8471                        .zip(comment_prefix_whitespace.bytes())
 8472                        .take_while(|(a, b)| a == b)
 8473                        .count() as u32;
 8474                    let end = Point::new(
 8475                        start.row,
 8476                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8477                    );
 8478                    start..end
 8479                } else {
 8480                    start..start
 8481                }
 8482            }
 8483
 8484            fn comment_suffix_range(
 8485                snapshot: &MultiBufferSnapshot,
 8486                row: MultiBufferRow,
 8487                comment_suffix: &str,
 8488                comment_suffix_has_leading_space: bool,
 8489            ) -> Range<Point> {
 8490                let end = Point::new(row.0, snapshot.line_len(row));
 8491                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8492
 8493                let mut line_end_bytes = snapshot
 8494                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8495                    .flatten()
 8496                    .copied();
 8497
 8498                let leading_space_len = if suffix_start_column > 0
 8499                    && line_end_bytes.next() == Some(b' ')
 8500                    && comment_suffix_has_leading_space
 8501                {
 8502                    1
 8503                } else {
 8504                    0
 8505                };
 8506
 8507                // If this line currently begins with the line comment prefix, then record
 8508                // the range containing the prefix.
 8509                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8510                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8511                    start..end
 8512                } else {
 8513                    end..end
 8514                }
 8515            }
 8516
 8517            // TODO: Handle selections that cross excerpts
 8518            for selection in &mut selections {
 8519                let start_column = snapshot
 8520                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8521                    .len;
 8522                let language = if let Some(language) =
 8523                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8524                {
 8525                    language
 8526                } else {
 8527                    continue;
 8528                };
 8529
 8530                selection_edit_ranges.clear();
 8531
 8532                // If multiple selections contain a given row, avoid processing that
 8533                // row more than once.
 8534                let mut start_row = MultiBufferRow(selection.start.row);
 8535                if last_toggled_row == Some(start_row) {
 8536                    start_row = start_row.next_row();
 8537                }
 8538                let end_row =
 8539                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8540                        MultiBufferRow(selection.end.row - 1)
 8541                    } else {
 8542                        MultiBufferRow(selection.end.row)
 8543                    };
 8544                last_toggled_row = Some(end_row);
 8545
 8546                if start_row > end_row {
 8547                    continue;
 8548                }
 8549
 8550                // If the language has line comments, toggle those.
 8551                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8552
 8553                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8554                if ignore_indent {
 8555                    full_comment_prefixes = full_comment_prefixes
 8556                        .into_iter()
 8557                        .map(|s| Arc::from(s.trim_end()))
 8558                        .collect();
 8559                }
 8560
 8561                if !full_comment_prefixes.is_empty() {
 8562                    let first_prefix = full_comment_prefixes
 8563                        .first()
 8564                        .expect("prefixes is non-empty");
 8565                    let prefix_trimmed_lengths = full_comment_prefixes
 8566                        .iter()
 8567                        .map(|p| p.trim_end_matches(' ').len())
 8568                        .collect::<SmallVec<[usize; 4]>>();
 8569
 8570                    let mut all_selection_lines_are_comments = true;
 8571
 8572                    for row in start_row.0..=end_row.0 {
 8573                        let row = MultiBufferRow(row);
 8574                        if start_row < end_row && snapshot.is_line_blank(row) {
 8575                            continue;
 8576                        }
 8577
 8578                        let prefix_range = full_comment_prefixes
 8579                            .iter()
 8580                            .zip(prefix_trimmed_lengths.iter().copied())
 8581                            .map(|(prefix, trimmed_prefix_len)| {
 8582                                comment_prefix_range(
 8583                                    snapshot.deref(),
 8584                                    row,
 8585                                    &prefix[..trimmed_prefix_len],
 8586                                    &prefix[trimmed_prefix_len..],
 8587                                    ignore_indent,
 8588                                )
 8589                            })
 8590                            .max_by_key(|range| range.end.column - range.start.column)
 8591                            .expect("prefixes is non-empty");
 8592
 8593                        if prefix_range.is_empty() {
 8594                            all_selection_lines_are_comments = false;
 8595                        }
 8596
 8597                        selection_edit_ranges.push(prefix_range);
 8598                    }
 8599
 8600                    if all_selection_lines_are_comments {
 8601                        edits.extend(
 8602                            selection_edit_ranges
 8603                                .iter()
 8604                                .cloned()
 8605                                .map(|range| (range, empty_str.clone())),
 8606                        );
 8607                    } else {
 8608                        let min_column = selection_edit_ranges
 8609                            .iter()
 8610                            .map(|range| range.start.column)
 8611                            .min()
 8612                            .unwrap_or(0);
 8613                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8614                            let position = Point::new(range.start.row, min_column);
 8615                            (position..position, first_prefix.clone())
 8616                        }));
 8617                    }
 8618                } else if let Some((full_comment_prefix, comment_suffix)) =
 8619                    language.block_comment_delimiters()
 8620                {
 8621                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8622                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8623                    let prefix_range = comment_prefix_range(
 8624                        snapshot.deref(),
 8625                        start_row,
 8626                        comment_prefix,
 8627                        comment_prefix_whitespace,
 8628                        ignore_indent,
 8629                    );
 8630                    let suffix_range = comment_suffix_range(
 8631                        snapshot.deref(),
 8632                        end_row,
 8633                        comment_suffix.trim_start_matches(' '),
 8634                        comment_suffix.starts_with(' '),
 8635                    );
 8636
 8637                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8638                        edits.push((
 8639                            prefix_range.start..prefix_range.start,
 8640                            full_comment_prefix.clone(),
 8641                        ));
 8642                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8643                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8644                    } else {
 8645                        edits.push((prefix_range, empty_str.clone()));
 8646                        edits.push((suffix_range, empty_str.clone()));
 8647                    }
 8648                } else {
 8649                    continue;
 8650                }
 8651            }
 8652
 8653            drop(snapshot);
 8654            this.buffer.update(cx, |buffer, cx| {
 8655                buffer.edit(edits, None, cx);
 8656            });
 8657
 8658            // Adjust selections so that they end before any comment suffixes that
 8659            // were inserted.
 8660            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8661            let mut selections = this.selections.all::<Point>(cx);
 8662            let snapshot = this.buffer.read(cx).read(cx);
 8663            for selection in &mut selections {
 8664                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8665                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8666                        Ordering::Less => {
 8667                            suffixes_inserted.next();
 8668                            continue;
 8669                        }
 8670                        Ordering::Greater => break,
 8671                        Ordering::Equal => {
 8672                            if selection.end.column == snapshot.line_len(row) {
 8673                                if selection.is_empty() {
 8674                                    selection.start.column -= suffix_len as u32;
 8675                                }
 8676                                selection.end.column -= suffix_len as u32;
 8677                            }
 8678                            break;
 8679                        }
 8680                    }
 8681                }
 8682            }
 8683
 8684            drop(snapshot);
 8685            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8686
 8687            let selections = this.selections.all::<Point>(cx);
 8688            let selections_on_single_row = selections.windows(2).all(|selections| {
 8689                selections[0].start.row == selections[1].start.row
 8690                    && selections[0].end.row == selections[1].end.row
 8691                    && selections[0].start.row == selections[0].end.row
 8692            });
 8693            let selections_selecting = selections
 8694                .iter()
 8695                .any(|selection| selection.start != selection.end);
 8696            let advance_downwards = action.advance_downwards
 8697                && selections_on_single_row
 8698                && !selections_selecting
 8699                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8700
 8701            if advance_downwards {
 8702                let snapshot = this.buffer.read(cx).snapshot(cx);
 8703
 8704                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8705                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8706                        let mut point = display_point.to_point(display_snapshot);
 8707                        point.row += 1;
 8708                        point = snapshot.clip_point(point, Bias::Left);
 8709                        let display_point = point.to_display_point(display_snapshot);
 8710                        let goal = SelectionGoal::HorizontalPosition(
 8711                            display_snapshot
 8712                                .x_for_display_point(display_point, text_layout_details)
 8713                                .into(),
 8714                        );
 8715                        (display_point, goal)
 8716                    })
 8717                });
 8718            }
 8719        });
 8720    }
 8721
 8722    pub fn select_enclosing_symbol(
 8723        &mut self,
 8724        _: &SelectEnclosingSymbol,
 8725        cx: &mut ViewContext<Self>,
 8726    ) {
 8727        let buffer = self.buffer.read(cx).snapshot(cx);
 8728        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8729
 8730        fn update_selection(
 8731            selection: &Selection<usize>,
 8732            buffer_snap: &MultiBufferSnapshot,
 8733        ) -> Option<Selection<usize>> {
 8734            let cursor = selection.head();
 8735            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8736            for symbol in symbols.iter().rev() {
 8737                let start = symbol.range.start.to_offset(buffer_snap);
 8738                let end = symbol.range.end.to_offset(buffer_snap);
 8739                let new_range = start..end;
 8740                if start < selection.start || end > selection.end {
 8741                    return Some(Selection {
 8742                        id: selection.id,
 8743                        start: new_range.start,
 8744                        end: new_range.end,
 8745                        goal: SelectionGoal::None,
 8746                        reversed: selection.reversed,
 8747                    });
 8748                }
 8749            }
 8750            None
 8751        }
 8752
 8753        let mut selected_larger_symbol = false;
 8754        let new_selections = old_selections
 8755            .iter()
 8756            .map(|selection| match update_selection(selection, &buffer) {
 8757                Some(new_selection) => {
 8758                    if new_selection.range() != selection.range() {
 8759                        selected_larger_symbol = true;
 8760                    }
 8761                    new_selection
 8762                }
 8763                None => selection.clone(),
 8764            })
 8765            .collect::<Vec<_>>();
 8766
 8767        if selected_larger_symbol {
 8768            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8769                s.select(new_selections);
 8770            });
 8771        }
 8772    }
 8773
 8774    pub fn select_larger_syntax_node(
 8775        &mut self,
 8776        _: &SelectLargerSyntaxNode,
 8777        cx: &mut ViewContext<Self>,
 8778    ) {
 8779        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8780        let buffer = self.buffer.read(cx).snapshot(cx);
 8781        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8782
 8783        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8784        let mut selected_larger_node = false;
 8785        let new_selections = old_selections
 8786            .iter()
 8787            .map(|selection| {
 8788                let old_range = selection.start..selection.end;
 8789                let mut new_range = old_range.clone();
 8790                let mut new_node = None;
 8791                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 8792                {
 8793                    new_node = Some(node);
 8794                    new_range = containing_range;
 8795                    if !display_map.intersects_fold(new_range.start)
 8796                        && !display_map.intersects_fold(new_range.end)
 8797                    {
 8798                        break;
 8799                    }
 8800                }
 8801
 8802                if let Some(node) = new_node {
 8803                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 8804                    // nodes. Parent and grandparent are also logged because this operation will not
 8805                    // visit nodes that have the same range as their parent.
 8806                    log::info!("Node: {node:?}");
 8807                    let parent = node.parent();
 8808                    log::info!("Parent: {parent:?}");
 8809                    let grandparent = parent.and_then(|x| x.parent());
 8810                    log::info!("Grandparent: {grandparent:?}");
 8811                }
 8812
 8813                selected_larger_node |= new_range != old_range;
 8814                Selection {
 8815                    id: selection.id,
 8816                    start: new_range.start,
 8817                    end: new_range.end,
 8818                    goal: SelectionGoal::None,
 8819                    reversed: selection.reversed,
 8820                }
 8821            })
 8822            .collect::<Vec<_>>();
 8823
 8824        if selected_larger_node {
 8825            stack.push(old_selections);
 8826            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8827                s.select(new_selections);
 8828            });
 8829        }
 8830        self.select_larger_syntax_node_stack = stack;
 8831    }
 8832
 8833    pub fn select_smaller_syntax_node(
 8834        &mut self,
 8835        _: &SelectSmallerSyntaxNode,
 8836        cx: &mut ViewContext<Self>,
 8837    ) {
 8838        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8839        if let Some(selections) = stack.pop() {
 8840            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8841                s.select(selections.to_vec());
 8842            });
 8843        }
 8844        self.select_larger_syntax_node_stack = stack;
 8845    }
 8846
 8847    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8848        if !EditorSettings::get_global(cx).gutter.runnables {
 8849            self.clear_tasks();
 8850            return Task::ready(());
 8851        }
 8852        let project = self.project.as_ref().map(Model::downgrade);
 8853        cx.spawn(|this, mut cx| async move {
 8854            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8855            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8856                return;
 8857            };
 8858            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8859                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8860            }) else {
 8861                return;
 8862            };
 8863
 8864            let hide_runnables = project
 8865                .update(&mut cx, |project, cx| {
 8866                    // Do not display any test indicators in non-dev server remote projects.
 8867                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8868                })
 8869                .unwrap_or(true);
 8870            if hide_runnables {
 8871                return;
 8872            }
 8873            let new_rows =
 8874                cx.background_executor()
 8875                    .spawn({
 8876                        let snapshot = display_snapshot.clone();
 8877                        async move {
 8878                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8879                        }
 8880                    })
 8881                    .await;
 8882            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8883
 8884            this.update(&mut cx, |this, _| {
 8885                this.clear_tasks();
 8886                for (key, value) in rows {
 8887                    this.insert_tasks(key, value);
 8888                }
 8889            })
 8890            .ok();
 8891        })
 8892    }
 8893    fn fetch_runnable_ranges(
 8894        snapshot: &DisplaySnapshot,
 8895        range: Range<Anchor>,
 8896    ) -> Vec<language::RunnableRange> {
 8897        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8898    }
 8899
 8900    fn runnable_rows(
 8901        project: Model<Project>,
 8902        snapshot: DisplaySnapshot,
 8903        runnable_ranges: Vec<RunnableRange>,
 8904        mut cx: AsyncWindowContext,
 8905    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8906        runnable_ranges
 8907            .into_iter()
 8908            .filter_map(|mut runnable| {
 8909                let tasks = cx
 8910                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8911                    .ok()?;
 8912                if tasks.is_empty() {
 8913                    return None;
 8914                }
 8915
 8916                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8917
 8918                let row = snapshot
 8919                    .buffer_snapshot
 8920                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8921                    .1
 8922                    .start
 8923                    .row;
 8924
 8925                let context_range =
 8926                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8927                Some((
 8928                    (runnable.buffer_id, row),
 8929                    RunnableTasks {
 8930                        templates: tasks,
 8931                        offset: MultiBufferOffset(runnable.run_range.start),
 8932                        context_range,
 8933                        column: point.column,
 8934                        extra_variables: runnable.extra_captures,
 8935                    },
 8936                ))
 8937            })
 8938            .collect()
 8939    }
 8940
 8941    fn templates_with_tags(
 8942        project: &Model<Project>,
 8943        runnable: &mut Runnable,
 8944        cx: &WindowContext,
 8945    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8946        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8947            let (worktree_id, file) = project
 8948                .buffer_for_id(runnable.buffer, cx)
 8949                .and_then(|buffer| buffer.read(cx).file())
 8950                .map(|file| (file.worktree_id(cx), file.clone()))
 8951                .unzip();
 8952
 8953            (
 8954                project.task_store().read(cx).task_inventory().cloned(),
 8955                worktree_id,
 8956                file,
 8957            )
 8958        });
 8959
 8960        let tags = mem::take(&mut runnable.tags);
 8961        let mut tags: Vec<_> = tags
 8962            .into_iter()
 8963            .flat_map(|tag| {
 8964                let tag = tag.0.clone();
 8965                inventory
 8966                    .as_ref()
 8967                    .into_iter()
 8968                    .flat_map(|inventory| {
 8969                        inventory.read(cx).list_tasks(
 8970                            file.clone(),
 8971                            Some(runnable.language.clone()),
 8972                            worktree_id,
 8973                            cx,
 8974                        )
 8975                    })
 8976                    .filter(move |(_, template)| {
 8977                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8978                    })
 8979            })
 8980            .sorted_by_key(|(kind, _)| kind.to_owned())
 8981            .collect();
 8982        if let Some((leading_tag_source, _)) = tags.first() {
 8983            // Strongest source wins; if we have worktree tag binding, prefer that to
 8984            // global and language bindings;
 8985            // if we have a global binding, prefer that to language binding.
 8986            let first_mismatch = tags
 8987                .iter()
 8988                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8989            if let Some(index) = first_mismatch {
 8990                tags.truncate(index);
 8991            }
 8992        }
 8993
 8994        tags
 8995    }
 8996
 8997    pub fn move_to_enclosing_bracket(
 8998        &mut self,
 8999        _: &MoveToEnclosingBracket,
 9000        cx: &mut ViewContext<Self>,
 9001    ) {
 9002        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9003            s.move_offsets_with(|snapshot, selection| {
 9004                let Some(enclosing_bracket_ranges) =
 9005                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9006                else {
 9007                    return;
 9008                };
 9009
 9010                let mut best_length = usize::MAX;
 9011                let mut best_inside = false;
 9012                let mut best_in_bracket_range = false;
 9013                let mut best_destination = None;
 9014                for (open, close) in enclosing_bracket_ranges {
 9015                    let close = close.to_inclusive();
 9016                    let length = close.end() - open.start;
 9017                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9018                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9019                        || close.contains(&selection.head());
 9020
 9021                    // If best is next to a bracket and current isn't, skip
 9022                    if !in_bracket_range && best_in_bracket_range {
 9023                        continue;
 9024                    }
 9025
 9026                    // Prefer smaller lengths unless best is inside and current isn't
 9027                    if length > best_length && (best_inside || !inside) {
 9028                        continue;
 9029                    }
 9030
 9031                    best_length = length;
 9032                    best_inside = inside;
 9033                    best_in_bracket_range = in_bracket_range;
 9034                    best_destination = Some(
 9035                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9036                            if inside {
 9037                                open.end
 9038                            } else {
 9039                                open.start
 9040                            }
 9041                        } else if inside {
 9042                            *close.start()
 9043                        } else {
 9044                            *close.end()
 9045                        },
 9046                    );
 9047                }
 9048
 9049                if let Some(destination) = best_destination {
 9050                    selection.collapse_to(destination, SelectionGoal::None);
 9051                }
 9052            })
 9053        });
 9054    }
 9055
 9056    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9057        self.end_selection(cx);
 9058        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9059        if let Some(entry) = self.selection_history.undo_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 redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9070        self.end_selection(cx);
 9071        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9072        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9073            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9074            self.select_next_state = entry.select_next_state;
 9075            self.select_prev_state = entry.select_prev_state;
 9076            self.add_selections_state = entry.add_selections_state;
 9077            self.request_autoscroll(Autoscroll::newest(), cx);
 9078        }
 9079        self.selection_history.mode = SelectionHistoryMode::Normal;
 9080    }
 9081
 9082    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9083        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9084    }
 9085
 9086    pub fn expand_excerpts_down(
 9087        &mut self,
 9088        action: &ExpandExcerptsDown,
 9089        cx: &mut ViewContext<Self>,
 9090    ) {
 9091        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9092    }
 9093
 9094    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9095        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9096    }
 9097
 9098    pub fn expand_excerpts_for_direction(
 9099        &mut self,
 9100        lines: u32,
 9101        direction: ExpandExcerptDirection,
 9102        cx: &mut ViewContext<Self>,
 9103    ) {
 9104        let selections = self.selections.disjoint_anchors();
 9105
 9106        let lines = if lines == 0 {
 9107            EditorSettings::get_global(cx).expand_excerpt_lines
 9108        } else {
 9109            lines
 9110        };
 9111
 9112        self.buffer.update(cx, |buffer, cx| {
 9113            buffer.expand_excerpts(
 9114                selections
 9115                    .iter()
 9116                    .map(|selection| selection.head().excerpt_id)
 9117                    .dedup(),
 9118                lines,
 9119                direction,
 9120                cx,
 9121            )
 9122        })
 9123    }
 9124
 9125    pub fn expand_excerpt(
 9126        &mut self,
 9127        excerpt: ExcerptId,
 9128        direction: ExpandExcerptDirection,
 9129        cx: &mut ViewContext<Self>,
 9130    ) {
 9131        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9132        self.buffer.update(cx, |buffer, cx| {
 9133            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9134        })
 9135    }
 9136
 9137    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9138        self.go_to_diagnostic_impl(Direction::Next, cx)
 9139    }
 9140
 9141    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9142        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9143    }
 9144
 9145    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9146        let buffer = self.buffer.read(cx).snapshot(cx);
 9147        let selection = self.selections.newest::<usize>(cx);
 9148
 9149        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9150        if direction == Direction::Next {
 9151            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9152                let (group_id, jump_to) = popover.activation_info();
 9153                if self.activate_diagnostics(group_id, cx) {
 9154                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9155                        let mut new_selection = s.newest_anchor().clone();
 9156                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9157                        s.select_anchors(vec![new_selection.clone()]);
 9158                    });
 9159                }
 9160                return;
 9161            }
 9162        }
 9163
 9164        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9165            active_diagnostics
 9166                .primary_range
 9167                .to_offset(&buffer)
 9168                .to_inclusive()
 9169        });
 9170        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9171            if active_primary_range.contains(&selection.head()) {
 9172                *active_primary_range.start()
 9173            } else {
 9174                selection.head()
 9175            }
 9176        } else {
 9177            selection.head()
 9178        };
 9179        let snapshot = self.snapshot(cx);
 9180        loop {
 9181            let diagnostics = if direction == Direction::Prev {
 9182                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9183            } else {
 9184                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9185            }
 9186            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9187            let group = diagnostics
 9188                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9189                // be sorted in a stable way
 9190                // skip until we are at current active diagnostic, if it exists
 9191                .skip_while(|entry| {
 9192                    (match direction {
 9193                        Direction::Prev => entry.range.start >= search_start,
 9194                        Direction::Next => entry.range.start <= search_start,
 9195                    }) && self
 9196                        .active_diagnostics
 9197                        .as_ref()
 9198                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9199                })
 9200                .find_map(|entry| {
 9201                    if entry.diagnostic.is_primary
 9202                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9203                        && !entry.range.is_empty()
 9204                        // if we match with the active diagnostic, skip it
 9205                        && Some(entry.diagnostic.group_id)
 9206                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9207                    {
 9208                        Some((entry.range, entry.diagnostic.group_id))
 9209                    } else {
 9210                        None
 9211                    }
 9212                });
 9213
 9214            if let Some((primary_range, group_id)) = group {
 9215                if self.activate_diagnostics(group_id, cx) {
 9216                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9217                        s.select(vec![Selection {
 9218                            id: selection.id,
 9219                            start: primary_range.start,
 9220                            end: primary_range.start,
 9221                            reversed: false,
 9222                            goal: SelectionGoal::None,
 9223                        }]);
 9224                    });
 9225                }
 9226                break;
 9227            } else {
 9228                // Cycle around to the start of the buffer, potentially moving back to the start of
 9229                // the currently active diagnostic.
 9230                active_primary_range.take();
 9231                if direction == Direction::Prev {
 9232                    if search_start == buffer.len() {
 9233                        break;
 9234                    } else {
 9235                        search_start = buffer.len();
 9236                    }
 9237                } else if search_start == 0 {
 9238                    break;
 9239                } else {
 9240                    search_start = 0;
 9241                }
 9242            }
 9243        }
 9244    }
 9245
 9246    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9247        let snapshot = self.snapshot(cx);
 9248        let selection = self.selections.newest::<Point>(cx);
 9249        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9250    }
 9251
 9252    fn go_to_hunk_after_position(
 9253        &mut self,
 9254        snapshot: &EditorSnapshot,
 9255        position: Point,
 9256        cx: &mut ViewContext<Editor>,
 9257    ) -> Option<MultiBufferDiffHunk> {
 9258        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9259            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9260                snapshot,
 9261                position,
 9262                ix > 0,
 9263                snapshot.diff_map.diff_hunks_in_range(
 9264                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9265                    &snapshot.buffer_snapshot,
 9266                ),
 9267                cx,
 9268            ) {
 9269                return Some(hunk);
 9270            }
 9271        }
 9272        None
 9273    }
 9274
 9275    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9276        let snapshot = self.snapshot(cx);
 9277        let selection = self.selections.newest::<Point>(cx);
 9278        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9279    }
 9280
 9281    fn go_to_hunk_before_position(
 9282        &mut self,
 9283        snapshot: &EditorSnapshot,
 9284        position: Point,
 9285        cx: &mut ViewContext<Editor>,
 9286    ) -> Option<MultiBufferDiffHunk> {
 9287        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9288            .into_iter()
 9289            .enumerate()
 9290        {
 9291            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9292                snapshot,
 9293                position,
 9294                ix > 0,
 9295                snapshot
 9296                    .diff_map
 9297                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9298                cx,
 9299            ) {
 9300                return Some(hunk);
 9301            }
 9302        }
 9303        None
 9304    }
 9305
 9306    fn go_to_next_hunk_in_direction(
 9307        &mut self,
 9308        snapshot: &DisplaySnapshot,
 9309        initial_point: Point,
 9310        is_wrapped: bool,
 9311        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9312        cx: &mut ViewContext<Editor>,
 9313    ) -> Option<MultiBufferDiffHunk> {
 9314        let display_point = initial_point.to_display_point(snapshot);
 9315        let mut hunks = hunks
 9316            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9317            .filter(|(display_hunk, _)| {
 9318                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9319            })
 9320            .dedup();
 9321
 9322        if let Some((display_hunk, hunk)) = hunks.next() {
 9323            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9324                let row = display_hunk.start_display_row();
 9325                let point = DisplayPoint::new(row, 0);
 9326                s.select_display_ranges([point..point]);
 9327            });
 9328
 9329            Some(hunk)
 9330        } else {
 9331            None
 9332        }
 9333    }
 9334
 9335    pub fn go_to_definition(
 9336        &mut self,
 9337        _: &GoToDefinition,
 9338        cx: &mut ViewContext<Self>,
 9339    ) -> Task<Result<Navigated>> {
 9340        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9341        cx.spawn(|editor, mut cx| async move {
 9342            if definition.await? == Navigated::Yes {
 9343                return Ok(Navigated::Yes);
 9344            }
 9345            match editor.update(&mut cx, |editor, cx| {
 9346                editor.find_all_references(&FindAllReferences, cx)
 9347            })? {
 9348                Some(references) => references.await,
 9349                None => Ok(Navigated::No),
 9350            }
 9351        })
 9352    }
 9353
 9354    pub fn go_to_declaration(
 9355        &mut self,
 9356        _: &GoToDeclaration,
 9357        cx: &mut ViewContext<Self>,
 9358    ) -> Task<Result<Navigated>> {
 9359        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9360    }
 9361
 9362    pub fn go_to_declaration_split(
 9363        &mut self,
 9364        _: &GoToDeclaration,
 9365        cx: &mut ViewContext<Self>,
 9366    ) -> Task<Result<Navigated>> {
 9367        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9368    }
 9369
 9370    pub fn go_to_implementation(
 9371        &mut self,
 9372        _: &GoToImplementation,
 9373        cx: &mut ViewContext<Self>,
 9374    ) -> Task<Result<Navigated>> {
 9375        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9376    }
 9377
 9378    pub fn go_to_implementation_split(
 9379        &mut self,
 9380        _: &GoToImplementationSplit,
 9381        cx: &mut ViewContext<Self>,
 9382    ) -> Task<Result<Navigated>> {
 9383        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9384    }
 9385
 9386    pub fn go_to_type_definition(
 9387        &mut self,
 9388        _: &GoToTypeDefinition,
 9389        cx: &mut ViewContext<Self>,
 9390    ) -> Task<Result<Navigated>> {
 9391        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9392    }
 9393
 9394    pub fn go_to_definition_split(
 9395        &mut self,
 9396        _: &GoToDefinitionSplit,
 9397        cx: &mut ViewContext<Self>,
 9398    ) -> Task<Result<Navigated>> {
 9399        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9400    }
 9401
 9402    pub fn go_to_type_definition_split(
 9403        &mut self,
 9404        _: &GoToTypeDefinitionSplit,
 9405        cx: &mut ViewContext<Self>,
 9406    ) -> Task<Result<Navigated>> {
 9407        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9408    }
 9409
 9410    fn go_to_definition_of_kind(
 9411        &mut self,
 9412        kind: GotoDefinitionKind,
 9413        split: bool,
 9414        cx: &mut ViewContext<Self>,
 9415    ) -> Task<Result<Navigated>> {
 9416        let Some(provider) = self.semantics_provider.clone() else {
 9417            return Task::ready(Ok(Navigated::No));
 9418        };
 9419        let head = self.selections.newest::<usize>(cx).head();
 9420        let buffer = self.buffer.read(cx);
 9421        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9422            text_anchor
 9423        } else {
 9424            return Task::ready(Ok(Navigated::No));
 9425        };
 9426
 9427        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9428            return Task::ready(Ok(Navigated::No));
 9429        };
 9430
 9431        cx.spawn(|editor, mut cx| async move {
 9432            let definitions = definitions.await?;
 9433            let navigated = editor
 9434                .update(&mut cx, |editor, cx| {
 9435                    editor.navigate_to_hover_links(
 9436                        Some(kind),
 9437                        definitions
 9438                            .into_iter()
 9439                            .filter(|location| {
 9440                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9441                            })
 9442                            .map(HoverLink::Text)
 9443                            .collect::<Vec<_>>(),
 9444                        split,
 9445                        cx,
 9446                    )
 9447                })?
 9448                .await?;
 9449            anyhow::Ok(navigated)
 9450        })
 9451    }
 9452
 9453    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9454        let selection = self.selections.newest_anchor();
 9455        let head = selection.head();
 9456        let tail = selection.tail();
 9457
 9458        let Some((buffer, start_position)) =
 9459            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9460        else {
 9461            return;
 9462        };
 9463
 9464        let end_position = if head != tail {
 9465            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9466                return;
 9467            };
 9468            Some(pos)
 9469        } else {
 9470            None
 9471        };
 9472
 9473        let url_finder = cx.spawn(|editor, mut cx| async move {
 9474            let url = if let Some(end_pos) = end_position {
 9475                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9476            } else {
 9477                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9478            };
 9479
 9480            if let Some(url) = url {
 9481                editor.update(&mut cx, |_, cx| {
 9482                    cx.open_url(&url);
 9483                })
 9484            } else {
 9485                Ok(())
 9486            }
 9487        });
 9488
 9489        url_finder.detach();
 9490    }
 9491
 9492    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9493        let Some(workspace) = self.workspace() else {
 9494            return;
 9495        };
 9496
 9497        let position = self.selections.newest_anchor().head();
 9498
 9499        let Some((buffer, buffer_position)) =
 9500            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9501        else {
 9502            return;
 9503        };
 9504
 9505        let project = self.project.clone();
 9506
 9507        cx.spawn(|_, mut cx| async move {
 9508            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9509
 9510            if let Some((_, path)) = result {
 9511                workspace
 9512                    .update(&mut cx, |workspace, cx| {
 9513                        workspace.open_resolved_path(path, cx)
 9514                    })?
 9515                    .await?;
 9516            }
 9517            anyhow::Ok(())
 9518        })
 9519        .detach();
 9520    }
 9521
 9522    pub(crate) fn navigate_to_hover_links(
 9523        &mut self,
 9524        kind: Option<GotoDefinitionKind>,
 9525        mut definitions: Vec<HoverLink>,
 9526        split: bool,
 9527        cx: &mut ViewContext<Editor>,
 9528    ) -> Task<Result<Navigated>> {
 9529        // If there is one definition, just open it directly
 9530        if definitions.len() == 1 {
 9531            let definition = definitions.pop().unwrap();
 9532
 9533            enum TargetTaskResult {
 9534                Location(Option<Location>),
 9535                AlreadyNavigated,
 9536            }
 9537
 9538            let target_task = match definition {
 9539                HoverLink::Text(link) => {
 9540                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9541                }
 9542                HoverLink::InlayHint(lsp_location, server_id) => {
 9543                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9544                    cx.background_executor().spawn(async move {
 9545                        let location = computation.await?;
 9546                        Ok(TargetTaskResult::Location(location))
 9547                    })
 9548                }
 9549                HoverLink::Url(url) => {
 9550                    cx.open_url(&url);
 9551                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9552                }
 9553                HoverLink::File(path) => {
 9554                    if let Some(workspace) = self.workspace() {
 9555                        cx.spawn(|_, mut cx| async move {
 9556                            workspace
 9557                                .update(&mut cx, |workspace, cx| {
 9558                                    workspace.open_resolved_path(path, cx)
 9559                                })?
 9560                                .await
 9561                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9562                        })
 9563                    } else {
 9564                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9565                    }
 9566                }
 9567            };
 9568            cx.spawn(|editor, mut cx| async move {
 9569                let target = match target_task.await.context("target resolution task")? {
 9570                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9571                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9572                    TargetTaskResult::Location(Some(target)) => target,
 9573                };
 9574
 9575                editor.update(&mut cx, |editor, cx| {
 9576                    let Some(workspace) = editor.workspace() else {
 9577                        return Navigated::No;
 9578                    };
 9579                    let pane = workspace.read(cx).active_pane().clone();
 9580
 9581                    let range = target.range.to_offset(target.buffer.read(cx));
 9582                    let range = editor.range_for_match(&range);
 9583
 9584                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9585                        let buffer = target.buffer.read(cx);
 9586                        let range = check_multiline_range(buffer, range);
 9587                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9588                            s.select_ranges([range]);
 9589                        });
 9590                    } else {
 9591                        cx.window_context().defer(move |cx| {
 9592                            let target_editor: View<Self> =
 9593                                workspace.update(cx, |workspace, cx| {
 9594                                    let pane = if split {
 9595                                        workspace.adjacent_pane(cx)
 9596                                    } else {
 9597                                        workspace.active_pane().clone()
 9598                                    };
 9599
 9600                                    workspace.open_project_item(
 9601                                        pane,
 9602                                        target.buffer.clone(),
 9603                                        true,
 9604                                        true,
 9605                                        cx,
 9606                                    )
 9607                                });
 9608                            target_editor.update(cx, |target_editor, cx| {
 9609                                // When selecting a definition in a different buffer, disable the nav history
 9610                                // to avoid creating a history entry at the previous cursor location.
 9611                                pane.update(cx, |pane, _| pane.disable_history());
 9612                                let buffer = target.buffer.read(cx);
 9613                                let range = check_multiline_range(buffer, range);
 9614                                target_editor.change_selections(
 9615                                    Some(Autoscroll::focused()),
 9616                                    cx,
 9617                                    |s| {
 9618                                        s.select_ranges([range]);
 9619                                    },
 9620                                );
 9621                                pane.update(cx, |pane, _| pane.enable_history());
 9622                            });
 9623                        });
 9624                    }
 9625                    Navigated::Yes
 9626                })
 9627            })
 9628        } else if !definitions.is_empty() {
 9629            cx.spawn(|editor, mut cx| async move {
 9630                let (title, location_tasks, workspace) = editor
 9631                    .update(&mut cx, |editor, cx| {
 9632                        let tab_kind = match kind {
 9633                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9634                            _ => "Definitions",
 9635                        };
 9636                        let title = definitions
 9637                            .iter()
 9638                            .find_map(|definition| match definition {
 9639                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9640                                    let buffer = origin.buffer.read(cx);
 9641                                    format!(
 9642                                        "{} for {}",
 9643                                        tab_kind,
 9644                                        buffer
 9645                                            .text_for_range(origin.range.clone())
 9646                                            .collect::<String>()
 9647                                    )
 9648                                }),
 9649                                HoverLink::InlayHint(_, _) => None,
 9650                                HoverLink::Url(_) => None,
 9651                                HoverLink::File(_) => None,
 9652                            })
 9653                            .unwrap_or(tab_kind.to_string());
 9654                        let location_tasks = definitions
 9655                            .into_iter()
 9656                            .map(|definition| match definition {
 9657                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9658                                HoverLink::InlayHint(lsp_location, server_id) => {
 9659                                    editor.compute_target_location(lsp_location, server_id, cx)
 9660                                }
 9661                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9662                                HoverLink::File(_) => Task::ready(Ok(None)),
 9663                            })
 9664                            .collect::<Vec<_>>();
 9665                        (title, location_tasks, editor.workspace().clone())
 9666                    })
 9667                    .context("location tasks preparation")?;
 9668
 9669                let locations = future::join_all(location_tasks)
 9670                    .await
 9671                    .into_iter()
 9672                    .filter_map(|location| location.transpose())
 9673                    .collect::<Result<_>>()
 9674                    .context("location tasks")?;
 9675
 9676                let Some(workspace) = workspace else {
 9677                    return Ok(Navigated::No);
 9678                };
 9679                let opened = workspace
 9680                    .update(&mut cx, |workspace, cx| {
 9681                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9682                    })
 9683                    .ok();
 9684
 9685                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9686            })
 9687        } else {
 9688            Task::ready(Ok(Navigated::No))
 9689        }
 9690    }
 9691
 9692    fn compute_target_location(
 9693        &self,
 9694        lsp_location: lsp::Location,
 9695        server_id: LanguageServerId,
 9696        cx: &mut ViewContext<Self>,
 9697    ) -> Task<anyhow::Result<Option<Location>>> {
 9698        let Some(project) = self.project.clone() else {
 9699            return Task::ready(Ok(None));
 9700        };
 9701
 9702        cx.spawn(move |editor, mut cx| async move {
 9703            let location_task = editor.update(&mut cx, |_, cx| {
 9704                project.update(cx, |project, cx| {
 9705                    let language_server_name = project
 9706                        .language_server_statuses(cx)
 9707                        .find(|(id, _)| server_id == *id)
 9708                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9709                    language_server_name.map(|language_server_name| {
 9710                        project.open_local_buffer_via_lsp(
 9711                            lsp_location.uri.clone(),
 9712                            server_id,
 9713                            language_server_name,
 9714                            cx,
 9715                        )
 9716                    })
 9717                })
 9718            })?;
 9719            let location = match location_task {
 9720                Some(task) => Some({
 9721                    let target_buffer_handle = task.await.context("open local buffer")?;
 9722                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9723                        let target_start = target_buffer
 9724                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9725                        let target_end = target_buffer
 9726                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9727                        target_buffer.anchor_after(target_start)
 9728                            ..target_buffer.anchor_before(target_end)
 9729                    })?;
 9730                    Location {
 9731                        buffer: target_buffer_handle,
 9732                        range,
 9733                    }
 9734                }),
 9735                None => None,
 9736            };
 9737            Ok(location)
 9738        })
 9739    }
 9740
 9741    pub fn find_all_references(
 9742        &mut self,
 9743        _: &FindAllReferences,
 9744        cx: &mut ViewContext<Self>,
 9745    ) -> Option<Task<Result<Navigated>>> {
 9746        let selection = self.selections.newest::<usize>(cx);
 9747        let multi_buffer = self.buffer.read(cx);
 9748        let head = selection.head();
 9749
 9750        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9751        let head_anchor = multi_buffer_snapshot.anchor_at(
 9752            head,
 9753            if head < selection.tail() {
 9754                Bias::Right
 9755            } else {
 9756                Bias::Left
 9757            },
 9758        );
 9759
 9760        match self
 9761            .find_all_references_task_sources
 9762            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9763        {
 9764            Ok(_) => {
 9765                log::info!(
 9766                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9767                );
 9768                return None;
 9769            }
 9770            Err(i) => {
 9771                self.find_all_references_task_sources.insert(i, head_anchor);
 9772            }
 9773        }
 9774
 9775        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9776        let workspace = self.workspace()?;
 9777        let project = workspace.read(cx).project().clone();
 9778        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9779        Some(cx.spawn(|editor, mut cx| async move {
 9780            let _cleanup = defer({
 9781                let mut cx = cx.clone();
 9782                move || {
 9783                    let _ = editor.update(&mut cx, |editor, _| {
 9784                        if let Ok(i) =
 9785                            editor
 9786                                .find_all_references_task_sources
 9787                                .binary_search_by(|anchor| {
 9788                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9789                                })
 9790                        {
 9791                            editor.find_all_references_task_sources.remove(i);
 9792                        }
 9793                    });
 9794                }
 9795            });
 9796
 9797            let locations = references.await?;
 9798            if locations.is_empty() {
 9799                return anyhow::Ok(Navigated::No);
 9800            }
 9801
 9802            workspace.update(&mut cx, |workspace, cx| {
 9803                let title = locations
 9804                    .first()
 9805                    .as_ref()
 9806                    .map(|location| {
 9807                        let buffer = location.buffer.read(cx);
 9808                        format!(
 9809                            "References to `{}`",
 9810                            buffer
 9811                                .text_for_range(location.range.clone())
 9812                                .collect::<String>()
 9813                        )
 9814                    })
 9815                    .unwrap();
 9816                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9817                Navigated::Yes
 9818            })
 9819        }))
 9820    }
 9821
 9822    /// Opens a multibuffer with the given project locations in it
 9823    pub fn open_locations_in_multibuffer(
 9824        workspace: &mut Workspace,
 9825        mut locations: Vec<Location>,
 9826        title: String,
 9827        split: bool,
 9828        cx: &mut ViewContext<Workspace>,
 9829    ) {
 9830        // If there are multiple definitions, open them in a multibuffer
 9831        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9832        let mut locations = locations.into_iter().peekable();
 9833        let mut ranges_to_highlight = Vec::new();
 9834        let capability = workspace.project().read(cx).capability();
 9835
 9836        let excerpt_buffer = cx.new_model(|cx| {
 9837            let mut multibuffer = MultiBuffer::new(capability);
 9838            while let Some(location) = locations.next() {
 9839                let buffer = location.buffer.read(cx);
 9840                let mut ranges_for_buffer = Vec::new();
 9841                let range = location.range.to_offset(buffer);
 9842                ranges_for_buffer.push(range.clone());
 9843
 9844                while let Some(next_location) = locations.peek() {
 9845                    if next_location.buffer == location.buffer {
 9846                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9847                        locations.next();
 9848                    } else {
 9849                        break;
 9850                    }
 9851                }
 9852
 9853                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9854                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9855                    location.buffer.clone(),
 9856                    ranges_for_buffer,
 9857                    DEFAULT_MULTIBUFFER_CONTEXT,
 9858                    cx,
 9859                ))
 9860            }
 9861
 9862            multibuffer.with_title(title)
 9863        });
 9864
 9865        let editor = cx.new_view(|cx| {
 9866            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9867        });
 9868        editor.update(cx, |editor, cx| {
 9869            if let Some(first_range) = ranges_to_highlight.first() {
 9870                editor.change_selections(None, cx, |selections| {
 9871                    selections.clear_disjoint();
 9872                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9873                });
 9874            }
 9875            editor.highlight_background::<Self>(
 9876                &ranges_to_highlight,
 9877                |theme| theme.editor_highlighted_line_background,
 9878                cx,
 9879            );
 9880            editor.register_buffers_with_language_servers(cx);
 9881        });
 9882
 9883        let item = Box::new(editor);
 9884        let item_id = item.item_id();
 9885
 9886        if split {
 9887            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9888        } else {
 9889            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9890                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9891                    pane.close_current_preview_item(cx)
 9892                } else {
 9893                    None
 9894                }
 9895            });
 9896            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9897        }
 9898        workspace.active_pane().update(cx, |pane, cx| {
 9899            pane.set_preview_item_id(Some(item_id), cx);
 9900        });
 9901    }
 9902
 9903    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9904        use language::ToOffset as _;
 9905
 9906        let provider = self.semantics_provider.clone()?;
 9907        let selection = self.selections.newest_anchor().clone();
 9908        let (cursor_buffer, cursor_buffer_position) = self
 9909            .buffer
 9910            .read(cx)
 9911            .text_anchor_for_position(selection.head(), cx)?;
 9912        let (tail_buffer, cursor_buffer_position_end) = self
 9913            .buffer
 9914            .read(cx)
 9915            .text_anchor_for_position(selection.tail(), cx)?;
 9916        if tail_buffer != cursor_buffer {
 9917            return None;
 9918        }
 9919
 9920        let snapshot = cursor_buffer.read(cx).snapshot();
 9921        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9922        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9923        let prepare_rename = provider
 9924            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9925            .unwrap_or_else(|| Task::ready(Ok(None)));
 9926        drop(snapshot);
 9927
 9928        Some(cx.spawn(|this, mut cx| async move {
 9929            let rename_range = if let Some(range) = prepare_rename.await? {
 9930                Some(range)
 9931            } else {
 9932                this.update(&mut cx, |this, cx| {
 9933                    let buffer = this.buffer.read(cx).snapshot(cx);
 9934                    let mut buffer_highlights = this
 9935                        .document_highlights_for_position(selection.head(), &buffer)
 9936                        .filter(|highlight| {
 9937                            highlight.start.excerpt_id == selection.head().excerpt_id
 9938                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9939                        });
 9940                    buffer_highlights
 9941                        .next()
 9942                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9943                })?
 9944            };
 9945            if let Some(rename_range) = rename_range {
 9946                this.update(&mut cx, |this, cx| {
 9947                    let snapshot = cursor_buffer.read(cx).snapshot();
 9948                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9949                    let cursor_offset_in_rename_range =
 9950                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9951                    let cursor_offset_in_rename_range_end =
 9952                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9953
 9954                    this.take_rename(false, cx);
 9955                    let buffer = this.buffer.read(cx).read(cx);
 9956                    let cursor_offset = selection.head().to_offset(&buffer);
 9957                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9958                    let rename_end = rename_start + rename_buffer_range.len();
 9959                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9960                    let mut old_highlight_id = None;
 9961                    let old_name: Arc<str> = buffer
 9962                        .chunks(rename_start..rename_end, true)
 9963                        .map(|chunk| {
 9964                            if old_highlight_id.is_none() {
 9965                                old_highlight_id = chunk.syntax_highlight_id;
 9966                            }
 9967                            chunk.text
 9968                        })
 9969                        .collect::<String>()
 9970                        .into();
 9971
 9972                    drop(buffer);
 9973
 9974                    // Position the selection in the rename editor so that it matches the current selection.
 9975                    this.show_local_selections = false;
 9976                    let rename_editor = cx.new_view(|cx| {
 9977                        let mut editor = Editor::single_line(cx);
 9978                        editor.buffer.update(cx, |buffer, cx| {
 9979                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9980                        });
 9981                        let rename_selection_range = match cursor_offset_in_rename_range
 9982                            .cmp(&cursor_offset_in_rename_range_end)
 9983                        {
 9984                            Ordering::Equal => {
 9985                                editor.select_all(&SelectAll, cx);
 9986                                return editor;
 9987                            }
 9988                            Ordering::Less => {
 9989                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9990                            }
 9991                            Ordering::Greater => {
 9992                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9993                            }
 9994                        };
 9995                        if rename_selection_range.end > old_name.len() {
 9996                            editor.select_all(&SelectAll, cx);
 9997                        } else {
 9998                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9999                                s.select_ranges([rename_selection_range]);
10000                            });
10001                        }
10002                        editor
10003                    });
10004                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10005                        if e == &EditorEvent::Focused {
10006                            cx.emit(EditorEvent::FocusedIn)
10007                        }
10008                    })
10009                    .detach();
10010
10011                    let write_highlights =
10012                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10013                    let read_highlights =
10014                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10015                    let ranges = write_highlights
10016                        .iter()
10017                        .flat_map(|(_, ranges)| ranges.iter())
10018                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10019                        .cloned()
10020                        .collect();
10021
10022                    this.highlight_text::<Rename>(
10023                        ranges,
10024                        HighlightStyle {
10025                            fade_out: Some(0.6),
10026                            ..Default::default()
10027                        },
10028                        cx,
10029                    );
10030                    let rename_focus_handle = rename_editor.focus_handle(cx);
10031                    cx.focus(&rename_focus_handle);
10032                    let block_id = this.insert_blocks(
10033                        [BlockProperties {
10034                            style: BlockStyle::Flex,
10035                            placement: BlockPlacement::Below(range.start),
10036                            height: 1,
10037                            render: Arc::new({
10038                                let rename_editor = rename_editor.clone();
10039                                move |cx: &mut BlockContext| {
10040                                    let mut text_style = cx.editor_style.text.clone();
10041                                    if let Some(highlight_style) = old_highlight_id
10042                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10043                                    {
10044                                        text_style = text_style.highlight(highlight_style);
10045                                    }
10046                                    div()
10047                                        .block_mouse_down()
10048                                        .pl(cx.anchor_x)
10049                                        .child(EditorElement::new(
10050                                            &rename_editor,
10051                                            EditorStyle {
10052                                                background: cx.theme().system().transparent,
10053                                                local_player: cx.editor_style.local_player,
10054                                                text: text_style,
10055                                                scrollbar_width: cx.editor_style.scrollbar_width,
10056                                                syntax: cx.editor_style.syntax.clone(),
10057                                                status: cx.editor_style.status.clone(),
10058                                                inlay_hints_style: HighlightStyle {
10059                                                    font_weight: Some(FontWeight::BOLD),
10060                                                    ..make_inlay_hints_style(cx)
10061                                                },
10062                                                inline_completion_styles: make_suggestion_styles(
10063                                                    cx,
10064                                                ),
10065                                                ..EditorStyle::default()
10066                                            },
10067                                        ))
10068                                        .into_any_element()
10069                                }
10070                            }),
10071                            priority: 0,
10072                        }],
10073                        Some(Autoscroll::fit()),
10074                        cx,
10075                    )[0];
10076                    this.pending_rename = Some(RenameState {
10077                        range,
10078                        old_name,
10079                        editor: rename_editor,
10080                        block_id,
10081                    });
10082                })?;
10083            }
10084
10085            Ok(())
10086        }))
10087    }
10088
10089    pub fn confirm_rename(
10090        &mut self,
10091        _: &ConfirmRename,
10092        cx: &mut ViewContext<Self>,
10093    ) -> Option<Task<Result<()>>> {
10094        let rename = self.take_rename(false, cx)?;
10095        let workspace = self.workspace()?.downgrade();
10096        let (buffer, start) = self
10097            .buffer
10098            .read(cx)
10099            .text_anchor_for_position(rename.range.start, cx)?;
10100        let (end_buffer, _) = self
10101            .buffer
10102            .read(cx)
10103            .text_anchor_for_position(rename.range.end, cx)?;
10104        if buffer != end_buffer {
10105            return None;
10106        }
10107
10108        let old_name = rename.old_name;
10109        let new_name = rename.editor.read(cx).text(cx);
10110
10111        let rename = self.semantics_provider.as_ref()?.perform_rename(
10112            &buffer,
10113            start,
10114            new_name.clone(),
10115            cx,
10116        )?;
10117
10118        Some(cx.spawn(|editor, mut cx| async move {
10119            let project_transaction = rename.await?;
10120            Self::open_project_transaction(
10121                &editor,
10122                workspace,
10123                project_transaction,
10124                format!("Rename: {}{}", old_name, new_name),
10125                cx.clone(),
10126            )
10127            .await?;
10128
10129            editor.update(&mut cx, |editor, cx| {
10130                editor.refresh_document_highlights(cx);
10131            })?;
10132            Ok(())
10133        }))
10134    }
10135
10136    fn take_rename(
10137        &mut self,
10138        moving_cursor: bool,
10139        cx: &mut ViewContext<Self>,
10140    ) -> Option<RenameState> {
10141        let rename = self.pending_rename.take()?;
10142        if rename.editor.focus_handle(cx).is_focused(cx) {
10143            cx.focus(&self.focus_handle);
10144        }
10145
10146        self.remove_blocks(
10147            [rename.block_id].into_iter().collect(),
10148            Some(Autoscroll::fit()),
10149            cx,
10150        );
10151        self.clear_highlights::<Rename>(cx);
10152        self.show_local_selections = true;
10153
10154        if moving_cursor {
10155            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10156                editor.selections.newest::<usize>(cx).head()
10157            });
10158
10159            // Update the selection to match the position of the selection inside
10160            // the rename editor.
10161            let snapshot = self.buffer.read(cx).read(cx);
10162            let rename_range = rename.range.to_offset(&snapshot);
10163            let cursor_in_editor = snapshot
10164                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10165                .min(rename_range.end);
10166            drop(snapshot);
10167
10168            self.change_selections(None, cx, |s| {
10169                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10170            });
10171        } else {
10172            self.refresh_document_highlights(cx);
10173        }
10174
10175        Some(rename)
10176    }
10177
10178    pub fn pending_rename(&self) -> Option<&RenameState> {
10179        self.pending_rename.as_ref()
10180    }
10181
10182    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10183        let project = match &self.project {
10184            Some(project) => project.clone(),
10185            None => return None,
10186        };
10187
10188        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10189    }
10190
10191    fn format_selections(
10192        &mut self,
10193        _: &FormatSelections,
10194        cx: &mut ViewContext<Self>,
10195    ) -> Option<Task<Result<()>>> {
10196        let project = match &self.project {
10197            Some(project) => project.clone(),
10198            None => return None,
10199        };
10200
10201        let selections = self
10202            .selections
10203            .all_adjusted(cx)
10204            .into_iter()
10205            .filter(|s| !s.is_empty())
10206            .collect_vec();
10207
10208        Some(self.perform_format(
10209            project,
10210            FormatTrigger::Manual,
10211            FormatTarget::Ranges(selections),
10212            cx,
10213        ))
10214    }
10215
10216    fn perform_format(
10217        &mut self,
10218        project: Model<Project>,
10219        trigger: FormatTrigger,
10220        target: FormatTarget,
10221        cx: &mut ViewContext<Self>,
10222    ) -> Task<Result<()>> {
10223        let buffer = self.buffer().clone();
10224        let mut buffers = buffer.read(cx).all_buffers();
10225        if trigger == FormatTrigger::Save {
10226            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10227        }
10228
10229        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10230        let format = project.update(cx, |project, cx| {
10231            project.format(buffers, true, trigger, target, cx)
10232        });
10233
10234        cx.spawn(|_, mut cx| async move {
10235            let transaction = futures::select_biased! {
10236                () = timeout => {
10237                    log::warn!("timed out waiting for formatting");
10238                    None
10239                }
10240                transaction = format.log_err().fuse() => transaction,
10241            };
10242
10243            buffer
10244                .update(&mut cx, |buffer, cx| {
10245                    if let Some(transaction) = transaction {
10246                        if !buffer.is_singleton() {
10247                            buffer.push_transaction(&transaction.0, cx);
10248                        }
10249                    }
10250
10251                    cx.notify();
10252                })
10253                .ok();
10254
10255            Ok(())
10256        })
10257    }
10258
10259    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10260        if let Some(project) = self.project.clone() {
10261            self.buffer.update(cx, |multi_buffer, cx| {
10262                project.update(cx, |project, cx| {
10263                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10264                });
10265            })
10266        }
10267    }
10268
10269    fn cancel_language_server_work(
10270        &mut self,
10271        _: &actions::CancelLanguageServerWork,
10272        cx: &mut ViewContext<Self>,
10273    ) {
10274        if let Some(project) = self.project.clone() {
10275            self.buffer.update(cx, |multi_buffer, cx| {
10276                project.update(cx, |project, cx| {
10277                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10278                });
10279            })
10280        }
10281    }
10282
10283    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10284        cx.show_character_palette();
10285    }
10286
10287    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10288        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10289            let buffer = self.buffer.read(cx).snapshot(cx);
10290            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10291            let is_valid = buffer
10292                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10293                .any(|entry| {
10294                    entry.diagnostic.is_primary
10295                        && !entry.range.is_empty()
10296                        && entry.range.start == primary_range_start
10297                        && entry.diagnostic.message == active_diagnostics.primary_message
10298                });
10299
10300            if is_valid != active_diagnostics.is_valid {
10301                active_diagnostics.is_valid = is_valid;
10302                let mut new_styles = HashMap::default();
10303                for (block_id, diagnostic) in &active_diagnostics.blocks {
10304                    new_styles.insert(
10305                        *block_id,
10306                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10307                    );
10308                }
10309                self.display_map.update(cx, |display_map, _cx| {
10310                    display_map.replace_blocks(new_styles)
10311                });
10312            }
10313        }
10314    }
10315
10316    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10317        self.dismiss_diagnostics(cx);
10318        let snapshot = self.snapshot(cx);
10319        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10320            let buffer = self.buffer.read(cx).snapshot(cx);
10321
10322            let mut primary_range = None;
10323            let mut primary_message = None;
10324            let mut group_end = Point::zero();
10325            let diagnostic_group = buffer
10326                .diagnostic_group::<MultiBufferPoint>(group_id)
10327                .filter_map(|entry| {
10328                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10329                        && (entry.range.start.row == entry.range.end.row
10330                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10331                    {
10332                        return None;
10333                    }
10334                    if entry.range.end > group_end {
10335                        group_end = entry.range.end;
10336                    }
10337                    if entry.diagnostic.is_primary {
10338                        primary_range = Some(entry.range.clone());
10339                        primary_message = Some(entry.diagnostic.message.clone());
10340                    }
10341                    Some(entry)
10342                })
10343                .collect::<Vec<_>>();
10344            let primary_range = primary_range?;
10345            let primary_message = primary_message?;
10346            let primary_range =
10347                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10348
10349            let blocks = display_map
10350                .insert_blocks(
10351                    diagnostic_group.iter().map(|entry| {
10352                        let diagnostic = entry.diagnostic.clone();
10353                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10354                        BlockProperties {
10355                            style: BlockStyle::Fixed,
10356                            placement: BlockPlacement::Below(
10357                                buffer.anchor_after(entry.range.start),
10358                            ),
10359                            height: message_height,
10360                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10361                            priority: 0,
10362                        }
10363                    }),
10364                    cx,
10365                )
10366                .into_iter()
10367                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10368                .collect();
10369
10370            Some(ActiveDiagnosticGroup {
10371                primary_range,
10372                primary_message,
10373                group_id,
10374                blocks,
10375                is_valid: true,
10376            })
10377        });
10378        self.active_diagnostics.is_some()
10379    }
10380
10381    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10382        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10383            self.display_map.update(cx, |display_map, cx| {
10384                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10385            });
10386            cx.notify();
10387        }
10388    }
10389
10390    pub fn set_selections_from_remote(
10391        &mut self,
10392        selections: Vec<Selection<Anchor>>,
10393        pending_selection: Option<Selection<Anchor>>,
10394        cx: &mut ViewContext<Self>,
10395    ) {
10396        let old_cursor_position = self.selections.newest_anchor().head();
10397        self.selections.change_with(cx, |s| {
10398            s.select_anchors(selections);
10399            if let Some(pending_selection) = pending_selection {
10400                s.set_pending(pending_selection, SelectMode::Character);
10401            } else {
10402                s.clear_pending();
10403            }
10404        });
10405        self.selections_did_change(false, &old_cursor_position, true, cx);
10406    }
10407
10408    fn push_to_selection_history(&mut self) {
10409        self.selection_history.push(SelectionHistoryEntry {
10410            selections: self.selections.disjoint_anchors(),
10411            select_next_state: self.select_next_state.clone(),
10412            select_prev_state: self.select_prev_state.clone(),
10413            add_selections_state: self.add_selections_state.clone(),
10414        });
10415    }
10416
10417    pub fn transact(
10418        &mut self,
10419        cx: &mut ViewContext<Self>,
10420        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10421    ) -> Option<TransactionId> {
10422        self.start_transaction_at(Instant::now(), cx);
10423        update(self, cx);
10424        self.end_transaction_at(Instant::now(), cx)
10425    }
10426
10427    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10428        self.end_selection(cx);
10429        if let Some(tx_id) = self
10430            .buffer
10431            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10432        {
10433            self.selection_history
10434                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10435            cx.emit(EditorEvent::TransactionBegun {
10436                transaction_id: tx_id,
10437            })
10438        }
10439    }
10440
10441    pub fn end_transaction_at(
10442        &mut self,
10443        now: Instant,
10444        cx: &mut ViewContext<Self>,
10445    ) -> Option<TransactionId> {
10446        if let Some(transaction_id) = self
10447            .buffer
10448            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10449        {
10450            if let Some((_, end_selections)) =
10451                self.selection_history.transaction_mut(transaction_id)
10452            {
10453                *end_selections = Some(self.selections.disjoint_anchors());
10454            } else {
10455                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10456            }
10457
10458            cx.emit(EditorEvent::Edited { transaction_id });
10459            Some(transaction_id)
10460        } else {
10461            None
10462        }
10463    }
10464
10465    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10466        if self.is_singleton(cx) {
10467            let selection = self.selections.newest::<Point>(cx);
10468
10469            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10470            let range = if selection.is_empty() {
10471                let point = selection.head().to_display_point(&display_map);
10472                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10473                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10474                    .to_point(&display_map);
10475                start..end
10476            } else {
10477                selection.range()
10478            };
10479            if display_map.folds_in_range(range).next().is_some() {
10480                self.unfold_lines(&Default::default(), cx)
10481            } else {
10482                self.fold(&Default::default(), cx)
10483            }
10484        } else {
10485            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10486            let mut toggled_buffers = HashSet::default();
10487            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10488                self.selections
10489                    .disjoint_anchors()
10490                    .into_iter()
10491                    .map(|selection| selection.range()),
10492            ) {
10493                let buffer_id = buffer_snapshot.remote_id();
10494                if toggled_buffers.insert(buffer_id) {
10495                    if self.buffer_folded(buffer_id, cx) {
10496                        self.unfold_buffer(buffer_id, cx);
10497                    } else {
10498                        self.fold_buffer(buffer_id, cx);
10499                    }
10500                }
10501            }
10502        }
10503    }
10504
10505    pub fn toggle_fold_recursive(
10506        &mut self,
10507        _: &actions::ToggleFoldRecursive,
10508        cx: &mut ViewContext<Self>,
10509    ) {
10510        let selection = self.selections.newest::<Point>(cx);
10511
10512        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10513        let range = if selection.is_empty() {
10514            let point = selection.head().to_display_point(&display_map);
10515            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10516            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10517                .to_point(&display_map);
10518            start..end
10519        } else {
10520            selection.range()
10521        };
10522        if display_map.folds_in_range(range).next().is_some() {
10523            self.unfold_recursive(&Default::default(), cx)
10524        } else {
10525            self.fold_recursive(&Default::default(), cx)
10526        }
10527    }
10528
10529    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10530        if self.is_singleton(cx) {
10531            let mut to_fold = Vec::new();
10532            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10533            let selections = self.selections.all_adjusted(cx);
10534
10535            for selection in selections {
10536                let range = selection.range().sorted();
10537                let buffer_start_row = range.start.row;
10538
10539                if range.start.row != range.end.row {
10540                    let mut found = false;
10541                    let mut row = range.start.row;
10542                    while row <= range.end.row {
10543                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10544                        {
10545                            found = true;
10546                            row = crease.range().end.row + 1;
10547                            to_fold.push(crease);
10548                        } else {
10549                            row += 1
10550                        }
10551                    }
10552                    if found {
10553                        continue;
10554                    }
10555                }
10556
10557                for row in (0..=range.start.row).rev() {
10558                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10559                        if crease.range().end.row >= buffer_start_row {
10560                            to_fold.push(crease);
10561                            if row <= range.start.row {
10562                                break;
10563                            }
10564                        }
10565                    }
10566                }
10567            }
10568
10569            self.fold_creases(to_fold, true, cx);
10570        } else {
10571            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10572            let mut folded_buffers = HashSet::default();
10573            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10574                self.selections
10575                    .disjoint_anchors()
10576                    .into_iter()
10577                    .map(|selection| selection.range()),
10578            ) {
10579                let buffer_id = buffer_snapshot.remote_id();
10580                if folded_buffers.insert(buffer_id) {
10581                    self.fold_buffer(buffer_id, cx);
10582                }
10583            }
10584        }
10585    }
10586
10587    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10588        if !self.buffer.read(cx).is_singleton() {
10589            return;
10590        }
10591
10592        let fold_at_level = fold_at.level;
10593        let snapshot = self.buffer.read(cx).snapshot(cx);
10594        let mut to_fold = Vec::new();
10595        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10596
10597        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10598            while start_row < end_row {
10599                match self
10600                    .snapshot(cx)
10601                    .crease_for_buffer_row(MultiBufferRow(start_row))
10602                {
10603                    Some(crease) => {
10604                        let nested_start_row = crease.range().start.row + 1;
10605                        let nested_end_row = crease.range().end.row;
10606
10607                        if current_level < fold_at_level {
10608                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10609                        } else if current_level == fold_at_level {
10610                            to_fold.push(crease);
10611                        }
10612
10613                        start_row = nested_end_row + 1;
10614                    }
10615                    None => start_row += 1,
10616                }
10617            }
10618        }
10619
10620        self.fold_creases(to_fold, true, cx);
10621    }
10622
10623    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10624        if self.buffer.read(cx).is_singleton() {
10625            let mut fold_ranges = Vec::new();
10626            let snapshot = self.buffer.read(cx).snapshot(cx);
10627
10628            for row in 0..snapshot.max_row().0 {
10629                if let Some(foldable_range) =
10630                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10631                {
10632                    fold_ranges.push(foldable_range);
10633                }
10634            }
10635
10636            self.fold_creases(fold_ranges, true, cx);
10637        } else {
10638            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10639                editor
10640                    .update(&mut cx, |editor, cx| {
10641                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10642                            editor.fold_buffer(buffer_id, cx);
10643                        }
10644                    })
10645                    .ok();
10646            });
10647        }
10648    }
10649
10650    pub fn fold_function_bodies(
10651        &mut self,
10652        _: &actions::FoldFunctionBodies,
10653        cx: &mut ViewContext<Self>,
10654    ) {
10655        let snapshot = self.buffer.read(cx).snapshot(cx);
10656        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10657            return;
10658        };
10659        let creases = buffer
10660            .function_body_fold_ranges(0..buffer.len())
10661            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10662            .collect();
10663
10664        self.fold_creases(creases, true, cx);
10665    }
10666
10667    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10668        let mut to_fold = Vec::new();
10669        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10670        let selections = self.selections.all_adjusted(cx);
10671
10672        for selection in selections {
10673            let range = selection.range().sorted();
10674            let buffer_start_row = range.start.row;
10675
10676            if range.start.row != range.end.row {
10677                let mut found = false;
10678                for row in range.start.row..=range.end.row {
10679                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10680                        found = true;
10681                        to_fold.push(crease);
10682                    }
10683                }
10684                if found {
10685                    continue;
10686                }
10687            }
10688
10689            for row in (0..=range.start.row).rev() {
10690                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10691                    if crease.range().end.row >= buffer_start_row {
10692                        to_fold.push(crease);
10693                    } else {
10694                        break;
10695                    }
10696                }
10697            }
10698        }
10699
10700        self.fold_creases(to_fold, true, cx);
10701    }
10702
10703    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10704        let buffer_row = fold_at.buffer_row;
10705        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10706
10707        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10708            let autoscroll = self
10709                .selections
10710                .all::<Point>(cx)
10711                .iter()
10712                .any(|selection| crease.range().overlaps(&selection.range()));
10713
10714            self.fold_creases(vec![crease], autoscroll, cx);
10715        }
10716    }
10717
10718    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10719        if self.is_singleton(cx) {
10720            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10721            let buffer = &display_map.buffer_snapshot;
10722            let selections = self.selections.all::<Point>(cx);
10723            let ranges = selections
10724                .iter()
10725                .map(|s| {
10726                    let range = s.display_range(&display_map).sorted();
10727                    let mut start = range.start.to_point(&display_map);
10728                    let mut end = range.end.to_point(&display_map);
10729                    start.column = 0;
10730                    end.column = buffer.line_len(MultiBufferRow(end.row));
10731                    start..end
10732                })
10733                .collect::<Vec<_>>();
10734
10735            self.unfold_ranges(&ranges, true, true, cx);
10736        } else {
10737            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10738            let mut unfolded_buffers = HashSet::default();
10739            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10740                self.selections
10741                    .disjoint_anchors()
10742                    .into_iter()
10743                    .map(|selection| selection.range()),
10744            ) {
10745                let buffer_id = buffer_snapshot.remote_id();
10746                if unfolded_buffers.insert(buffer_id) {
10747                    self.unfold_buffer(buffer_id, cx);
10748                }
10749            }
10750        }
10751    }
10752
10753    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10754        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10755        let selections = self.selections.all::<Point>(cx);
10756        let ranges = selections
10757            .iter()
10758            .map(|s| {
10759                let mut range = s.display_range(&display_map).sorted();
10760                *range.start.column_mut() = 0;
10761                *range.end.column_mut() = display_map.line_len(range.end.row());
10762                let start = range.start.to_point(&display_map);
10763                let end = range.end.to_point(&display_map);
10764                start..end
10765            })
10766            .collect::<Vec<_>>();
10767
10768        self.unfold_ranges(&ranges, true, true, cx);
10769    }
10770
10771    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10772        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10773
10774        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10775            ..Point::new(
10776                unfold_at.buffer_row.0,
10777                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10778            );
10779
10780        let autoscroll = self
10781            .selections
10782            .all::<Point>(cx)
10783            .iter()
10784            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10785
10786        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10787    }
10788
10789    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10790        if self.buffer.read(cx).is_singleton() {
10791            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10792            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10793        } else {
10794            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10795                editor
10796                    .update(&mut cx, |editor, cx| {
10797                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10798                            editor.unfold_buffer(buffer_id, cx);
10799                        }
10800                    })
10801                    .ok();
10802            });
10803        }
10804    }
10805
10806    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10807        let selections = self.selections.all::<Point>(cx);
10808        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10809        let line_mode = self.selections.line_mode;
10810        let ranges = selections
10811            .into_iter()
10812            .map(|s| {
10813                if line_mode {
10814                    let start = Point::new(s.start.row, 0);
10815                    let end = Point::new(
10816                        s.end.row,
10817                        display_map
10818                            .buffer_snapshot
10819                            .line_len(MultiBufferRow(s.end.row)),
10820                    );
10821                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10822                } else {
10823                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10824                }
10825            })
10826            .collect::<Vec<_>>();
10827        self.fold_creases(ranges, true, cx);
10828    }
10829
10830    pub fn fold_creases<T: ToOffset + Clone>(
10831        &mut self,
10832        creases: Vec<Crease<T>>,
10833        auto_scroll: bool,
10834        cx: &mut ViewContext<Self>,
10835    ) {
10836        if creases.is_empty() {
10837            return;
10838        }
10839
10840        let mut buffers_affected = HashSet::default();
10841        let multi_buffer = self.buffer().read(cx);
10842        for crease in &creases {
10843            if let Some((_, buffer, _)) =
10844                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10845            {
10846                buffers_affected.insert(buffer.read(cx).remote_id());
10847            };
10848        }
10849
10850        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10851
10852        if auto_scroll {
10853            self.request_autoscroll(Autoscroll::fit(), cx);
10854        }
10855
10856        for buffer_id in buffers_affected {
10857            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10858        }
10859
10860        cx.notify();
10861
10862        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10863            // Clear diagnostics block when folding a range that contains it.
10864            let snapshot = self.snapshot(cx);
10865            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10866                drop(snapshot);
10867                self.active_diagnostics = Some(active_diagnostics);
10868                self.dismiss_diagnostics(cx);
10869            } else {
10870                self.active_diagnostics = Some(active_diagnostics);
10871            }
10872        }
10873
10874        self.scrollbar_marker_state.dirty = true;
10875    }
10876
10877    /// Removes any folds whose ranges intersect any of the given ranges.
10878    pub fn unfold_ranges<T: ToOffset + Clone>(
10879        &mut self,
10880        ranges: &[Range<T>],
10881        inclusive: bool,
10882        auto_scroll: bool,
10883        cx: &mut ViewContext<Self>,
10884    ) {
10885        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10886            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10887        });
10888    }
10889
10890    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10891        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10892            return;
10893        }
10894        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10895            return;
10896        };
10897        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10898        self.display_map
10899            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10900        cx.emit(EditorEvent::BufferFoldToggled {
10901            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10902            folded: true,
10903        });
10904        cx.notify();
10905    }
10906
10907    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10908        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10909            return;
10910        }
10911        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10912            return;
10913        };
10914        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10915        self.display_map.update(cx, |display_map, cx| {
10916            display_map.unfold_buffer(buffer_id, cx);
10917        });
10918        cx.emit(EditorEvent::BufferFoldToggled {
10919            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10920            folded: false,
10921        });
10922        cx.notify();
10923    }
10924
10925    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10926        self.display_map.read(cx).buffer_folded(buffer)
10927    }
10928
10929    /// Removes any folds with the given ranges.
10930    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10931        &mut self,
10932        ranges: &[Range<T>],
10933        type_id: TypeId,
10934        auto_scroll: bool,
10935        cx: &mut ViewContext<Self>,
10936    ) {
10937        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10938            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10939        });
10940    }
10941
10942    fn remove_folds_with<T: ToOffset + Clone>(
10943        &mut self,
10944        ranges: &[Range<T>],
10945        auto_scroll: bool,
10946        cx: &mut ViewContext<Self>,
10947        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10948    ) {
10949        if ranges.is_empty() {
10950            return;
10951        }
10952
10953        let mut buffers_affected = HashSet::default();
10954        let multi_buffer = self.buffer().read(cx);
10955        for range in ranges {
10956            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10957                buffers_affected.insert(buffer.read(cx).remote_id());
10958            };
10959        }
10960
10961        self.display_map.update(cx, update);
10962
10963        if auto_scroll {
10964            self.request_autoscroll(Autoscroll::fit(), cx);
10965        }
10966
10967        for buffer_id in buffers_affected {
10968            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10969        }
10970
10971        cx.notify();
10972        self.scrollbar_marker_state.dirty = true;
10973        self.active_indent_guides_state.dirty = true;
10974    }
10975
10976    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10977        self.display_map.read(cx).fold_placeholder.clone()
10978    }
10979
10980    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10981        if hovered != self.gutter_hovered {
10982            self.gutter_hovered = hovered;
10983            cx.notify();
10984        }
10985    }
10986
10987    pub fn insert_blocks(
10988        &mut self,
10989        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10990        autoscroll: Option<Autoscroll>,
10991        cx: &mut ViewContext<Self>,
10992    ) -> Vec<CustomBlockId> {
10993        let blocks = self
10994            .display_map
10995            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10996        if let Some(autoscroll) = autoscroll {
10997            self.request_autoscroll(autoscroll, cx);
10998        }
10999        cx.notify();
11000        blocks
11001    }
11002
11003    pub fn resize_blocks(
11004        &mut self,
11005        heights: HashMap<CustomBlockId, u32>,
11006        autoscroll: Option<Autoscroll>,
11007        cx: &mut ViewContext<Self>,
11008    ) {
11009        self.display_map
11010            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11011        if let Some(autoscroll) = autoscroll {
11012            self.request_autoscroll(autoscroll, cx);
11013        }
11014        cx.notify();
11015    }
11016
11017    pub fn replace_blocks(
11018        &mut self,
11019        renderers: HashMap<CustomBlockId, RenderBlock>,
11020        autoscroll: Option<Autoscroll>,
11021        cx: &mut ViewContext<Self>,
11022    ) {
11023        self.display_map
11024            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11025        if let Some(autoscroll) = autoscroll {
11026            self.request_autoscroll(autoscroll, cx);
11027        }
11028        cx.notify();
11029    }
11030
11031    pub fn remove_blocks(
11032        &mut self,
11033        block_ids: HashSet<CustomBlockId>,
11034        autoscroll: Option<Autoscroll>,
11035        cx: &mut ViewContext<Self>,
11036    ) {
11037        self.display_map.update(cx, |display_map, cx| {
11038            display_map.remove_blocks(block_ids, cx)
11039        });
11040        if let Some(autoscroll) = autoscroll {
11041            self.request_autoscroll(autoscroll, cx);
11042        }
11043        cx.notify();
11044    }
11045
11046    pub fn row_for_block(
11047        &self,
11048        block_id: CustomBlockId,
11049        cx: &mut ViewContext<Self>,
11050    ) -> Option<DisplayRow> {
11051        self.display_map
11052            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11053    }
11054
11055    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11056        self.focused_block = Some(focused_block);
11057    }
11058
11059    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11060        self.focused_block.take()
11061    }
11062
11063    pub fn insert_creases(
11064        &mut self,
11065        creases: impl IntoIterator<Item = Crease<Anchor>>,
11066        cx: &mut ViewContext<Self>,
11067    ) -> Vec<CreaseId> {
11068        self.display_map
11069            .update(cx, |map, cx| map.insert_creases(creases, cx))
11070    }
11071
11072    pub fn remove_creases(
11073        &mut self,
11074        ids: impl IntoIterator<Item = CreaseId>,
11075        cx: &mut ViewContext<Self>,
11076    ) {
11077        self.display_map
11078            .update(cx, |map, cx| map.remove_creases(ids, cx));
11079    }
11080
11081    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11082        self.display_map
11083            .update(cx, |map, cx| map.snapshot(cx))
11084            .longest_row()
11085    }
11086
11087    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11088        self.display_map
11089            .update(cx, |map, cx| map.snapshot(cx))
11090            .max_point()
11091    }
11092
11093    pub fn text(&self, cx: &AppContext) -> String {
11094        self.buffer.read(cx).read(cx).text()
11095    }
11096
11097    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11098        let text = self.text(cx);
11099        let text = text.trim();
11100
11101        if text.is_empty() {
11102            return None;
11103        }
11104
11105        Some(text.to_string())
11106    }
11107
11108    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11109        self.transact(cx, |this, cx| {
11110            this.buffer
11111                .read(cx)
11112                .as_singleton()
11113                .expect("you can only call set_text on editors for singleton buffers")
11114                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11115        });
11116    }
11117
11118    pub fn display_text(&self, cx: &mut AppContext) -> String {
11119        self.display_map
11120            .update(cx, |map, cx| map.snapshot(cx))
11121            .text()
11122    }
11123
11124    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11125        let mut wrap_guides = smallvec::smallvec![];
11126
11127        if self.show_wrap_guides == Some(false) {
11128            return wrap_guides;
11129        }
11130
11131        let settings = self.buffer.read(cx).settings_at(0, cx);
11132        if settings.show_wrap_guides {
11133            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11134                wrap_guides.push((soft_wrap as usize, true));
11135            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11136                wrap_guides.push((soft_wrap as usize, true));
11137            }
11138            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11139        }
11140
11141        wrap_guides
11142    }
11143
11144    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11145        let settings = self.buffer.read(cx).settings_at(0, cx);
11146        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11147        match mode {
11148            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11149                SoftWrap::None
11150            }
11151            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11152            language_settings::SoftWrap::PreferredLineLength => {
11153                SoftWrap::Column(settings.preferred_line_length)
11154            }
11155            language_settings::SoftWrap::Bounded => {
11156                SoftWrap::Bounded(settings.preferred_line_length)
11157            }
11158        }
11159    }
11160
11161    pub fn set_soft_wrap_mode(
11162        &mut self,
11163        mode: language_settings::SoftWrap,
11164        cx: &mut ViewContext<Self>,
11165    ) {
11166        self.soft_wrap_mode_override = Some(mode);
11167        cx.notify();
11168    }
11169
11170    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11171        self.text_style_refinement = Some(style);
11172    }
11173
11174    /// called by the Element so we know what style we were most recently rendered with.
11175    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11176        let rem_size = cx.rem_size();
11177        self.display_map.update(cx, |map, cx| {
11178            map.set_font(
11179                style.text.font(),
11180                style.text.font_size.to_pixels(rem_size),
11181                cx,
11182            )
11183        });
11184        self.style = Some(style);
11185    }
11186
11187    pub fn style(&self) -> Option<&EditorStyle> {
11188        self.style.as_ref()
11189    }
11190
11191    // Called by the element. This method is not designed to be called outside of the editor
11192    // element's layout code because it does not notify when rewrapping is computed synchronously.
11193    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11194        self.display_map
11195            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11196    }
11197
11198    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11199        if self.soft_wrap_mode_override.is_some() {
11200            self.soft_wrap_mode_override.take();
11201        } else {
11202            let soft_wrap = match self.soft_wrap_mode(cx) {
11203                SoftWrap::GitDiff => return,
11204                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11205                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11206                    language_settings::SoftWrap::None
11207                }
11208            };
11209            self.soft_wrap_mode_override = Some(soft_wrap);
11210        }
11211        cx.notify();
11212    }
11213
11214    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11215        let Some(workspace) = self.workspace() else {
11216            return;
11217        };
11218        let fs = workspace.read(cx).app_state().fs.clone();
11219        let current_show = TabBarSettings::get_global(cx).show;
11220        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11221            setting.show = Some(!current_show);
11222        });
11223    }
11224
11225    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11226        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11227            self.buffer
11228                .read(cx)
11229                .settings_at(0, cx)
11230                .indent_guides
11231                .enabled
11232        });
11233        self.show_indent_guides = Some(!currently_enabled);
11234        cx.notify();
11235    }
11236
11237    fn should_show_indent_guides(&self) -> Option<bool> {
11238        self.show_indent_guides
11239    }
11240
11241    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11242        let mut editor_settings = EditorSettings::get_global(cx).clone();
11243        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11244        EditorSettings::override_global(editor_settings, cx);
11245    }
11246
11247    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11248        self.use_relative_line_numbers
11249            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11250    }
11251
11252    pub fn toggle_relative_line_numbers(
11253        &mut self,
11254        _: &ToggleRelativeLineNumbers,
11255        cx: &mut ViewContext<Self>,
11256    ) {
11257        let is_relative = self.should_use_relative_line_numbers(cx);
11258        self.set_relative_line_number(Some(!is_relative), cx)
11259    }
11260
11261    pub fn set_relative_line_number(
11262        &mut self,
11263        is_relative: Option<bool>,
11264        cx: &mut ViewContext<Self>,
11265    ) {
11266        self.use_relative_line_numbers = is_relative;
11267        cx.notify();
11268    }
11269
11270    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11271        self.show_gutter = show_gutter;
11272        cx.notify();
11273    }
11274
11275    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11276        self.show_scrollbars = show_scrollbars;
11277        cx.notify();
11278    }
11279
11280    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11281        self.show_line_numbers = Some(show_line_numbers);
11282        cx.notify();
11283    }
11284
11285    pub fn set_show_git_diff_gutter(
11286        &mut self,
11287        show_git_diff_gutter: bool,
11288        cx: &mut ViewContext<Self>,
11289    ) {
11290        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11291        cx.notify();
11292    }
11293
11294    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11295        self.show_code_actions = Some(show_code_actions);
11296        cx.notify();
11297    }
11298
11299    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11300        self.show_runnables = Some(show_runnables);
11301        cx.notify();
11302    }
11303
11304    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11305        if self.display_map.read(cx).masked != masked {
11306            self.display_map.update(cx, |map, _| map.masked = masked);
11307        }
11308        cx.notify()
11309    }
11310
11311    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11312        self.show_wrap_guides = Some(show_wrap_guides);
11313        cx.notify();
11314    }
11315
11316    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11317        self.show_indent_guides = Some(show_indent_guides);
11318        cx.notify();
11319    }
11320
11321    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11322        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11323            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11324                if let Some(dir) = file.abs_path(cx).parent() {
11325                    return Some(dir.to_owned());
11326                }
11327            }
11328
11329            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11330                return Some(project_path.path.to_path_buf());
11331            }
11332        }
11333
11334        None
11335    }
11336
11337    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11338        self.active_excerpt(cx)?
11339            .1
11340            .read(cx)
11341            .file()
11342            .and_then(|f| f.as_local())
11343    }
11344
11345    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11346        if let Some(target) = self.target_file(cx) {
11347            cx.reveal_path(&target.abs_path(cx));
11348        }
11349    }
11350
11351    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11352        if let Some(file) = self.target_file(cx) {
11353            if let Some(path) = file.abs_path(cx).to_str() {
11354                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11355            }
11356        }
11357    }
11358
11359    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11360        if let Some(file) = self.target_file(cx) {
11361            if let Some(path) = file.path().to_str() {
11362                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11363            }
11364        }
11365    }
11366
11367    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11368        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11369
11370        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11371            self.start_git_blame(true, cx);
11372        }
11373
11374        cx.notify();
11375    }
11376
11377    pub fn toggle_git_blame_inline(
11378        &mut self,
11379        _: &ToggleGitBlameInline,
11380        cx: &mut ViewContext<Self>,
11381    ) {
11382        self.toggle_git_blame_inline_internal(true, cx);
11383        cx.notify();
11384    }
11385
11386    pub fn git_blame_inline_enabled(&self) -> bool {
11387        self.git_blame_inline_enabled
11388    }
11389
11390    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11391        self.show_selection_menu = self
11392            .show_selection_menu
11393            .map(|show_selections_menu| !show_selections_menu)
11394            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11395
11396        cx.notify();
11397    }
11398
11399    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11400        self.show_selection_menu
11401            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11402    }
11403
11404    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11405        if let Some(project) = self.project.as_ref() {
11406            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11407                return;
11408            };
11409
11410            if buffer.read(cx).file().is_none() {
11411                return;
11412            }
11413
11414            let focused = self.focus_handle(cx).contains_focused(cx);
11415
11416            let project = project.clone();
11417            let blame =
11418                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11419            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11420            self.blame = Some(blame);
11421        }
11422    }
11423
11424    fn toggle_git_blame_inline_internal(
11425        &mut self,
11426        user_triggered: bool,
11427        cx: &mut ViewContext<Self>,
11428    ) {
11429        if self.git_blame_inline_enabled {
11430            self.git_blame_inline_enabled = false;
11431            self.show_git_blame_inline = false;
11432            self.show_git_blame_inline_delay_task.take();
11433        } else {
11434            self.git_blame_inline_enabled = true;
11435            self.start_git_blame_inline(user_triggered, cx);
11436        }
11437
11438        cx.notify();
11439    }
11440
11441    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11442        self.start_git_blame(user_triggered, cx);
11443
11444        if ProjectSettings::get_global(cx)
11445            .git
11446            .inline_blame_delay()
11447            .is_some()
11448        {
11449            self.start_inline_blame_timer(cx);
11450        } else {
11451            self.show_git_blame_inline = true
11452        }
11453    }
11454
11455    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11456        self.blame.as_ref()
11457    }
11458
11459    pub fn show_git_blame_gutter(&self) -> bool {
11460        self.show_git_blame_gutter
11461    }
11462
11463    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11464        self.show_git_blame_gutter && self.has_blame_entries(cx)
11465    }
11466
11467    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11468        self.show_git_blame_inline
11469            && self.focus_handle.is_focused(cx)
11470            && !self.newest_selection_head_on_empty_line(cx)
11471            && self.has_blame_entries(cx)
11472    }
11473
11474    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11475        self.blame()
11476            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11477    }
11478
11479    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11480        let cursor_anchor = self.selections.newest_anchor().head();
11481
11482        let snapshot = self.buffer.read(cx).snapshot(cx);
11483        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11484
11485        snapshot.line_len(buffer_row) == 0
11486    }
11487
11488    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11489        let buffer_and_selection = maybe!({
11490            let selection = self.selections.newest::<Point>(cx);
11491            let selection_range = selection.range();
11492
11493            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11494                (buffer, selection_range.start.row..selection_range.end.row)
11495            } else {
11496                let buffer_ranges = self
11497                    .buffer()
11498                    .read(cx)
11499                    .range_to_buffer_ranges(selection_range, cx);
11500
11501                let (buffer, range, _) = if selection.reversed {
11502                    buffer_ranges.first()
11503                } else {
11504                    buffer_ranges.last()
11505                }?;
11506
11507                let snapshot = buffer.read(cx).snapshot();
11508                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11509                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11510                (buffer.clone(), selection)
11511            };
11512
11513            Some((buffer, selection))
11514        });
11515
11516        let Some((buffer, selection)) = buffer_and_selection else {
11517            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11518        };
11519
11520        let Some(project) = self.project.as_ref() else {
11521            return Task::ready(Err(anyhow!("editor does not have project")));
11522        };
11523
11524        project.update(cx, |project, cx| {
11525            project.get_permalink_to_line(&buffer, selection, cx)
11526        })
11527    }
11528
11529    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11530        let permalink_task = self.get_permalink_to_line(cx);
11531        let workspace = self.workspace();
11532
11533        cx.spawn(|_, mut cx| async move {
11534            match permalink_task.await {
11535                Ok(permalink) => {
11536                    cx.update(|cx| {
11537                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11538                    })
11539                    .ok();
11540                }
11541                Err(err) => {
11542                    let message = format!("Failed to copy permalink: {err}");
11543
11544                    Err::<(), anyhow::Error>(err).log_err();
11545
11546                    if let Some(workspace) = workspace {
11547                        workspace
11548                            .update(&mut cx, |workspace, cx| {
11549                                struct CopyPermalinkToLine;
11550
11551                                workspace.show_toast(
11552                                    Toast::new(
11553                                        NotificationId::unique::<CopyPermalinkToLine>(),
11554                                        message,
11555                                    ),
11556                                    cx,
11557                                )
11558                            })
11559                            .ok();
11560                    }
11561                }
11562            }
11563        })
11564        .detach();
11565    }
11566
11567    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11568        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11569        if let Some(file) = self.target_file(cx) {
11570            if let Some(path) = file.path().to_str() {
11571                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11572            }
11573        }
11574    }
11575
11576    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11577        let permalink_task = self.get_permalink_to_line(cx);
11578        let workspace = self.workspace();
11579
11580        cx.spawn(|_, mut cx| async move {
11581            match permalink_task.await {
11582                Ok(permalink) => {
11583                    cx.update(|cx| {
11584                        cx.open_url(permalink.as_ref());
11585                    })
11586                    .ok();
11587                }
11588                Err(err) => {
11589                    let message = format!("Failed to open permalink: {err}");
11590
11591                    Err::<(), anyhow::Error>(err).log_err();
11592
11593                    if let Some(workspace) = workspace {
11594                        workspace
11595                            .update(&mut cx, |workspace, cx| {
11596                                struct OpenPermalinkToLine;
11597
11598                                workspace.show_toast(
11599                                    Toast::new(
11600                                        NotificationId::unique::<OpenPermalinkToLine>(),
11601                                        message,
11602                                    ),
11603                                    cx,
11604                                )
11605                            })
11606                            .ok();
11607                    }
11608                }
11609            }
11610        })
11611        .detach();
11612    }
11613
11614    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11615        self.insert_uuid(UuidVersion::V4, cx);
11616    }
11617
11618    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11619        self.insert_uuid(UuidVersion::V7, cx);
11620    }
11621
11622    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11623        self.transact(cx, |this, cx| {
11624            let edits = this
11625                .selections
11626                .all::<Point>(cx)
11627                .into_iter()
11628                .map(|selection| {
11629                    let uuid = match version {
11630                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11631                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11632                    };
11633
11634                    (selection.range(), uuid.to_string())
11635                });
11636            this.edit(edits, cx);
11637            this.refresh_inline_completion(true, false, cx);
11638        });
11639    }
11640
11641    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11642    /// last highlight added will be used.
11643    ///
11644    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11645    pub fn highlight_rows<T: 'static>(
11646        &mut self,
11647        range: Range<Anchor>,
11648        color: Hsla,
11649        should_autoscroll: bool,
11650        cx: &mut ViewContext<Self>,
11651    ) {
11652        let snapshot = self.buffer().read(cx).snapshot(cx);
11653        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11654        let ix = row_highlights.binary_search_by(|highlight| {
11655            Ordering::Equal
11656                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11657                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11658        });
11659
11660        if let Err(mut ix) = ix {
11661            let index = post_inc(&mut self.highlight_order);
11662
11663            // If this range intersects with the preceding highlight, then merge it with
11664            // the preceding highlight. Otherwise insert a new highlight.
11665            let mut merged = false;
11666            if ix > 0 {
11667                let prev_highlight = &mut row_highlights[ix - 1];
11668                if prev_highlight
11669                    .range
11670                    .end
11671                    .cmp(&range.start, &snapshot)
11672                    .is_ge()
11673                {
11674                    ix -= 1;
11675                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11676                        prev_highlight.range.end = range.end;
11677                    }
11678                    merged = true;
11679                    prev_highlight.index = index;
11680                    prev_highlight.color = color;
11681                    prev_highlight.should_autoscroll = should_autoscroll;
11682                }
11683            }
11684
11685            if !merged {
11686                row_highlights.insert(
11687                    ix,
11688                    RowHighlight {
11689                        range: range.clone(),
11690                        index,
11691                        color,
11692                        should_autoscroll,
11693                    },
11694                );
11695            }
11696
11697            // If any of the following highlights intersect with this one, merge them.
11698            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11699                let highlight = &row_highlights[ix];
11700                if next_highlight
11701                    .range
11702                    .start
11703                    .cmp(&highlight.range.end, &snapshot)
11704                    .is_le()
11705                {
11706                    if next_highlight
11707                        .range
11708                        .end
11709                        .cmp(&highlight.range.end, &snapshot)
11710                        .is_gt()
11711                    {
11712                        row_highlights[ix].range.end = next_highlight.range.end;
11713                    }
11714                    row_highlights.remove(ix + 1);
11715                } else {
11716                    break;
11717                }
11718            }
11719        }
11720    }
11721
11722    /// Remove any highlighted row ranges of the given type that intersect the
11723    /// given ranges.
11724    pub fn remove_highlighted_rows<T: 'static>(
11725        &mut self,
11726        ranges_to_remove: Vec<Range<Anchor>>,
11727        cx: &mut ViewContext<Self>,
11728    ) {
11729        let snapshot = self.buffer().read(cx).snapshot(cx);
11730        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11731        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11732        row_highlights.retain(|highlight| {
11733            while let Some(range_to_remove) = ranges_to_remove.peek() {
11734                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11735                    Ordering::Less | Ordering::Equal => {
11736                        ranges_to_remove.next();
11737                    }
11738                    Ordering::Greater => {
11739                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11740                            Ordering::Less | Ordering::Equal => {
11741                                return false;
11742                            }
11743                            Ordering::Greater => break,
11744                        }
11745                    }
11746                }
11747            }
11748
11749            true
11750        })
11751    }
11752
11753    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11754    pub fn clear_row_highlights<T: 'static>(&mut self) {
11755        self.highlighted_rows.remove(&TypeId::of::<T>());
11756    }
11757
11758    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11759    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11760        self.highlighted_rows
11761            .get(&TypeId::of::<T>())
11762            .map_or(&[] as &[_], |vec| vec.as_slice())
11763            .iter()
11764            .map(|highlight| (highlight.range.clone(), highlight.color))
11765    }
11766
11767    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11768    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11769    /// Allows to ignore certain kinds of highlights.
11770    pub fn highlighted_display_rows(
11771        &mut self,
11772        cx: &mut WindowContext,
11773    ) -> BTreeMap<DisplayRow, Hsla> {
11774        let snapshot = self.snapshot(cx);
11775        let mut used_highlight_orders = HashMap::default();
11776        self.highlighted_rows
11777            .iter()
11778            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11779            .fold(
11780                BTreeMap::<DisplayRow, Hsla>::new(),
11781                |mut unique_rows, highlight| {
11782                    let start = highlight.range.start.to_display_point(&snapshot);
11783                    let end = highlight.range.end.to_display_point(&snapshot);
11784                    let start_row = start.row().0;
11785                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11786                        && end.column() == 0
11787                    {
11788                        end.row().0.saturating_sub(1)
11789                    } else {
11790                        end.row().0
11791                    };
11792                    for row in start_row..=end_row {
11793                        let used_index =
11794                            used_highlight_orders.entry(row).or_insert(highlight.index);
11795                        if highlight.index >= *used_index {
11796                            *used_index = highlight.index;
11797                            unique_rows.insert(DisplayRow(row), highlight.color);
11798                        }
11799                    }
11800                    unique_rows
11801                },
11802            )
11803    }
11804
11805    pub fn highlighted_display_row_for_autoscroll(
11806        &self,
11807        snapshot: &DisplaySnapshot,
11808    ) -> Option<DisplayRow> {
11809        self.highlighted_rows
11810            .values()
11811            .flat_map(|highlighted_rows| highlighted_rows.iter())
11812            .filter_map(|highlight| {
11813                if highlight.should_autoscroll {
11814                    Some(highlight.range.start.to_display_point(snapshot).row())
11815                } else {
11816                    None
11817                }
11818            })
11819            .min()
11820    }
11821
11822    pub fn set_search_within_ranges(
11823        &mut self,
11824        ranges: &[Range<Anchor>],
11825        cx: &mut ViewContext<Self>,
11826    ) {
11827        self.highlight_background::<SearchWithinRange>(
11828            ranges,
11829            |colors| colors.editor_document_highlight_read_background,
11830            cx,
11831        )
11832    }
11833
11834    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11835        self.breadcrumb_header = Some(new_header);
11836    }
11837
11838    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11839        self.clear_background_highlights::<SearchWithinRange>(cx);
11840    }
11841
11842    pub fn highlight_background<T: 'static>(
11843        &mut self,
11844        ranges: &[Range<Anchor>],
11845        color_fetcher: fn(&ThemeColors) -> Hsla,
11846        cx: &mut ViewContext<Self>,
11847    ) {
11848        self.background_highlights
11849            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11850        self.scrollbar_marker_state.dirty = true;
11851        cx.notify();
11852    }
11853
11854    pub fn clear_background_highlights<T: 'static>(
11855        &mut self,
11856        cx: &mut ViewContext<Self>,
11857    ) -> Option<BackgroundHighlight> {
11858        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11859        if !text_highlights.1.is_empty() {
11860            self.scrollbar_marker_state.dirty = true;
11861            cx.notify();
11862        }
11863        Some(text_highlights)
11864    }
11865
11866    pub fn highlight_gutter<T: 'static>(
11867        &mut self,
11868        ranges: &[Range<Anchor>],
11869        color_fetcher: fn(&AppContext) -> Hsla,
11870        cx: &mut ViewContext<Self>,
11871    ) {
11872        self.gutter_highlights
11873            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11874        cx.notify();
11875    }
11876
11877    pub fn clear_gutter_highlights<T: 'static>(
11878        &mut self,
11879        cx: &mut ViewContext<Self>,
11880    ) -> Option<GutterHighlight> {
11881        cx.notify();
11882        self.gutter_highlights.remove(&TypeId::of::<T>())
11883    }
11884
11885    #[cfg(feature = "test-support")]
11886    pub fn all_text_background_highlights(
11887        &mut self,
11888        cx: &mut ViewContext<Self>,
11889    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11890        let snapshot = self.snapshot(cx);
11891        let buffer = &snapshot.buffer_snapshot;
11892        let start = buffer.anchor_before(0);
11893        let end = buffer.anchor_after(buffer.len());
11894        let theme = cx.theme().colors();
11895        self.background_highlights_in_range(start..end, &snapshot, theme)
11896    }
11897
11898    #[cfg(feature = "test-support")]
11899    pub fn search_background_highlights(
11900        &mut self,
11901        cx: &mut ViewContext<Self>,
11902    ) -> Vec<Range<Point>> {
11903        let snapshot = self.buffer().read(cx).snapshot(cx);
11904
11905        let highlights = self
11906            .background_highlights
11907            .get(&TypeId::of::<items::BufferSearchHighlights>());
11908
11909        if let Some((_color, ranges)) = highlights {
11910            ranges
11911                .iter()
11912                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11913                .collect_vec()
11914        } else {
11915            vec![]
11916        }
11917    }
11918
11919    fn document_highlights_for_position<'a>(
11920        &'a self,
11921        position: Anchor,
11922        buffer: &'a MultiBufferSnapshot,
11923    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11924        let read_highlights = self
11925            .background_highlights
11926            .get(&TypeId::of::<DocumentHighlightRead>())
11927            .map(|h| &h.1);
11928        let write_highlights = self
11929            .background_highlights
11930            .get(&TypeId::of::<DocumentHighlightWrite>())
11931            .map(|h| &h.1);
11932        let left_position = position.bias_left(buffer);
11933        let right_position = position.bias_right(buffer);
11934        read_highlights
11935            .into_iter()
11936            .chain(write_highlights)
11937            .flat_map(move |ranges| {
11938                let start_ix = match ranges.binary_search_by(|probe| {
11939                    let cmp = probe.end.cmp(&left_position, buffer);
11940                    if cmp.is_ge() {
11941                        Ordering::Greater
11942                    } else {
11943                        Ordering::Less
11944                    }
11945                }) {
11946                    Ok(i) | Err(i) => i,
11947                };
11948
11949                ranges[start_ix..]
11950                    .iter()
11951                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11952            })
11953    }
11954
11955    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11956        self.background_highlights
11957            .get(&TypeId::of::<T>())
11958            .map_or(false, |(_, highlights)| !highlights.is_empty())
11959    }
11960
11961    pub fn background_highlights_in_range(
11962        &self,
11963        search_range: Range<Anchor>,
11964        display_snapshot: &DisplaySnapshot,
11965        theme: &ThemeColors,
11966    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11967        let mut results = Vec::new();
11968        for (color_fetcher, ranges) in self.background_highlights.values() {
11969            let color = color_fetcher(theme);
11970            let start_ix = match ranges.binary_search_by(|probe| {
11971                let cmp = probe
11972                    .end
11973                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11974                if cmp.is_gt() {
11975                    Ordering::Greater
11976                } else {
11977                    Ordering::Less
11978                }
11979            }) {
11980                Ok(i) | Err(i) => i,
11981            };
11982            for range in &ranges[start_ix..] {
11983                if range
11984                    .start
11985                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11986                    .is_ge()
11987                {
11988                    break;
11989                }
11990
11991                let start = range.start.to_display_point(display_snapshot);
11992                let end = range.end.to_display_point(display_snapshot);
11993                results.push((start..end, color))
11994            }
11995        }
11996        results
11997    }
11998
11999    pub fn background_highlight_row_ranges<T: 'static>(
12000        &self,
12001        search_range: Range<Anchor>,
12002        display_snapshot: &DisplaySnapshot,
12003        count: usize,
12004    ) -> Vec<RangeInclusive<DisplayPoint>> {
12005        let mut results = Vec::new();
12006        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12007            return vec![];
12008        };
12009
12010        let start_ix = match ranges.binary_search_by(|probe| {
12011            let cmp = probe
12012                .end
12013                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12014            if cmp.is_gt() {
12015                Ordering::Greater
12016            } else {
12017                Ordering::Less
12018            }
12019        }) {
12020            Ok(i) | Err(i) => i,
12021        };
12022        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12023            if let (Some(start_display), Some(end_display)) = (start, end) {
12024                results.push(
12025                    start_display.to_display_point(display_snapshot)
12026                        ..=end_display.to_display_point(display_snapshot),
12027                );
12028            }
12029        };
12030        let mut start_row: Option<Point> = None;
12031        let mut end_row: Option<Point> = None;
12032        if ranges.len() > count {
12033            return Vec::new();
12034        }
12035        for range in &ranges[start_ix..] {
12036            if range
12037                .start
12038                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12039                .is_ge()
12040            {
12041                break;
12042            }
12043            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12044            if let Some(current_row) = &end_row {
12045                if end.row == current_row.row {
12046                    continue;
12047                }
12048            }
12049            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12050            if start_row.is_none() {
12051                assert_eq!(end_row, None);
12052                start_row = Some(start);
12053                end_row = Some(end);
12054                continue;
12055            }
12056            if let Some(current_end) = end_row.as_mut() {
12057                if start.row > current_end.row + 1 {
12058                    push_region(start_row, end_row);
12059                    start_row = Some(start);
12060                    end_row = Some(end);
12061                } else {
12062                    // Merge two hunks.
12063                    *current_end = end;
12064                }
12065            } else {
12066                unreachable!();
12067            }
12068        }
12069        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12070        push_region(start_row, end_row);
12071        results
12072    }
12073
12074    pub fn gutter_highlights_in_range(
12075        &self,
12076        search_range: Range<Anchor>,
12077        display_snapshot: &DisplaySnapshot,
12078        cx: &AppContext,
12079    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12080        let mut results = Vec::new();
12081        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12082            let color = color_fetcher(cx);
12083            let start_ix = match ranges.binary_search_by(|probe| {
12084                let cmp = probe
12085                    .end
12086                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12087                if cmp.is_gt() {
12088                    Ordering::Greater
12089                } else {
12090                    Ordering::Less
12091                }
12092            }) {
12093                Ok(i) | Err(i) => i,
12094            };
12095            for range in &ranges[start_ix..] {
12096                if range
12097                    .start
12098                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12099                    .is_ge()
12100                {
12101                    break;
12102                }
12103
12104                let start = range.start.to_display_point(display_snapshot);
12105                let end = range.end.to_display_point(display_snapshot);
12106                results.push((start..end, color))
12107            }
12108        }
12109        results
12110    }
12111
12112    /// Get the text ranges corresponding to the redaction query
12113    pub fn redacted_ranges(
12114        &self,
12115        search_range: Range<Anchor>,
12116        display_snapshot: &DisplaySnapshot,
12117        cx: &WindowContext,
12118    ) -> Vec<Range<DisplayPoint>> {
12119        display_snapshot
12120            .buffer_snapshot
12121            .redacted_ranges(search_range, |file| {
12122                if let Some(file) = file {
12123                    file.is_private()
12124                        && EditorSettings::get(
12125                            Some(SettingsLocation {
12126                                worktree_id: file.worktree_id(cx),
12127                                path: file.path().as_ref(),
12128                            }),
12129                            cx,
12130                        )
12131                        .redact_private_values
12132                } else {
12133                    false
12134                }
12135            })
12136            .map(|range| {
12137                range.start.to_display_point(display_snapshot)
12138                    ..range.end.to_display_point(display_snapshot)
12139            })
12140            .collect()
12141    }
12142
12143    pub fn highlight_text<T: 'static>(
12144        &mut self,
12145        ranges: Vec<Range<Anchor>>,
12146        style: HighlightStyle,
12147        cx: &mut ViewContext<Self>,
12148    ) {
12149        self.display_map.update(cx, |map, _| {
12150            map.highlight_text(TypeId::of::<T>(), ranges, style)
12151        });
12152        cx.notify();
12153    }
12154
12155    pub(crate) fn highlight_inlays<T: 'static>(
12156        &mut self,
12157        highlights: Vec<InlayHighlight>,
12158        style: HighlightStyle,
12159        cx: &mut ViewContext<Self>,
12160    ) {
12161        self.display_map.update(cx, |map, _| {
12162            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12163        });
12164        cx.notify();
12165    }
12166
12167    pub fn text_highlights<'a, T: 'static>(
12168        &'a self,
12169        cx: &'a AppContext,
12170    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12171        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12172    }
12173
12174    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12175        let cleared = self
12176            .display_map
12177            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12178        if cleared {
12179            cx.notify();
12180        }
12181    }
12182
12183    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12184        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12185            && self.focus_handle.is_focused(cx)
12186    }
12187
12188    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12189        self.show_cursor_when_unfocused = is_enabled;
12190        cx.notify();
12191    }
12192
12193    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12194        self.project
12195            .as_ref()
12196            .map(|project| project.read(cx).lsp_store())
12197    }
12198
12199    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12200        cx.notify();
12201    }
12202
12203    fn on_buffer_event(
12204        &mut self,
12205        multibuffer: Model<MultiBuffer>,
12206        event: &multi_buffer::Event,
12207        cx: &mut ViewContext<Self>,
12208    ) {
12209        match event {
12210            multi_buffer::Event::Edited {
12211                singleton_buffer_edited,
12212                edited_buffer: buffer_edited,
12213            } => {
12214                self.scrollbar_marker_state.dirty = true;
12215                self.active_indent_guides_state.dirty = true;
12216                self.refresh_active_diagnostics(cx);
12217                self.refresh_code_actions(cx);
12218                if self.has_active_inline_completion() {
12219                    self.update_visible_inline_completion(cx);
12220                }
12221                if let Some(buffer) = buffer_edited {
12222                    let buffer_id = buffer.read(cx).remote_id();
12223                    if !self.registered_buffers.contains_key(&buffer_id) {
12224                        if let Some(lsp_store) = self.lsp_store(cx) {
12225                            lsp_store.update(cx, |lsp_store, cx| {
12226                                self.registered_buffers.insert(
12227                                    buffer_id,
12228                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12229                                );
12230                            })
12231                        }
12232                    }
12233                }
12234                cx.emit(EditorEvent::BufferEdited);
12235                cx.emit(SearchEvent::MatchesInvalidated);
12236                if *singleton_buffer_edited {
12237                    if let Some(project) = &self.project {
12238                        let project = project.read(cx);
12239                        #[allow(clippy::mutable_key_type)]
12240                        let languages_affected = multibuffer
12241                            .read(cx)
12242                            .all_buffers()
12243                            .into_iter()
12244                            .filter_map(|buffer| {
12245                                let buffer = buffer.read(cx);
12246                                let language = buffer.language()?;
12247                                if project.is_local()
12248                                    && project
12249                                        .language_servers_for_local_buffer(buffer, cx)
12250                                        .count()
12251                                        == 0
12252                                {
12253                                    None
12254                                } else {
12255                                    Some(language)
12256                                }
12257                            })
12258                            .cloned()
12259                            .collect::<HashSet<_>>();
12260                        if !languages_affected.is_empty() {
12261                            self.refresh_inlay_hints(
12262                                InlayHintRefreshReason::BufferEdited(languages_affected),
12263                                cx,
12264                            );
12265                        }
12266                    }
12267                }
12268
12269                let Some(project) = &self.project else { return };
12270                let (telemetry, is_via_ssh) = {
12271                    let project = project.read(cx);
12272                    let telemetry = project.client().telemetry().clone();
12273                    let is_via_ssh = project.is_via_ssh();
12274                    (telemetry, is_via_ssh)
12275                };
12276                refresh_linked_ranges(self, cx);
12277                telemetry.log_edit_event("editor", is_via_ssh);
12278            }
12279            multi_buffer::Event::ExcerptsAdded {
12280                buffer,
12281                predecessor,
12282                excerpts,
12283            } => {
12284                self.tasks_update_task = Some(self.refresh_runnables(cx));
12285                let buffer_id = buffer.read(cx).remote_id();
12286                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12287                    if let Some(project) = &self.project {
12288                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12289                    }
12290                }
12291                cx.emit(EditorEvent::ExcerptsAdded {
12292                    buffer: buffer.clone(),
12293                    predecessor: *predecessor,
12294                    excerpts: excerpts.clone(),
12295                });
12296                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12297            }
12298            multi_buffer::Event::ExcerptsRemoved { ids } => {
12299                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12300                let buffer = self.buffer.read(cx);
12301                self.registered_buffers
12302                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12303                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12304            }
12305            multi_buffer::Event::ExcerptsEdited { ids } => {
12306                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12307            }
12308            multi_buffer::Event::ExcerptsExpanded { ids } => {
12309                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12310            }
12311            multi_buffer::Event::Reparsed(buffer_id) => {
12312                self.tasks_update_task = Some(self.refresh_runnables(cx));
12313
12314                cx.emit(EditorEvent::Reparsed(*buffer_id));
12315            }
12316            multi_buffer::Event::LanguageChanged(buffer_id) => {
12317                linked_editing_ranges::refresh_linked_ranges(self, cx);
12318                cx.emit(EditorEvent::Reparsed(*buffer_id));
12319                cx.notify();
12320            }
12321            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12322            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12323            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12324                cx.emit(EditorEvent::TitleChanged)
12325            }
12326            // multi_buffer::Event::DiffBaseChanged => {
12327            //     self.scrollbar_marker_state.dirty = true;
12328            //     cx.emit(EditorEvent::DiffBaseChanged);
12329            //     cx.notify();
12330            // }
12331            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12332            multi_buffer::Event::DiagnosticsUpdated => {
12333                self.refresh_active_diagnostics(cx);
12334                self.scrollbar_marker_state.dirty = true;
12335                cx.notify();
12336            }
12337            _ => {}
12338        };
12339    }
12340
12341    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12342        cx.notify();
12343    }
12344
12345    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12346        self.tasks_update_task = Some(self.refresh_runnables(cx));
12347        self.refresh_inline_completion(true, false, cx);
12348        self.refresh_inlay_hints(
12349            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12350                self.selections.newest_anchor().head(),
12351                &self.buffer.read(cx).snapshot(cx),
12352                cx,
12353            )),
12354            cx,
12355        );
12356
12357        let old_cursor_shape = self.cursor_shape;
12358
12359        {
12360            let editor_settings = EditorSettings::get_global(cx);
12361            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12362            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12363            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12364        }
12365
12366        if old_cursor_shape != self.cursor_shape {
12367            cx.emit(EditorEvent::CursorShapeChanged);
12368        }
12369
12370        let project_settings = ProjectSettings::get_global(cx);
12371        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12372
12373        if self.mode == EditorMode::Full {
12374            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12375            if self.git_blame_inline_enabled != inline_blame_enabled {
12376                self.toggle_git_blame_inline_internal(false, cx);
12377            }
12378        }
12379
12380        cx.notify();
12381    }
12382
12383    pub fn set_searchable(&mut self, searchable: bool) {
12384        self.searchable = searchable;
12385    }
12386
12387    pub fn searchable(&self) -> bool {
12388        self.searchable
12389    }
12390
12391    fn open_proposed_changes_editor(
12392        &mut self,
12393        _: &OpenProposedChangesEditor,
12394        cx: &mut ViewContext<Self>,
12395    ) {
12396        let Some(workspace) = self.workspace() else {
12397            cx.propagate();
12398            return;
12399        };
12400
12401        let selections = self.selections.all::<usize>(cx);
12402        let buffer = self.buffer.read(cx);
12403        let mut new_selections_by_buffer = HashMap::default();
12404        for selection in selections {
12405            for (buffer, range, _) in
12406                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12407            {
12408                let mut range = range.to_point(buffer.read(cx));
12409                range.start.column = 0;
12410                range.end.column = buffer.read(cx).line_len(range.end.row);
12411                new_selections_by_buffer
12412                    .entry(buffer)
12413                    .or_insert(Vec::new())
12414                    .push(range)
12415            }
12416        }
12417
12418        let proposed_changes_buffers = new_selections_by_buffer
12419            .into_iter()
12420            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12421            .collect::<Vec<_>>();
12422        let proposed_changes_editor = cx.new_view(|cx| {
12423            ProposedChangesEditor::new(
12424                "Proposed changes",
12425                proposed_changes_buffers,
12426                self.project.clone(),
12427                cx,
12428            )
12429        });
12430
12431        cx.window_context().defer(move |cx| {
12432            workspace.update(cx, |workspace, cx| {
12433                workspace.active_pane().update(cx, |pane, cx| {
12434                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12435                });
12436            });
12437        });
12438    }
12439
12440    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12441        self.open_excerpts_common(None, true, cx)
12442    }
12443
12444    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12445        self.open_excerpts_common(None, false, cx)
12446    }
12447
12448    fn open_excerpts_common(
12449        &mut self,
12450        jump_data: Option<JumpData>,
12451        split: bool,
12452        cx: &mut ViewContext<Self>,
12453    ) {
12454        let Some(workspace) = self.workspace() else {
12455            cx.propagate();
12456            return;
12457        };
12458
12459        if self.buffer.read(cx).is_singleton() {
12460            cx.propagate();
12461            return;
12462        }
12463
12464        let mut new_selections_by_buffer = HashMap::default();
12465        match &jump_data {
12466            Some(JumpData::MultiBufferPoint {
12467                excerpt_id,
12468                position,
12469                anchor,
12470                line_offset_from_top,
12471            }) => {
12472                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12473                if let Some(buffer) = multi_buffer_snapshot
12474                    .buffer_id_for_excerpt(*excerpt_id)
12475                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12476                {
12477                    let buffer_snapshot = buffer.read(cx).snapshot();
12478                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12479                        language::ToPoint::to_point(anchor, &buffer_snapshot)
12480                    } else {
12481                        buffer_snapshot.clip_point(*position, Bias::Left)
12482                    };
12483                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12484                    new_selections_by_buffer.insert(
12485                        buffer,
12486                        (
12487                            vec![jump_to_offset..jump_to_offset],
12488                            Some(*line_offset_from_top),
12489                        ),
12490                    );
12491                }
12492            }
12493            Some(JumpData::MultiBufferRow {
12494                row,
12495                line_offset_from_top,
12496            }) => {
12497                let point = MultiBufferPoint::new(row.0, 0);
12498                if let Some((buffer, buffer_point, _)) =
12499                    self.buffer.read(cx).point_to_buffer_point(point, cx)
12500                {
12501                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12502                    new_selections_by_buffer
12503                        .entry(buffer)
12504                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
12505                        .0
12506                        .push(buffer_offset..buffer_offset)
12507                }
12508            }
12509            None => {
12510                let selections = self.selections.all::<usize>(cx);
12511                let buffer = self.buffer.read(cx);
12512                for selection in selections {
12513                    for (mut buffer_handle, mut range, _) in
12514                        buffer.range_to_buffer_ranges(selection.range(), cx)
12515                    {
12516                        // When editing branch buffers, jump to the corresponding location
12517                        // in their base buffer.
12518                        let buffer = buffer_handle.read(cx);
12519                        if let Some(base_buffer) = buffer.base_buffer() {
12520                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12521                            buffer_handle = base_buffer;
12522                        }
12523
12524                        if selection.reversed {
12525                            mem::swap(&mut range.start, &mut range.end);
12526                        }
12527                        new_selections_by_buffer
12528                            .entry(buffer_handle)
12529                            .or_insert((Vec::new(), None))
12530                            .0
12531                            .push(range)
12532                    }
12533                }
12534            }
12535        }
12536
12537        if new_selections_by_buffer.is_empty() {
12538            return;
12539        }
12540
12541        // We defer the pane interaction because we ourselves are a workspace item
12542        // and activating a new item causes the pane to call a method on us reentrantly,
12543        // which panics if we're on the stack.
12544        cx.window_context().defer(move |cx| {
12545            workspace.update(cx, |workspace, cx| {
12546                let pane = if split {
12547                    workspace.adjacent_pane(cx)
12548                } else {
12549                    workspace.active_pane().clone()
12550                };
12551
12552                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12553                    let editor = buffer
12554                        .read(cx)
12555                        .file()
12556                        .is_none()
12557                        .then(|| {
12558                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12559                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12560                            // Instead, we try to activate the existing editor in the pane first.
12561                            let (editor, pane_item_index) =
12562                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12563                                    let editor = item.downcast::<Editor>()?;
12564                                    let singleton_buffer =
12565                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12566                                    if singleton_buffer == buffer {
12567                                        Some((editor, i))
12568                                    } else {
12569                                        None
12570                                    }
12571                                })?;
12572                            pane.update(cx, |pane, cx| {
12573                                pane.activate_item(pane_item_index, true, true, cx)
12574                            });
12575                            Some(editor)
12576                        })
12577                        .flatten()
12578                        .unwrap_or_else(|| {
12579                            workspace.open_project_item::<Self>(
12580                                pane.clone(),
12581                                buffer,
12582                                true,
12583                                true,
12584                                cx,
12585                            )
12586                        });
12587
12588                    editor.update(cx, |editor, cx| {
12589                        let autoscroll = match scroll_offset {
12590                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12591                            None => Autoscroll::newest(),
12592                        };
12593                        let nav_history = editor.nav_history.take();
12594                        editor.change_selections(Some(autoscroll), cx, |s| {
12595                            s.select_ranges(ranges);
12596                        });
12597                        editor.nav_history = nav_history;
12598                    });
12599                }
12600            })
12601        });
12602    }
12603
12604    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12605        let snapshot = self.buffer.read(cx).read(cx);
12606        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12607        Some(
12608            ranges
12609                .iter()
12610                .map(move |range| {
12611                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12612                })
12613                .collect(),
12614        )
12615    }
12616
12617    fn selection_replacement_ranges(
12618        &self,
12619        range: Range<OffsetUtf16>,
12620        cx: &mut AppContext,
12621    ) -> Vec<Range<OffsetUtf16>> {
12622        let selections = self.selections.all::<OffsetUtf16>(cx);
12623        let newest_selection = selections
12624            .iter()
12625            .max_by_key(|selection| selection.id)
12626            .unwrap();
12627        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12628        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12629        let snapshot = self.buffer.read(cx).read(cx);
12630        selections
12631            .into_iter()
12632            .map(|mut selection| {
12633                selection.start.0 =
12634                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12635                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12636                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12637                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12638            })
12639            .collect()
12640    }
12641
12642    fn report_editor_event(
12643        &self,
12644        event_type: &'static str,
12645        file_extension: Option<String>,
12646        cx: &AppContext,
12647    ) {
12648        if cfg!(any(test, feature = "test-support")) {
12649            return;
12650        }
12651
12652        let Some(project) = &self.project else { return };
12653
12654        // If None, we are in a file without an extension
12655        let file = self
12656            .buffer
12657            .read(cx)
12658            .as_singleton()
12659            .and_then(|b| b.read(cx).file());
12660        let file_extension = file_extension.or(file
12661            .as_ref()
12662            .and_then(|file| Path::new(file.file_name(cx)).extension())
12663            .and_then(|e| e.to_str())
12664            .map(|a| a.to_string()));
12665
12666        let vim_mode = cx
12667            .global::<SettingsStore>()
12668            .raw_user_settings()
12669            .get("vim_mode")
12670            == Some(&serde_json::Value::Bool(true));
12671
12672        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12673            == language::language_settings::InlineCompletionProvider::Copilot;
12674        let copilot_enabled_for_language = self
12675            .buffer
12676            .read(cx)
12677            .settings_at(0, cx)
12678            .show_inline_completions;
12679
12680        let project = project.read(cx);
12681        telemetry::event!(
12682            event_type,
12683            file_extension,
12684            vim_mode,
12685            copilot_enabled,
12686            copilot_enabled_for_language,
12687            is_via_ssh = project.is_via_ssh(),
12688        );
12689    }
12690
12691    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12692    /// with each line being an array of {text, highlight} objects.
12693    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12694        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12695            return;
12696        };
12697
12698        #[derive(Serialize)]
12699        struct Chunk<'a> {
12700            text: String,
12701            highlight: Option<&'a str>,
12702        }
12703
12704        let snapshot = buffer.read(cx).snapshot();
12705        let range = self
12706            .selected_text_range(false, cx)
12707            .and_then(|selection| {
12708                if selection.range.is_empty() {
12709                    None
12710                } else {
12711                    Some(selection.range)
12712                }
12713            })
12714            .unwrap_or_else(|| 0..snapshot.len());
12715
12716        let chunks = snapshot.chunks(range, true);
12717        let mut lines = Vec::new();
12718        let mut line: VecDeque<Chunk> = VecDeque::new();
12719
12720        let Some(style) = self.style.as_ref() else {
12721            return;
12722        };
12723
12724        for chunk in chunks {
12725            let highlight = chunk
12726                .syntax_highlight_id
12727                .and_then(|id| id.name(&style.syntax));
12728            let mut chunk_lines = chunk.text.split('\n').peekable();
12729            while let Some(text) = chunk_lines.next() {
12730                let mut merged_with_last_token = false;
12731                if let Some(last_token) = line.back_mut() {
12732                    if last_token.highlight == highlight {
12733                        last_token.text.push_str(text);
12734                        merged_with_last_token = true;
12735                    }
12736                }
12737
12738                if !merged_with_last_token {
12739                    line.push_back(Chunk {
12740                        text: text.into(),
12741                        highlight,
12742                    });
12743                }
12744
12745                if chunk_lines.peek().is_some() {
12746                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12747                        line.pop_front();
12748                    }
12749                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12750                        line.pop_back();
12751                    }
12752
12753                    lines.push(mem::take(&mut line));
12754                }
12755            }
12756        }
12757
12758        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12759            return;
12760        };
12761        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12762    }
12763
12764    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12765        self.request_autoscroll(Autoscroll::newest(), cx);
12766        let position = self.selections.newest_display(cx).start;
12767        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12768    }
12769
12770    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12771        &self.inlay_hint_cache
12772    }
12773
12774    pub fn replay_insert_event(
12775        &mut self,
12776        text: &str,
12777        relative_utf16_range: Option<Range<isize>>,
12778        cx: &mut ViewContext<Self>,
12779    ) {
12780        if !self.input_enabled {
12781            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12782            return;
12783        }
12784        if let Some(relative_utf16_range) = relative_utf16_range {
12785            let selections = self.selections.all::<OffsetUtf16>(cx);
12786            self.change_selections(None, cx, |s| {
12787                let new_ranges = selections.into_iter().map(|range| {
12788                    let start = OffsetUtf16(
12789                        range
12790                            .head()
12791                            .0
12792                            .saturating_add_signed(relative_utf16_range.start),
12793                    );
12794                    let end = OffsetUtf16(
12795                        range
12796                            .head()
12797                            .0
12798                            .saturating_add_signed(relative_utf16_range.end),
12799                    );
12800                    start..end
12801                });
12802                s.select_ranges(new_ranges);
12803            });
12804        }
12805
12806        self.handle_input(text, cx);
12807    }
12808
12809    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12810        let Some(provider) = self.semantics_provider.as_ref() else {
12811            return false;
12812        };
12813
12814        let mut supports = false;
12815        self.buffer().read(cx).for_each_buffer(|buffer| {
12816            supports |= provider.supports_inlay_hints(buffer, cx);
12817        });
12818        supports
12819    }
12820
12821    pub fn focus(&self, cx: &mut WindowContext) {
12822        cx.focus(&self.focus_handle)
12823    }
12824
12825    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12826        self.focus_handle.is_focused(cx)
12827    }
12828
12829    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12830        cx.emit(EditorEvent::Focused);
12831
12832        if let Some(descendant) = self
12833            .last_focused_descendant
12834            .take()
12835            .and_then(|descendant| descendant.upgrade())
12836        {
12837            cx.focus(&descendant);
12838        } else {
12839            if let Some(blame) = self.blame.as_ref() {
12840                blame.update(cx, GitBlame::focus)
12841            }
12842
12843            self.blink_manager.update(cx, BlinkManager::enable);
12844            self.show_cursor_names(cx);
12845            self.buffer.update(cx, |buffer, cx| {
12846                buffer.finalize_last_transaction(cx);
12847                if self.leader_peer_id.is_none() {
12848                    buffer.set_active_selections(
12849                        &self.selections.disjoint_anchors(),
12850                        self.selections.line_mode,
12851                        self.cursor_shape,
12852                        cx,
12853                    );
12854                }
12855            });
12856        }
12857    }
12858
12859    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12860        cx.emit(EditorEvent::FocusedIn)
12861    }
12862
12863    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12864        if event.blurred != self.focus_handle {
12865            self.last_focused_descendant = Some(event.blurred);
12866        }
12867    }
12868
12869    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12870        self.blink_manager.update(cx, BlinkManager::disable);
12871        self.buffer
12872            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12873
12874        if let Some(blame) = self.blame.as_ref() {
12875            blame.update(cx, GitBlame::blur)
12876        }
12877        if !self.hover_state.focused(cx) {
12878            hide_hover(self, cx);
12879        }
12880
12881        self.hide_context_menu(cx);
12882        cx.emit(EditorEvent::Blurred);
12883        cx.notify();
12884    }
12885
12886    pub fn register_action<A: Action>(
12887        &mut self,
12888        listener: impl Fn(&A, &mut WindowContext) + 'static,
12889    ) -> Subscription {
12890        let id = self.next_editor_action_id.post_inc();
12891        let listener = Arc::new(listener);
12892        self.editor_actions.borrow_mut().insert(
12893            id,
12894            Box::new(move |cx| {
12895                let cx = cx.window_context();
12896                let listener = listener.clone();
12897                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12898                    let action = action.downcast_ref().unwrap();
12899                    if phase == DispatchPhase::Bubble {
12900                        listener(action, cx)
12901                    }
12902                })
12903            }),
12904        );
12905
12906        let editor_actions = self.editor_actions.clone();
12907        Subscription::new(move || {
12908            editor_actions.borrow_mut().remove(&id);
12909        })
12910    }
12911
12912    pub fn file_header_size(&self) -> u32 {
12913        FILE_HEADER_HEIGHT
12914    }
12915
12916    pub fn revert(
12917        &mut self,
12918        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12919        cx: &mut ViewContext<Self>,
12920    ) {
12921        self.buffer().update(cx, |multi_buffer, cx| {
12922            for (buffer_id, changes) in revert_changes {
12923                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12924                    buffer.update(cx, |buffer, cx| {
12925                        buffer.edit(
12926                            changes.into_iter().map(|(range, text)| {
12927                                (range, text.to_string().map(Arc::<str>::from))
12928                            }),
12929                            None,
12930                            cx,
12931                        );
12932                    });
12933                }
12934            }
12935        });
12936        self.change_selections(None, cx, |selections| selections.refresh());
12937    }
12938
12939    pub fn to_pixel_point(
12940        &mut self,
12941        source: multi_buffer::Anchor,
12942        editor_snapshot: &EditorSnapshot,
12943        cx: &mut ViewContext<Self>,
12944    ) -> Option<gpui::Point<Pixels>> {
12945        let source_point = source.to_display_point(editor_snapshot);
12946        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12947    }
12948
12949    pub fn display_to_pixel_point(
12950        &self,
12951        source: DisplayPoint,
12952        editor_snapshot: &EditorSnapshot,
12953        cx: &WindowContext,
12954    ) -> Option<gpui::Point<Pixels>> {
12955        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12956        let text_layout_details = self.text_layout_details(cx);
12957        let scroll_top = text_layout_details
12958            .scroll_anchor
12959            .scroll_position(editor_snapshot)
12960            .y;
12961
12962        if source.row().as_f32() < scroll_top.floor() {
12963            return None;
12964        }
12965        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12966        let source_y = line_height * (source.row().as_f32() - scroll_top);
12967        Some(gpui::Point::new(source_x, source_y))
12968    }
12969
12970    pub fn has_active_completions_menu(&self) -> bool {
12971        self.context_menu.borrow().as_ref().map_or(false, |menu| {
12972            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12973        })
12974    }
12975
12976    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12977        self.addons
12978            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12979    }
12980
12981    pub fn unregister_addon<T: Addon>(&mut self) {
12982        self.addons.remove(&std::any::TypeId::of::<T>());
12983    }
12984
12985    pub fn addon<T: Addon>(&self) -> Option<&T> {
12986        let type_id = std::any::TypeId::of::<T>();
12987        self.addons
12988            .get(&type_id)
12989            .and_then(|item| item.to_any().downcast_ref::<T>())
12990    }
12991
12992    pub fn add_change_set(
12993        &mut self,
12994        change_set: Model<BufferChangeSet>,
12995        cx: &mut ViewContext<Self>,
12996    ) {
12997        self.diff_map.add_change_set(change_set, cx);
12998    }
12999
13000    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13001        let text_layout_details = self.text_layout_details(cx);
13002        let style = &text_layout_details.editor_style;
13003        let font_id = cx.text_system().resolve_font(&style.text.font());
13004        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13005        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13006
13007        let em_width = cx
13008            .text_system()
13009            .typographic_bounds(font_id, font_size, 'm')
13010            .unwrap()
13011            .size
13012            .width;
13013
13014        gpui::Point::new(em_width, line_height)
13015    }
13016}
13017
13018fn get_unstaged_changes_for_buffers(
13019    project: &Model<Project>,
13020    buffers: impl IntoIterator<Item = Model<Buffer>>,
13021    cx: &mut ViewContext<Editor>,
13022) {
13023    let mut tasks = Vec::new();
13024    project.update(cx, |project, cx| {
13025        for buffer in buffers {
13026            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13027        }
13028    });
13029    cx.spawn(|this, mut cx| async move {
13030        let change_sets = futures::future::join_all(tasks).await;
13031        this.update(&mut cx, |this, cx| {
13032            for change_set in change_sets {
13033                if let Some(change_set) = change_set.log_err() {
13034                    this.diff_map.add_change_set(change_set, cx);
13035                }
13036            }
13037        })
13038        .ok();
13039    })
13040    .detach();
13041}
13042
13043fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13044    let tab_size = tab_size.get() as usize;
13045    let mut width = offset;
13046
13047    for ch in text.chars() {
13048        width += if ch == '\t' {
13049            tab_size - (width % tab_size)
13050        } else {
13051            1
13052        };
13053    }
13054
13055    width - offset
13056}
13057
13058#[cfg(test)]
13059mod tests {
13060    use super::*;
13061
13062    #[test]
13063    fn test_string_size_with_expanded_tabs() {
13064        let nz = |val| NonZeroU32::new(val).unwrap();
13065        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13066        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13067        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13068        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13069        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13070        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13071        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13072        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13073    }
13074}
13075
13076/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13077struct WordBreakingTokenizer<'a> {
13078    input: &'a str,
13079}
13080
13081impl<'a> WordBreakingTokenizer<'a> {
13082    fn new(input: &'a str) -> Self {
13083        Self { input }
13084    }
13085}
13086
13087fn is_char_ideographic(ch: char) -> bool {
13088    use unicode_script::Script::*;
13089    use unicode_script::UnicodeScript;
13090    matches!(ch.script(), Han | Tangut | Yi)
13091}
13092
13093fn is_grapheme_ideographic(text: &str) -> bool {
13094    text.chars().any(is_char_ideographic)
13095}
13096
13097fn is_grapheme_whitespace(text: &str) -> bool {
13098    text.chars().any(|x| x.is_whitespace())
13099}
13100
13101fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13102    text.chars().next().map_or(false, |ch| {
13103        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13104    })
13105}
13106
13107#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13108struct WordBreakToken<'a> {
13109    token: &'a str,
13110    grapheme_len: usize,
13111    is_whitespace: bool,
13112}
13113
13114impl<'a> Iterator for WordBreakingTokenizer<'a> {
13115    /// Yields a span, the count of graphemes in the token, and whether it was
13116    /// whitespace. Note that it also breaks at word boundaries.
13117    type Item = WordBreakToken<'a>;
13118
13119    fn next(&mut self) -> Option<Self::Item> {
13120        use unicode_segmentation::UnicodeSegmentation;
13121        if self.input.is_empty() {
13122            return None;
13123        }
13124
13125        let mut iter = self.input.graphemes(true).peekable();
13126        let mut offset = 0;
13127        let mut graphemes = 0;
13128        if let Some(first_grapheme) = iter.next() {
13129            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13130            offset += first_grapheme.len();
13131            graphemes += 1;
13132            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13133                if let Some(grapheme) = iter.peek().copied() {
13134                    if should_stay_with_preceding_ideograph(grapheme) {
13135                        offset += grapheme.len();
13136                        graphemes += 1;
13137                    }
13138                }
13139            } else {
13140                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13141                let mut next_word_bound = words.peek().copied();
13142                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13143                    next_word_bound = words.next();
13144                }
13145                while let Some(grapheme) = iter.peek().copied() {
13146                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13147                        break;
13148                    };
13149                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13150                        break;
13151                    };
13152                    offset += grapheme.len();
13153                    graphemes += 1;
13154                    iter.next();
13155                }
13156            }
13157            let token = &self.input[..offset];
13158            self.input = &self.input[offset..];
13159            if is_whitespace {
13160                Some(WordBreakToken {
13161                    token: " ",
13162                    grapheme_len: 1,
13163                    is_whitespace: true,
13164                })
13165            } else {
13166                Some(WordBreakToken {
13167                    token,
13168                    grapheme_len: graphemes,
13169                    is_whitespace: false,
13170                })
13171            }
13172        } else {
13173            None
13174        }
13175    }
13176}
13177
13178#[test]
13179fn test_word_breaking_tokenizer() {
13180    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13181        ("", &[]),
13182        ("  ", &[(" ", 1, true)]),
13183        ("Ʒ", &[("Ʒ", 1, false)]),
13184        ("Ǽ", &[("Ǽ", 1, false)]),
13185        ("", &[("", 1, false)]),
13186        ("⋑⋑", &[("⋑⋑", 2, false)]),
13187        (
13188            "原理,进而",
13189            &[
13190                ("", 1, false),
13191                ("理,", 2, false),
13192                ("", 1, false),
13193                ("", 1, false),
13194            ],
13195        ),
13196        (
13197            "hello world",
13198            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13199        ),
13200        (
13201            "hello, world",
13202            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13203        ),
13204        (
13205            "  hello world",
13206            &[
13207                (" ", 1, true),
13208                ("hello", 5, false),
13209                (" ", 1, true),
13210                ("world", 5, false),
13211            ],
13212        ),
13213        (
13214            "这是什么 \n 钢笔",
13215            &[
13216                ("", 1, false),
13217                ("", 1, false),
13218                ("", 1, false),
13219                ("", 1, false),
13220                (" ", 1, true),
13221                ("", 1, false),
13222                ("", 1, false),
13223            ],
13224        ),
13225        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13226    ];
13227
13228    for (input, result) in tests {
13229        assert_eq!(
13230            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13231            result
13232                .iter()
13233                .copied()
13234                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13235                    token,
13236                    grapheme_len,
13237                    is_whitespace,
13238                })
13239                .collect::<Vec<_>>()
13240        );
13241    }
13242}
13243
13244fn wrap_with_prefix(
13245    line_prefix: String,
13246    unwrapped_text: String,
13247    wrap_column: usize,
13248    tab_size: NonZeroU32,
13249) -> String {
13250    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13251    let mut wrapped_text = String::new();
13252    let mut current_line = line_prefix.clone();
13253
13254    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13255    let mut current_line_len = line_prefix_len;
13256    for WordBreakToken {
13257        token,
13258        grapheme_len,
13259        is_whitespace,
13260    } in tokenizer
13261    {
13262        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13263            wrapped_text.push_str(current_line.trim_end());
13264            wrapped_text.push('\n');
13265            current_line.truncate(line_prefix.len());
13266            current_line_len = line_prefix_len;
13267            if !is_whitespace {
13268                current_line.push_str(token);
13269                current_line_len += grapheme_len;
13270            }
13271        } else if !is_whitespace {
13272            current_line.push_str(token);
13273            current_line_len += grapheme_len;
13274        } else if current_line_len != line_prefix_len {
13275            current_line.push(' ');
13276            current_line_len += 1;
13277        }
13278    }
13279
13280    if !current_line.is_empty() {
13281        wrapped_text.push_str(&current_line);
13282    }
13283    wrapped_text
13284}
13285
13286#[test]
13287fn test_wrap_with_prefix() {
13288    assert_eq!(
13289        wrap_with_prefix(
13290            "# ".to_string(),
13291            "abcdefg".to_string(),
13292            4,
13293            NonZeroU32::new(4).unwrap()
13294        ),
13295        "# abcdefg"
13296    );
13297    assert_eq!(
13298        wrap_with_prefix(
13299            "".to_string(),
13300            "\thello world".to_string(),
13301            8,
13302            NonZeroU32::new(4).unwrap()
13303        ),
13304        "hello\nworld"
13305    );
13306    assert_eq!(
13307        wrap_with_prefix(
13308            "// ".to_string(),
13309            "xx \nyy zz aa bb cc".to_string(),
13310            12,
13311            NonZeroU32::new(4).unwrap()
13312        ),
13313        "// xx yy zz\n// aa bb cc"
13314    );
13315    assert_eq!(
13316        wrap_with_prefix(
13317            String::new(),
13318            "这是什么 \n 钢笔".to_string(),
13319            3,
13320            NonZeroU32::new(4).unwrap()
13321        ),
13322        "这是什\n么 钢\n"
13323    );
13324}
13325
13326fn hunks_for_selections(
13327    snapshot: &EditorSnapshot,
13328    selections: &[Selection<Point>],
13329) -> Vec<MultiBufferDiffHunk> {
13330    hunks_for_ranges(
13331        selections.iter().map(|selection| selection.range()),
13332        snapshot,
13333    )
13334}
13335
13336pub fn hunks_for_ranges(
13337    ranges: impl Iterator<Item = Range<Point>>,
13338    snapshot: &EditorSnapshot,
13339) -> Vec<MultiBufferDiffHunk> {
13340    let mut hunks = Vec::new();
13341    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13342        HashMap::default();
13343    for query_range in ranges {
13344        let query_rows =
13345            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13346        for hunk in snapshot.diff_map.diff_hunks_in_range(
13347            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13348            &snapshot.buffer_snapshot,
13349        ) {
13350            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13351            // when the caret is just above or just below the deleted hunk.
13352            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13353            let related_to_selection = if allow_adjacent {
13354                hunk.row_range.overlaps(&query_rows)
13355                    || hunk.row_range.start == query_rows.end
13356                    || hunk.row_range.end == query_rows.start
13357            } else {
13358                hunk.row_range.overlaps(&query_rows)
13359            };
13360            if related_to_selection {
13361                if !processed_buffer_rows
13362                    .entry(hunk.buffer_id)
13363                    .or_default()
13364                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13365                {
13366                    continue;
13367                }
13368                hunks.push(hunk);
13369            }
13370        }
13371    }
13372
13373    hunks
13374}
13375
13376pub trait CollaborationHub {
13377    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13378    fn user_participant_indices<'a>(
13379        &self,
13380        cx: &'a AppContext,
13381    ) -> &'a HashMap<u64, ParticipantIndex>;
13382    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13383}
13384
13385impl CollaborationHub for Model<Project> {
13386    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13387        self.read(cx).collaborators()
13388    }
13389
13390    fn user_participant_indices<'a>(
13391        &self,
13392        cx: &'a AppContext,
13393    ) -> &'a HashMap<u64, ParticipantIndex> {
13394        self.read(cx).user_store().read(cx).participant_indices()
13395    }
13396
13397    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13398        let this = self.read(cx);
13399        let user_ids = this.collaborators().values().map(|c| c.user_id);
13400        this.user_store().read_with(cx, |user_store, cx| {
13401            user_store.participant_names(user_ids, cx)
13402        })
13403    }
13404}
13405
13406pub trait SemanticsProvider {
13407    fn hover(
13408        &self,
13409        buffer: &Model<Buffer>,
13410        position: text::Anchor,
13411        cx: &mut AppContext,
13412    ) -> Option<Task<Vec<project::Hover>>>;
13413
13414    fn inlay_hints(
13415        &self,
13416        buffer_handle: Model<Buffer>,
13417        range: Range<text::Anchor>,
13418        cx: &mut AppContext,
13419    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13420
13421    fn resolve_inlay_hint(
13422        &self,
13423        hint: InlayHint,
13424        buffer_handle: Model<Buffer>,
13425        server_id: LanguageServerId,
13426        cx: &mut AppContext,
13427    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13428
13429    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13430
13431    fn document_highlights(
13432        &self,
13433        buffer: &Model<Buffer>,
13434        position: text::Anchor,
13435        cx: &mut AppContext,
13436    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13437
13438    fn definitions(
13439        &self,
13440        buffer: &Model<Buffer>,
13441        position: text::Anchor,
13442        kind: GotoDefinitionKind,
13443        cx: &mut AppContext,
13444    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13445
13446    fn range_for_rename(
13447        &self,
13448        buffer: &Model<Buffer>,
13449        position: text::Anchor,
13450        cx: &mut AppContext,
13451    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13452
13453    fn perform_rename(
13454        &self,
13455        buffer: &Model<Buffer>,
13456        position: text::Anchor,
13457        new_name: String,
13458        cx: &mut AppContext,
13459    ) -> Option<Task<Result<ProjectTransaction>>>;
13460}
13461
13462pub trait CompletionProvider {
13463    fn completions(
13464        &self,
13465        buffer: &Model<Buffer>,
13466        buffer_position: text::Anchor,
13467        trigger: CompletionContext,
13468        cx: &mut ViewContext<Editor>,
13469    ) -> Task<Result<Vec<Completion>>>;
13470
13471    fn resolve_completions(
13472        &self,
13473        buffer: Model<Buffer>,
13474        completion_indices: Vec<usize>,
13475        completions: Rc<RefCell<Box<[Completion]>>>,
13476        cx: &mut ViewContext<Editor>,
13477    ) -> Task<Result<bool>>;
13478
13479    fn apply_additional_edits_for_completion(
13480        &self,
13481        _buffer: Model<Buffer>,
13482        _completions: Rc<RefCell<Box<[Completion]>>>,
13483        _completion_index: usize,
13484        _push_to_history: bool,
13485        _cx: &mut ViewContext<Editor>,
13486    ) -> Task<Result<Option<language::Transaction>>> {
13487        Task::ready(Ok(None))
13488    }
13489
13490    fn is_completion_trigger(
13491        &self,
13492        buffer: &Model<Buffer>,
13493        position: language::Anchor,
13494        text: &str,
13495        trigger_in_words: bool,
13496        cx: &mut ViewContext<Editor>,
13497    ) -> bool;
13498
13499    fn sort_completions(&self) -> bool {
13500        true
13501    }
13502}
13503
13504pub trait CodeActionProvider {
13505    fn code_actions(
13506        &self,
13507        buffer: &Model<Buffer>,
13508        range: Range<text::Anchor>,
13509        cx: &mut WindowContext,
13510    ) -> Task<Result<Vec<CodeAction>>>;
13511
13512    fn apply_code_action(
13513        &self,
13514        buffer_handle: Model<Buffer>,
13515        action: CodeAction,
13516        excerpt_id: ExcerptId,
13517        push_to_history: bool,
13518        cx: &mut WindowContext,
13519    ) -> Task<Result<ProjectTransaction>>;
13520}
13521
13522impl CodeActionProvider for Model<Project> {
13523    fn code_actions(
13524        &self,
13525        buffer: &Model<Buffer>,
13526        range: Range<text::Anchor>,
13527        cx: &mut WindowContext,
13528    ) -> Task<Result<Vec<CodeAction>>> {
13529        self.update(cx, |project, cx| {
13530            project.code_actions(buffer, range, None, cx)
13531        })
13532    }
13533
13534    fn apply_code_action(
13535        &self,
13536        buffer_handle: Model<Buffer>,
13537        action: CodeAction,
13538        _excerpt_id: ExcerptId,
13539        push_to_history: bool,
13540        cx: &mut WindowContext,
13541    ) -> Task<Result<ProjectTransaction>> {
13542        self.update(cx, |project, cx| {
13543            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13544        })
13545    }
13546}
13547
13548fn snippet_completions(
13549    project: &Project,
13550    buffer: &Model<Buffer>,
13551    buffer_position: text::Anchor,
13552    cx: &mut AppContext,
13553) -> Task<Result<Vec<Completion>>> {
13554    let language = buffer.read(cx).language_at(buffer_position);
13555    let language_name = language.as_ref().map(|language| language.lsp_id());
13556    let snippet_store = project.snippets().read(cx);
13557    let snippets = snippet_store.snippets_for(language_name, cx);
13558
13559    if snippets.is_empty() {
13560        return Task::ready(Ok(vec![]));
13561    }
13562    let snapshot = buffer.read(cx).text_snapshot();
13563    let chars: String = snapshot
13564        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13565        .collect();
13566
13567    let scope = language.map(|language| language.default_scope());
13568    let executor = cx.background_executor().clone();
13569
13570    cx.background_executor().spawn(async move {
13571        let classifier = CharClassifier::new(scope).for_completion(true);
13572        let mut last_word = chars
13573            .chars()
13574            .take_while(|c| classifier.is_word(*c))
13575            .collect::<String>();
13576        last_word = last_word.chars().rev().collect();
13577
13578        if last_word.is_empty() {
13579            return Ok(vec![]);
13580        }
13581
13582        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13583        let to_lsp = |point: &text::Anchor| {
13584            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13585            point_to_lsp(end)
13586        };
13587        let lsp_end = to_lsp(&buffer_position);
13588
13589        let candidates = snippets
13590            .iter()
13591            .enumerate()
13592            .flat_map(|(ix, snippet)| {
13593                snippet
13594                    .prefix
13595                    .iter()
13596                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13597            })
13598            .collect::<Vec<StringMatchCandidate>>();
13599
13600        let mut matches = fuzzy::match_strings(
13601            &candidates,
13602            &last_word,
13603            last_word.chars().any(|c| c.is_uppercase()),
13604            100,
13605            &Default::default(),
13606            executor,
13607        )
13608        .await;
13609
13610        // Remove all candidates where the query's start does not match the start of any word in the candidate
13611        if let Some(query_start) = last_word.chars().next() {
13612            matches.retain(|string_match| {
13613                split_words(&string_match.string).any(|word| {
13614                    // Check that the first codepoint of the word as lowercase matches the first
13615                    // codepoint of the query as lowercase
13616                    word.chars()
13617                        .flat_map(|codepoint| codepoint.to_lowercase())
13618                        .zip(query_start.to_lowercase())
13619                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13620                })
13621            });
13622        }
13623
13624        let matched_strings = matches
13625            .into_iter()
13626            .map(|m| m.string)
13627            .collect::<HashSet<_>>();
13628
13629        let result: Vec<Completion> = snippets
13630            .into_iter()
13631            .filter_map(|snippet| {
13632                let matching_prefix = snippet
13633                    .prefix
13634                    .iter()
13635                    .find(|prefix| matched_strings.contains(*prefix))?;
13636                let start = as_offset - last_word.len();
13637                let start = snapshot.anchor_before(start);
13638                let range = start..buffer_position;
13639                let lsp_start = to_lsp(&start);
13640                let lsp_range = lsp::Range {
13641                    start: lsp_start,
13642                    end: lsp_end,
13643                };
13644                Some(Completion {
13645                    old_range: range,
13646                    new_text: snippet.body.clone(),
13647                    resolved: false,
13648                    label: CodeLabel {
13649                        text: matching_prefix.clone(),
13650                        runs: vec![],
13651                        filter_range: 0..matching_prefix.len(),
13652                    },
13653                    server_id: LanguageServerId(usize::MAX),
13654                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13655                    lsp_completion: lsp::CompletionItem {
13656                        label: snippet.prefix.first().unwrap().clone(),
13657                        kind: Some(CompletionItemKind::SNIPPET),
13658                        label_details: snippet.description.as_ref().map(|description| {
13659                            lsp::CompletionItemLabelDetails {
13660                                detail: Some(description.clone()),
13661                                description: None,
13662                            }
13663                        }),
13664                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13665                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13666                            lsp::InsertReplaceEdit {
13667                                new_text: snippet.body.clone(),
13668                                insert: lsp_range,
13669                                replace: lsp_range,
13670                            },
13671                        )),
13672                        filter_text: Some(snippet.body.clone()),
13673                        sort_text: Some(char::MAX.to_string()),
13674                        ..Default::default()
13675                    },
13676                    confirm: None,
13677                })
13678            })
13679            .collect();
13680
13681        Ok(result)
13682    })
13683}
13684
13685impl CompletionProvider for Model<Project> {
13686    fn completions(
13687        &self,
13688        buffer: &Model<Buffer>,
13689        buffer_position: text::Anchor,
13690        options: CompletionContext,
13691        cx: &mut ViewContext<Editor>,
13692    ) -> Task<Result<Vec<Completion>>> {
13693        self.update(cx, |project, cx| {
13694            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13695            let project_completions = project.completions(buffer, buffer_position, options, cx);
13696            cx.background_executor().spawn(async move {
13697                let mut completions = project_completions.await?;
13698                let snippets_completions = snippets.await?;
13699                completions.extend(snippets_completions);
13700                Ok(completions)
13701            })
13702        })
13703    }
13704
13705    fn resolve_completions(
13706        &self,
13707        buffer: Model<Buffer>,
13708        completion_indices: Vec<usize>,
13709        completions: Rc<RefCell<Box<[Completion]>>>,
13710        cx: &mut ViewContext<Editor>,
13711    ) -> Task<Result<bool>> {
13712        self.update(cx, |project, cx| {
13713            project.lsp_store().update(cx, |lsp_store, cx| {
13714                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13715            })
13716        })
13717    }
13718
13719    fn apply_additional_edits_for_completion(
13720        &self,
13721        buffer: Model<Buffer>,
13722        completions: Rc<RefCell<Box<[Completion]>>>,
13723        completion_index: usize,
13724        push_to_history: bool,
13725        cx: &mut ViewContext<Editor>,
13726    ) -> Task<Result<Option<language::Transaction>>> {
13727        self.update(cx, |project, cx| {
13728            project.lsp_store().update(cx, |lsp_store, cx| {
13729                lsp_store.apply_additional_edits_for_completion(
13730                    buffer,
13731                    completions,
13732                    completion_index,
13733                    push_to_history,
13734                    cx,
13735                )
13736            })
13737        })
13738    }
13739
13740    fn is_completion_trigger(
13741        &self,
13742        buffer: &Model<Buffer>,
13743        position: language::Anchor,
13744        text: &str,
13745        trigger_in_words: bool,
13746        cx: &mut ViewContext<Editor>,
13747    ) -> bool {
13748        let mut chars = text.chars();
13749        let char = if let Some(char) = chars.next() {
13750            char
13751        } else {
13752            return false;
13753        };
13754        if chars.next().is_some() {
13755            return false;
13756        }
13757
13758        let buffer = buffer.read(cx);
13759        let snapshot = buffer.snapshot();
13760        if !snapshot.settings_at(position, cx).show_completions_on_input {
13761            return false;
13762        }
13763        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13764        if trigger_in_words && classifier.is_word(char) {
13765            return true;
13766        }
13767
13768        buffer.completion_triggers().contains(text)
13769    }
13770}
13771
13772impl SemanticsProvider for Model<Project> {
13773    fn hover(
13774        &self,
13775        buffer: &Model<Buffer>,
13776        position: text::Anchor,
13777        cx: &mut AppContext,
13778    ) -> Option<Task<Vec<project::Hover>>> {
13779        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13780    }
13781
13782    fn document_highlights(
13783        &self,
13784        buffer: &Model<Buffer>,
13785        position: text::Anchor,
13786        cx: &mut AppContext,
13787    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13788        Some(self.update(cx, |project, cx| {
13789            project.document_highlights(buffer, position, cx)
13790        }))
13791    }
13792
13793    fn definitions(
13794        &self,
13795        buffer: &Model<Buffer>,
13796        position: text::Anchor,
13797        kind: GotoDefinitionKind,
13798        cx: &mut AppContext,
13799    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13800        Some(self.update(cx, |project, cx| match kind {
13801            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13802            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13803            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13804            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13805        }))
13806    }
13807
13808    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13809        // TODO: make this work for remote projects
13810        self.read(cx)
13811            .language_servers_for_local_buffer(buffer.read(cx), cx)
13812            .any(
13813                |(_, server)| match server.capabilities().inlay_hint_provider {
13814                    Some(lsp::OneOf::Left(enabled)) => enabled,
13815                    Some(lsp::OneOf::Right(_)) => true,
13816                    None => false,
13817                },
13818            )
13819    }
13820
13821    fn inlay_hints(
13822        &self,
13823        buffer_handle: Model<Buffer>,
13824        range: Range<text::Anchor>,
13825        cx: &mut AppContext,
13826    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13827        Some(self.update(cx, |project, cx| {
13828            project.inlay_hints(buffer_handle, range, cx)
13829        }))
13830    }
13831
13832    fn resolve_inlay_hint(
13833        &self,
13834        hint: InlayHint,
13835        buffer_handle: Model<Buffer>,
13836        server_id: LanguageServerId,
13837        cx: &mut AppContext,
13838    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13839        Some(self.update(cx, |project, cx| {
13840            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13841        }))
13842    }
13843
13844    fn range_for_rename(
13845        &self,
13846        buffer: &Model<Buffer>,
13847        position: text::Anchor,
13848        cx: &mut AppContext,
13849    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13850        Some(self.update(cx, |project, cx| {
13851            project.prepare_rename(buffer.clone(), position, cx)
13852        }))
13853    }
13854
13855    fn perform_rename(
13856        &self,
13857        buffer: &Model<Buffer>,
13858        position: text::Anchor,
13859        new_name: String,
13860        cx: &mut AppContext,
13861    ) -> Option<Task<Result<ProjectTransaction>>> {
13862        Some(self.update(cx, |project, cx| {
13863            project.perform_rename(buffer.clone(), position, new_name, cx)
13864        }))
13865    }
13866}
13867
13868fn inlay_hint_settings(
13869    location: Anchor,
13870    snapshot: &MultiBufferSnapshot,
13871    cx: &mut ViewContext<Editor>,
13872) -> InlayHintSettings {
13873    let file = snapshot.file_at(location);
13874    let language = snapshot.language_at(location).map(|l| l.name());
13875    language_settings(language, file, cx).inlay_hints
13876}
13877
13878fn consume_contiguous_rows(
13879    contiguous_row_selections: &mut Vec<Selection<Point>>,
13880    selection: &Selection<Point>,
13881    display_map: &DisplaySnapshot,
13882    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13883) -> (MultiBufferRow, MultiBufferRow) {
13884    contiguous_row_selections.push(selection.clone());
13885    let start_row = MultiBufferRow(selection.start.row);
13886    let mut end_row = ending_row(selection, display_map);
13887
13888    while let Some(next_selection) = selections.peek() {
13889        if next_selection.start.row <= end_row.0 {
13890            end_row = ending_row(next_selection, display_map);
13891            contiguous_row_selections.push(selections.next().unwrap().clone());
13892        } else {
13893            break;
13894        }
13895    }
13896    (start_row, end_row)
13897}
13898
13899fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13900    if next_selection.end.column > 0 || next_selection.is_empty() {
13901        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13902    } else {
13903        MultiBufferRow(next_selection.end.row)
13904    }
13905}
13906
13907impl EditorSnapshot {
13908    pub fn remote_selections_in_range<'a>(
13909        &'a self,
13910        range: &'a Range<Anchor>,
13911        collaboration_hub: &dyn CollaborationHub,
13912        cx: &'a AppContext,
13913    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13914        let participant_names = collaboration_hub.user_names(cx);
13915        let participant_indices = collaboration_hub.user_participant_indices(cx);
13916        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13917        let collaborators_by_replica_id = collaborators_by_peer_id
13918            .iter()
13919            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13920            .collect::<HashMap<_, _>>();
13921        self.buffer_snapshot
13922            .selections_in_range(range, false)
13923            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13924                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13925                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13926                let user_name = participant_names.get(&collaborator.user_id).cloned();
13927                Some(RemoteSelection {
13928                    replica_id,
13929                    selection,
13930                    cursor_shape,
13931                    line_mode,
13932                    participant_index,
13933                    peer_id: collaborator.peer_id,
13934                    user_name,
13935                })
13936            })
13937    }
13938
13939    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13940        self.display_snapshot.buffer_snapshot.language_at(position)
13941    }
13942
13943    pub fn is_focused(&self) -> bool {
13944        self.is_focused
13945    }
13946
13947    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13948        self.placeholder_text.as_ref()
13949    }
13950
13951    pub fn scroll_position(&self) -> gpui::Point<f32> {
13952        self.scroll_anchor.scroll_position(&self.display_snapshot)
13953    }
13954
13955    fn gutter_dimensions(
13956        &self,
13957        font_id: FontId,
13958        font_size: Pixels,
13959        em_width: Pixels,
13960        em_advance: Pixels,
13961        max_line_number_width: Pixels,
13962        cx: &AppContext,
13963    ) -> GutterDimensions {
13964        if !self.show_gutter {
13965            return GutterDimensions::default();
13966        }
13967        let descent = cx.text_system().descent(font_id, font_size);
13968
13969        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13970            matches!(
13971                ProjectSettings::get_global(cx).git.git_gutter,
13972                Some(GitGutterSetting::TrackedFiles)
13973            )
13974        });
13975        let gutter_settings = EditorSettings::get_global(cx).gutter;
13976        let show_line_numbers = self
13977            .show_line_numbers
13978            .unwrap_or(gutter_settings.line_numbers);
13979        let line_gutter_width = if show_line_numbers {
13980            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13981            let min_width_for_number_on_gutter = em_advance * 4.0;
13982            max_line_number_width.max(min_width_for_number_on_gutter)
13983        } else {
13984            0.0.into()
13985        };
13986
13987        let show_code_actions = self
13988            .show_code_actions
13989            .unwrap_or(gutter_settings.code_actions);
13990
13991        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13992
13993        let git_blame_entries_width =
13994            self.git_blame_gutter_max_author_length
13995                .map(|max_author_length| {
13996                    // Length of the author name, but also space for the commit hash,
13997                    // the spacing and the timestamp.
13998                    let max_char_count = max_author_length
13999                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14000                        + 7 // length of commit sha
14001                        + 14 // length of max relative timestamp ("60 minutes ago")
14002                        + 4; // gaps and margins
14003
14004                    em_advance * max_char_count
14005                });
14006
14007        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14008        left_padding += if show_code_actions || show_runnables {
14009            em_width * 3.0
14010        } else if show_git_gutter && show_line_numbers {
14011            em_width * 2.0
14012        } else if show_git_gutter || show_line_numbers {
14013            em_width
14014        } else {
14015            px(0.)
14016        };
14017
14018        let right_padding = if gutter_settings.folds && show_line_numbers {
14019            em_width * 4.0
14020        } else if gutter_settings.folds {
14021            em_width * 3.0
14022        } else if show_line_numbers {
14023            em_width
14024        } else {
14025            px(0.)
14026        };
14027
14028        GutterDimensions {
14029            left_padding,
14030            right_padding,
14031            width: line_gutter_width + left_padding + right_padding,
14032            margin: -descent,
14033            git_blame_entries_width,
14034        }
14035    }
14036
14037    pub fn render_crease_toggle(
14038        &self,
14039        buffer_row: MultiBufferRow,
14040        row_contains_cursor: bool,
14041        editor: View<Editor>,
14042        cx: &mut WindowContext,
14043    ) -> Option<AnyElement> {
14044        let folded = self.is_line_folded(buffer_row);
14045        let mut is_foldable = false;
14046
14047        if let Some(crease) = self
14048            .crease_snapshot
14049            .query_row(buffer_row, &self.buffer_snapshot)
14050        {
14051            is_foldable = true;
14052            match crease {
14053                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14054                    if let Some(render_toggle) = render_toggle {
14055                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14056                            if folded {
14057                                editor.update(cx, |editor, cx| {
14058                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14059                                });
14060                            } else {
14061                                editor.update(cx, |editor, cx| {
14062                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14063                                });
14064                            }
14065                        });
14066                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14067                    }
14068                }
14069            }
14070        }
14071
14072        is_foldable |= self.starts_indent(buffer_row);
14073
14074        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14075            Some(
14076                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14077                    .toggle_state(folded)
14078                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14079                        if folded {
14080                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14081                        } else {
14082                            this.fold_at(&FoldAt { buffer_row }, cx);
14083                        }
14084                    }))
14085                    .into_any_element(),
14086            )
14087        } else {
14088            None
14089        }
14090    }
14091
14092    pub fn render_crease_trailer(
14093        &self,
14094        buffer_row: MultiBufferRow,
14095        cx: &mut WindowContext,
14096    ) -> Option<AnyElement> {
14097        let folded = self.is_line_folded(buffer_row);
14098        if let Crease::Inline { render_trailer, .. } = self
14099            .crease_snapshot
14100            .query_row(buffer_row, &self.buffer_snapshot)?
14101        {
14102            let render_trailer = render_trailer.as_ref()?;
14103            Some(render_trailer(buffer_row, folded, cx))
14104        } else {
14105            None
14106        }
14107    }
14108}
14109
14110impl Deref for EditorSnapshot {
14111    type Target = DisplaySnapshot;
14112
14113    fn deref(&self) -> &Self::Target {
14114        &self.display_snapshot
14115    }
14116}
14117
14118#[derive(Clone, Debug, PartialEq, Eq)]
14119pub enum EditorEvent {
14120    InputIgnored {
14121        text: Arc<str>,
14122    },
14123    InputHandled {
14124        utf16_range_to_replace: Option<Range<isize>>,
14125        text: Arc<str>,
14126    },
14127    ExcerptsAdded {
14128        buffer: Model<Buffer>,
14129        predecessor: ExcerptId,
14130        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14131    },
14132    ExcerptsRemoved {
14133        ids: Vec<ExcerptId>,
14134    },
14135    BufferFoldToggled {
14136        ids: Vec<ExcerptId>,
14137        folded: bool,
14138    },
14139    ExcerptsEdited {
14140        ids: Vec<ExcerptId>,
14141    },
14142    ExcerptsExpanded {
14143        ids: Vec<ExcerptId>,
14144    },
14145    BufferEdited,
14146    Edited {
14147        transaction_id: clock::Lamport,
14148    },
14149    Reparsed(BufferId),
14150    Focused,
14151    FocusedIn,
14152    Blurred,
14153    DirtyChanged,
14154    Saved,
14155    TitleChanged,
14156    DiffBaseChanged,
14157    SelectionsChanged {
14158        local: bool,
14159    },
14160    ScrollPositionChanged {
14161        local: bool,
14162        autoscroll: bool,
14163    },
14164    Closed,
14165    TransactionUndone {
14166        transaction_id: clock::Lamport,
14167    },
14168    TransactionBegun {
14169        transaction_id: clock::Lamport,
14170    },
14171    Reloaded,
14172    CursorShapeChanged,
14173}
14174
14175impl EventEmitter<EditorEvent> for Editor {}
14176
14177impl FocusableView for Editor {
14178    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14179        self.focus_handle.clone()
14180    }
14181}
14182
14183impl Render for Editor {
14184    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14185        let settings = ThemeSettings::get_global(cx);
14186
14187        let mut text_style = match self.mode {
14188            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14189                color: cx.theme().colors().editor_foreground,
14190                font_family: settings.ui_font.family.clone(),
14191                font_features: settings.ui_font.features.clone(),
14192                font_fallbacks: settings.ui_font.fallbacks.clone(),
14193                font_size: rems(0.875).into(),
14194                font_weight: settings.ui_font.weight,
14195                line_height: relative(settings.buffer_line_height.value()),
14196                ..Default::default()
14197            },
14198            EditorMode::Full => TextStyle {
14199                color: cx.theme().colors().editor_foreground,
14200                font_family: settings.buffer_font.family.clone(),
14201                font_features: settings.buffer_font.features.clone(),
14202                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14203                font_size: settings.buffer_font_size(cx).into(),
14204                font_weight: settings.buffer_font.weight,
14205                line_height: relative(settings.buffer_line_height.value()),
14206                ..Default::default()
14207            },
14208        };
14209        if let Some(text_style_refinement) = &self.text_style_refinement {
14210            text_style.refine(text_style_refinement)
14211        }
14212
14213        let background = match self.mode {
14214            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14215            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14216            EditorMode::Full => cx.theme().colors().editor_background,
14217        };
14218
14219        EditorElement::new(
14220            cx.view(),
14221            EditorStyle {
14222                background,
14223                local_player: cx.theme().players().local(),
14224                text: text_style,
14225                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14226                syntax: cx.theme().syntax().clone(),
14227                status: cx.theme().status().clone(),
14228                inlay_hints_style: make_inlay_hints_style(cx),
14229                inline_completion_styles: make_suggestion_styles(cx),
14230                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14231            },
14232        )
14233    }
14234}
14235
14236impl ViewInputHandler for Editor {
14237    fn text_for_range(
14238        &mut self,
14239        range_utf16: Range<usize>,
14240        adjusted_range: &mut Option<Range<usize>>,
14241        cx: &mut ViewContext<Self>,
14242    ) -> Option<String> {
14243        let snapshot = self.buffer.read(cx).read(cx);
14244        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14245        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14246        if (start.0..end.0) != range_utf16 {
14247            adjusted_range.replace(start.0..end.0);
14248        }
14249        Some(snapshot.text_for_range(start..end).collect())
14250    }
14251
14252    fn selected_text_range(
14253        &mut self,
14254        ignore_disabled_input: bool,
14255        cx: &mut ViewContext<Self>,
14256    ) -> Option<UTF16Selection> {
14257        // Prevent the IME menu from appearing when holding down an alphabetic key
14258        // while input is disabled.
14259        if !ignore_disabled_input && !self.input_enabled {
14260            return None;
14261        }
14262
14263        let selection = self.selections.newest::<OffsetUtf16>(cx);
14264        let range = selection.range();
14265
14266        Some(UTF16Selection {
14267            range: range.start.0..range.end.0,
14268            reversed: selection.reversed,
14269        })
14270    }
14271
14272    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14273        let snapshot = self.buffer.read(cx).read(cx);
14274        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14275        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14276    }
14277
14278    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14279        self.clear_highlights::<InputComposition>(cx);
14280        self.ime_transaction.take();
14281    }
14282
14283    fn replace_text_in_range(
14284        &mut self,
14285        range_utf16: Option<Range<usize>>,
14286        text: &str,
14287        cx: &mut ViewContext<Self>,
14288    ) {
14289        if !self.input_enabled {
14290            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14291            return;
14292        }
14293
14294        self.transact(cx, |this, cx| {
14295            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14296                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14297                Some(this.selection_replacement_ranges(range_utf16, cx))
14298            } else {
14299                this.marked_text_ranges(cx)
14300            };
14301
14302            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14303                let newest_selection_id = this.selections.newest_anchor().id;
14304                this.selections
14305                    .all::<OffsetUtf16>(cx)
14306                    .iter()
14307                    .zip(ranges_to_replace.iter())
14308                    .find_map(|(selection, range)| {
14309                        if selection.id == newest_selection_id {
14310                            Some(
14311                                (range.start.0 as isize - selection.head().0 as isize)
14312                                    ..(range.end.0 as isize - selection.head().0 as isize),
14313                            )
14314                        } else {
14315                            None
14316                        }
14317                    })
14318            });
14319
14320            cx.emit(EditorEvent::InputHandled {
14321                utf16_range_to_replace: range_to_replace,
14322                text: text.into(),
14323            });
14324
14325            if let Some(new_selected_ranges) = new_selected_ranges {
14326                this.change_selections(None, cx, |selections| {
14327                    selections.select_ranges(new_selected_ranges)
14328                });
14329                this.backspace(&Default::default(), cx);
14330            }
14331
14332            this.handle_input(text, cx);
14333        });
14334
14335        if let Some(transaction) = self.ime_transaction {
14336            self.buffer.update(cx, |buffer, cx| {
14337                buffer.group_until_transaction(transaction, cx);
14338            });
14339        }
14340
14341        self.unmark_text(cx);
14342    }
14343
14344    fn replace_and_mark_text_in_range(
14345        &mut self,
14346        range_utf16: Option<Range<usize>>,
14347        text: &str,
14348        new_selected_range_utf16: Option<Range<usize>>,
14349        cx: &mut ViewContext<Self>,
14350    ) {
14351        if !self.input_enabled {
14352            return;
14353        }
14354
14355        let transaction = self.transact(cx, |this, cx| {
14356            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14357                let snapshot = this.buffer.read(cx).read(cx);
14358                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14359                    for marked_range in &mut marked_ranges {
14360                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14361                        marked_range.start.0 += relative_range_utf16.start;
14362                        marked_range.start =
14363                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14364                        marked_range.end =
14365                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14366                    }
14367                }
14368                Some(marked_ranges)
14369            } else if let Some(range_utf16) = range_utf16 {
14370                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14371                Some(this.selection_replacement_ranges(range_utf16, cx))
14372            } else {
14373                None
14374            };
14375
14376            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14377                let newest_selection_id = this.selections.newest_anchor().id;
14378                this.selections
14379                    .all::<OffsetUtf16>(cx)
14380                    .iter()
14381                    .zip(ranges_to_replace.iter())
14382                    .find_map(|(selection, range)| {
14383                        if selection.id == newest_selection_id {
14384                            Some(
14385                                (range.start.0 as isize - selection.head().0 as isize)
14386                                    ..(range.end.0 as isize - selection.head().0 as isize),
14387                            )
14388                        } else {
14389                            None
14390                        }
14391                    })
14392            });
14393
14394            cx.emit(EditorEvent::InputHandled {
14395                utf16_range_to_replace: range_to_replace,
14396                text: text.into(),
14397            });
14398
14399            if let Some(ranges) = ranges_to_replace {
14400                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14401            }
14402
14403            let marked_ranges = {
14404                let snapshot = this.buffer.read(cx).read(cx);
14405                this.selections
14406                    .disjoint_anchors()
14407                    .iter()
14408                    .map(|selection| {
14409                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14410                    })
14411                    .collect::<Vec<_>>()
14412            };
14413
14414            if text.is_empty() {
14415                this.unmark_text(cx);
14416            } else {
14417                this.highlight_text::<InputComposition>(
14418                    marked_ranges.clone(),
14419                    HighlightStyle {
14420                        underline: Some(UnderlineStyle {
14421                            thickness: px(1.),
14422                            color: None,
14423                            wavy: false,
14424                        }),
14425                        ..Default::default()
14426                    },
14427                    cx,
14428                );
14429            }
14430
14431            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14432            let use_autoclose = this.use_autoclose;
14433            let use_auto_surround = this.use_auto_surround;
14434            this.set_use_autoclose(false);
14435            this.set_use_auto_surround(false);
14436            this.handle_input(text, cx);
14437            this.set_use_autoclose(use_autoclose);
14438            this.set_use_auto_surround(use_auto_surround);
14439
14440            if let Some(new_selected_range) = new_selected_range_utf16 {
14441                let snapshot = this.buffer.read(cx).read(cx);
14442                let new_selected_ranges = marked_ranges
14443                    .into_iter()
14444                    .map(|marked_range| {
14445                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14446                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14447                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14448                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14449                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14450                    })
14451                    .collect::<Vec<_>>();
14452
14453                drop(snapshot);
14454                this.change_selections(None, cx, |selections| {
14455                    selections.select_ranges(new_selected_ranges)
14456                });
14457            }
14458        });
14459
14460        self.ime_transaction = self.ime_transaction.or(transaction);
14461        if let Some(transaction) = self.ime_transaction {
14462            self.buffer.update(cx, |buffer, cx| {
14463                buffer.group_until_transaction(transaction, cx);
14464            });
14465        }
14466
14467        if self.text_highlights::<InputComposition>(cx).is_none() {
14468            self.ime_transaction.take();
14469        }
14470    }
14471
14472    fn bounds_for_range(
14473        &mut self,
14474        range_utf16: Range<usize>,
14475        element_bounds: gpui::Bounds<Pixels>,
14476        cx: &mut ViewContext<Self>,
14477    ) -> Option<gpui::Bounds<Pixels>> {
14478        let text_layout_details = self.text_layout_details(cx);
14479        let gpui::Point {
14480            x: em_width,
14481            y: line_height,
14482        } = self.character_size(cx);
14483
14484        let snapshot = self.snapshot(cx);
14485        let scroll_position = snapshot.scroll_position();
14486        let scroll_left = scroll_position.x * em_width;
14487
14488        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14489        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14490            + self.gutter_dimensions.width
14491            + self.gutter_dimensions.margin;
14492        let y = line_height * (start.row().as_f32() - scroll_position.y);
14493
14494        Some(Bounds {
14495            origin: element_bounds.origin + point(x, y),
14496            size: size(em_width, line_height),
14497        })
14498    }
14499}
14500
14501trait SelectionExt {
14502    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14503    fn spanned_rows(
14504        &self,
14505        include_end_if_at_line_start: bool,
14506        map: &DisplaySnapshot,
14507    ) -> Range<MultiBufferRow>;
14508}
14509
14510impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14511    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14512        let start = self
14513            .start
14514            .to_point(&map.buffer_snapshot)
14515            .to_display_point(map);
14516        let end = self
14517            .end
14518            .to_point(&map.buffer_snapshot)
14519            .to_display_point(map);
14520        if self.reversed {
14521            end..start
14522        } else {
14523            start..end
14524        }
14525    }
14526
14527    fn spanned_rows(
14528        &self,
14529        include_end_if_at_line_start: bool,
14530        map: &DisplaySnapshot,
14531    ) -> Range<MultiBufferRow> {
14532        let start = self.start.to_point(&map.buffer_snapshot);
14533        let mut end = self.end.to_point(&map.buffer_snapshot);
14534        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14535            end.row -= 1;
14536        }
14537
14538        let buffer_start = map.prev_line_boundary(start).0;
14539        let buffer_end = map.next_line_boundary(end).0;
14540        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14541    }
14542}
14543
14544impl<T: InvalidationRegion> InvalidationStack<T> {
14545    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14546    where
14547        S: Clone + ToOffset,
14548    {
14549        while let Some(region) = self.last() {
14550            let all_selections_inside_invalidation_ranges =
14551                if selections.len() == region.ranges().len() {
14552                    selections
14553                        .iter()
14554                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14555                        .all(|(selection, invalidation_range)| {
14556                            let head = selection.head().to_offset(buffer);
14557                            invalidation_range.start <= head && invalidation_range.end >= head
14558                        })
14559                } else {
14560                    false
14561                };
14562
14563            if all_selections_inside_invalidation_ranges {
14564                break;
14565            } else {
14566                self.pop();
14567            }
14568        }
14569    }
14570}
14571
14572impl<T> Default for InvalidationStack<T> {
14573    fn default() -> Self {
14574        Self(Default::default())
14575    }
14576}
14577
14578impl<T> Deref for InvalidationStack<T> {
14579    type Target = Vec<T>;
14580
14581    fn deref(&self) -> &Self::Target {
14582        &self.0
14583    }
14584}
14585
14586impl<T> DerefMut for InvalidationStack<T> {
14587    fn deref_mut(&mut self) -> &mut Self::Target {
14588        &mut self.0
14589    }
14590}
14591
14592impl InvalidationRegion for SnippetState {
14593    fn ranges(&self) -> &[Range<Anchor>] {
14594        &self.ranges[self.active_index]
14595    }
14596}
14597
14598pub fn diagnostic_block_renderer(
14599    diagnostic: Diagnostic,
14600    max_message_rows: Option<u8>,
14601    allow_closing: bool,
14602    _is_valid: bool,
14603) -> RenderBlock {
14604    let (text_without_backticks, code_ranges) =
14605        highlight_diagnostic_message(&diagnostic, max_message_rows);
14606
14607    Arc::new(move |cx: &mut BlockContext| {
14608        let group_id: SharedString = cx.block_id.to_string().into();
14609
14610        let mut text_style = cx.text_style().clone();
14611        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14612        let theme_settings = ThemeSettings::get_global(cx);
14613        text_style.font_family = theme_settings.buffer_font.family.clone();
14614        text_style.font_style = theme_settings.buffer_font.style;
14615        text_style.font_features = theme_settings.buffer_font.features.clone();
14616        text_style.font_weight = theme_settings.buffer_font.weight;
14617
14618        let multi_line_diagnostic = diagnostic.message.contains('\n');
14619
14620        let buttons = |diagnostic: &Diagnostic| {
14621            if multi_line_diagnostic {
14622                v_flex()
14623            } else {
14624                h_flex()
14625            }
14626            .when(allow_closing, |div| {
14627                div.children(diagnostic.is_primary.then(|| {
14628                    IconButton::new("close-block", IconName::XCircle)
14629                        .icon_color(Color::Muted)
14630                        .size(ButtonSize::Compact)
14631                        .style(ButtonStyle::Transparent)
14632                        .visible_on_hover(group_id.clone())
14633                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14634                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14635                }))
14636            })
14637            .child(
14638                IconButton::new("copy-block", IconName::Copy)
14639                    .icon_color(Color::Muted)
14640                    .size(ButtonSize::Compact)
14641                    .style(ButtonStyle::Transparent)
14642                    .visible_on_hover(group_id.clone())
14643                    .on_click({
14644                        let message = diagnostic.message.clone();
14645                        move |_click, cx| {
14646                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14647                        }
14648                    })
14649                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14650            )
14651        };
14652
14653        let icon_size = buttons(&diagnostic)
14654            .into_any_element()
14655            .layout_as_root(AvailableSpace::min_size(), cx);
14656
14657        h_flex()
14658            .id(cx.block_id)
14659            .group(group_id.clone())
14660            .relative()
14661            .size_full()
14662            .block_mouse_down()
14663            .pl(cx.gutter_dimensions.width)
14664            .w(cx.max_width - cx.gutter_dimensions.full_width())
14665            .child(
14666                div()
14667                    .flex()
14668                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14669                    .flex_shrink(),
14670            )
14671            .child(buttons(&diagnostic))
14672            .child(div().flex().flex_shrink_0().child(
14673                StyledText::new(text_without_backticks.clone()).with_highlights(
14674                    &text_style,
14675                    code_ranges.iter().map(|range| {
14676                        (
14677                            range.clone(),
14678                            HighlightStyle {
14679                                font_weight: Some(FontWeight::BOLD),
14680                                ..Default::default()
14681                            },
14682                        )
14683                    }),
14684                ),
14685            ))
14686            .into_any_element()
14687    })
14688}
14689
14690fn inline_completion_edit_text(
14691    editor_snapshot: &EditorSnapshot,
14692    edits: &Vec<(Range<Anchor>, String)>,
14693    include_deletions: bool,
14694    cx: &WindowContext,
14695) -> InlineCompletionText {
14696    let edit_start = edits
14697        .first()
14698        .unwrap()
14699        .0
14700        .start
14701        .to_display_point(editor_snapshot);
14702
14703    let mut text = String::new();
14704    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14705    let mut highlights = Vec::new();
14706    for (old_range, new_text) in edits {
14707        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14708        text.extend(
14709            editor_snapshot
14710                .buffer_snapshot
14711                .chunks(offset..old_offset_range.start, false)
14712                .map(|chunk| chunk.text),
14713        );
14714        offset = old_offset_range.end;
14715
14716        let start = text.len();
14717        let color = if include_deletions && new_text.is_empty() {
14718            text.extend(
14719                editor_snapshot
14720                    .buffer_snapshot
14721                    .chunks(old_offset_range.start..offset, false)
14722                    .map(|chunk| chunk.text),
14723            );
14724            cx.theme().status().deleted_background
14725        } else {
14726            text.push_str(new_text);
14727            cx.theme().status().created_background
14728        };
14729        let end = text.len();
14730
14731        highlights.push((
14732            start..end,
14733            HighlightStyle {
14734                background_color: Some(color),
14735                ..Default::default()
14736            },
14737        ));
14738    }
14739
14740    let edit_end = edits
14741        .last()
14742        .unwrap()
14743        .0
14744        .end
14745        .to_display_point(editor_snapshot);
14746    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14747        .to_offset(editor_snapshot, Bias::Right);
14748    text.extend(
14749        editor_snapshot
14750            .buffer_snapshot
14751            .chunks(offset..end_of_line, false)
14752            .map(|chunk| chunk.text),
14753    );
14754
14755    InlineCompletionText::Edit {
14756        text: text.into(),
14757        highlights,
14758    }
14759}
14760
14761pub fn highlight_diagnostic_message(
14762    diagnostic: &Diagnostic,
14763    mut max_message_rows: Option<u8>,
14764) -> (SharedString, Vec<Range<usize>>) {
14765    let mut text_without_backticks = String::new();
14766    let mut code_ranges = Vec::new();
14767
14768    if let Some(source) = &diagnostic.source {
14769        text_without_backticks.push_str(source);
14770        code_ranges.push(0..source.len());
14771        text_without_backticks.push_str(": ");
14772    }
14773
14774    let mut prev_offset = 0;
14775    let mut in_code_block = false;
14776    let has_row_limit = max_message_rows.is_some();
14777    let mut newline_indices = diagnostic
14778        .message
14779        .match_indices('\n')
14780        .filter(|_| has_row_limit)
14781        .map(|(ix, _)| ix)
14782        .fuse()
14783        .peekable();
14784
14785    for (quote_ix, _) in diagnostic
14786        .message
14787        .match_indices('`')
14788        .chain([(diagnostic.message.len(), "")])
14789    {
14790        let mut first_newline_ix = None;
14791        let mut last_newline_ix = None;
14792        while let Some(newline_ix) = newline_indices.peek() {
14793            if *newline_ix < quote_ix {
14794                if first_newline_ix.is_none() {
14795                    first_newline_ix = Some(*newline_ix);
14796                }
14797                last_newline_ix = Some(*newline_ix);
14798
14799                if let Some(rows_left) = &mut max_message_rows {
14800                    if *rows_left == 0 {
14801                        break;
14802                    } else {
14803                        *rows_left -= 1;
14804                    }
14805                }
14806                let _ = newline_indices.next();
14807            } else {
14808                break;
14809            }
14810        }
14811        let prev_len = text_without_backticks.len();
14812        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14813        text_without_backticks.push_str(new_text);
14814        if in_code_block {
14815            code_ranges.push(prev_len..text_without_backticks.len());
14816        }
14817        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14818        in_code_block = !in_code_block;
14819        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14820            text_without_backticks.push_str("...");
14821            break;
14822        }
14823    }
14824
14825    (text_without_backticks.into(), code_ranges)
14826}
14827
14828fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14829    match severity {
14830        DiagnosticSeverity::ERROR => colors.error,
14831        DiagnosticSeverity::WARNING => colors.warning,
14832        DiagnosticSeverity::INFORMATION => colors.info,
14833        DiagnosticSeverity::HINT => colors.info,
14834        _ => colors.ignored,
14835    }
14836}
14837
14838pub fn styled_runs_for_code_label<'a>(
14839    label: &'a CodeLabel,
14840    syntax_theme: &'a theme::SyntaxTheme,
14841) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14842    let fade_out = HighlightStyle {
14843        fade_out: Some(0.35),
14844        ..Default::default()
14845    };
14846
14847    let mut prev_end = label.filter_range.end;
14848    label
14849        .runs
14850        .iter()
14851        .enumerate()
14852        .flat_map(move |(ix, (range, highlight_id))| {
14853            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14854                style
14855            } else {
14856                return Default::default();
14857            };
14858            let mut muted_style = style;
14859            muted_style.highlight(fade_out);
14860
14861            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14862            if range.start >= label.filter_range.end {
14863                if range.start > prev_end {
14864                    runs.push((prev_end..range.start, fade_out));
14865                }
14866                runs.push((range.clone(), muted_style));
14867            } else if range.end <= label.filter_range.end {
14868                runs.push((range.clone(), style));
14869            } else {
14870                runs.push((range.start..label.filter_range.end, style));
14871                runs.push((label.filter_range.end..range.end, muted_style));
14872            }
14873            prev_end = cmp::max(prev_end, range.end);
14874
14875            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14876                runs.push((prev_end..label.text.len(), fade_out));
14877            }
14878
14879            runs
14880        })
14881}
14882
14883pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14884    let mut prev_index = 0;
14885    let mut prev_codepoint: Option<char> = None;
14886    text.char_indices()
14887        .chain([(text.len(), '\0')])
14888        .filter_map(move |(index, codepoint)| {
14889            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14890            let is_boundary = index == text.len()
14891                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14892                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14893            if is_boundary {
14894                let chunk = &text[prev_index..index];
14895                prev_index = index;
14896                Some(chunk)
14897            } else {
14898                None
14899            }
14900        })
14901}
14902
14903pub trait RangeToAnchorExt: Sized {
14904    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14905
14906    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14907        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14908        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14909    }
14910}
14911
14912impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14913    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14914        let start_offset = self.start.to_offset(snapshot);
14915        let end_offset = self.end.to_offset(snapshot);
14916        if start_offset == end_offset {
14917            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14918        } else {
14919            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14920        }
14921    }
14922}
14923
14924pub trait RowExt {
14925    fn as_f32(&self) -> f32;
14926
14927    fn next_row(&self) -> Self;
14928
14929    fn previous_row(&self) -> Self;
14930
14931    fn minus(&self, other: Self) -> u32;
14932}
14933
14934impl RowExt for DisplayRow {
14935    fn as_f32(&self) -> f32 {
14936        self.0 as f32
14937    }
14938
14939    fn next_row(&self) -> Self {
14940        Self(self.0 + 1)
14941    }
14942
14943    fn previous_row(&self) -> Self {
14944        Self(self.0.saturating_sub(1))
14945    }
14946
14947    fn minus(&self, other: Self) -> u32 {
14948        self.0 - other.0
14949    }
14950}
14951
14952impl RowExt for MultiBufferRow {
14953    fn as_f32(&self) -> f32 {
14954        self.0 as f32
14955    }
14956
14957    fn next_row(&self) -> Self {
14958        Self(self.0 + 1)
14959    }
14960
14961    fn previous_row(&self) -> Self {
14962        Self(self.0.saturating_sub(1))
14963    }
14964
14965    fn minus(&self, other: Self) -> u32 {
14966        self.0 - other.0
14967    }
14968}
14969
14970trait RowRangeExt {
14971    type Row;
14972
14973    fn len(&self) -> usize;
14974
14975    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14976}
14977
14978impl RowRangeExt for Range<MultiBufferRow> {
14979    type Row = MultiBufferRow;
14980
14981    fn len(&self) -> usize {
14982        (self.end.0 - self.start.0) as usize
14983    }
14984
14985    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14986        (self.start.0..self.end.0).map(MultiBufferRow)
14987    }
14988}
14989
14990impl RowRangeExt for Range<DisplayRow> {
14991    type Row = DisplayRow;
14992
14993    fn len(&self) -> usize {
14994        (self.end.0 - self.start.0) as usize
14995    }
14996
14997    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14998        (self.start.0..self.end.0).map(DisplayRow)
14999    }
15000}
15001
15002fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15003    if hunk.diff_base_byte_range.is_empty() {
15004        DiffHunkStatus::Added
15005    } else if hunk.row_range.is_empty() {
15006        DiffHunkStatus::Removed
15007    } else {
15008        DiffHunkStatus::Modified
15009    }
15010}
15011
15012/// If select range has more than one line, we
15013/// just point the cursor to range.start.
15014fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15015    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15016        range
15017    } else {
15018        range.start..range.start
15019    }
15020}
15021
15022pub struct KillRing(ClipboardItem);
15023impl Global for KillRing {}
15024
15025const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);