editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod code_context_menus;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51use ::git::diff::DiffHunkStatus;
   52pub(crate) use actions::*;
   53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{anyhow, Context as _, Result};
   56use blink_manager::BlinkManager;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::StringMatchCandidate;
   73
   74use code_context_menus::{
   75    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   76    CompletionEntry, CompletionsMenu, ContextMenuOrigin,
   77};
   78use git::blame::GitBlame;
   79use gpui::{
   80    div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
   81    AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
   82    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
   83    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
   84    MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
   85    Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   87    WeakView, WindowContext,
   88};
   89use highlight_matching_bracket::refresh_matching_bracket_highlights;
   90use hover_popover::{hide_hover, HoverState};
   91pub(crate) use hunk_diff::HoveredHunk;
   92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CursorShape, Diagnostic, DiagnosticEntry, Documentation, IndentKind, IndentSize, Language,
  103    OffsetRangeExt, Point, Selection, SelectionGoal, TransactionId,
  104};
  105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  106use linked_editing_ranges::refresh_linked_ranges;
  107use mouse_context_menu::MouseContextMenu;
  108pub use proposed_changes_editor::{
  109    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  110};
  111use similar::{ChangeTag, TextDiff};
  112use std::iter::Peekable;
  113use task::{ResolvedTask, TaskTemplate, TaskVariables};
  114
  115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  116pub use lsp::CompletionContext;
  117use lsp::{
  118    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  119    LanguageServerId, LanguageServerName,
  120};
  121
  122use movement::TextLayoutDetails;
  123pub use multi_buffer::{
  124    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  125    ToPoint,
  126};
  127use multi_buffer::{
  128    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  129};
  130use project::{
  131    buffer_store::BufferChangeSet,
  132    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  133    project_settings::{GitGutterSetting, ProjectSettings},
  134    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  135    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  136};
  137use rand::prelude::*;
  138use rpc::{proto::*, ErrorExt};
  139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  140use selections_collection::{
  141    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  142};
  143use serde::{Deserialize, Serialize};
  144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  145use smallvec::SmallVec;
  146use snippet::Snippet;
  147use std::{
  148    any::TypeId,
  149    borrow::Cow,
  150    cell::RefCell,
  151    cmp::{self, Ordering, Reverse},
  152    mem,
  153    num::NonZeroU32,
  154    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  155    path::{Path, PathBuf},
  156    rc::Rc,
  157    sync::Arc,
  158    time::{Duration, Instant},
  159};
  160pub use sum_tree::Bias;
  161use sum_tree::TreeMap;
  162use text::{BufferId, OffsetUtf16, Rope};
  163use theme::{
  164    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  165    ThemeColors, ThemeSettings,
  166};
  167use ui::{
  168    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  169    PopoverMenuHandle, Tooltip,
  170};
  171use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  172use workspace::item::{ItemHandle, PreviewTabsSettings};
  173use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  174use workspace::{
  175    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  176};
  177use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  178
  179use crate::hover_links::{find_url, find_url_from_range};
  180use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  181
  182pub const FILE_HEADER_HEIGHT: u32 = 2;
  183pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  184pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  185pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  186const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  187const MAX_LINE_LEN: usize = 1024;
  188const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  189const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  190pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  191#[doc(hidden)]
  192pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  193
  194pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  195pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  196
  197pub fn render_parsed_markdown(
  198    element_id: impl Into<ElementId>,
  199    parsed: &language::ParsedMarkdown,
  200    editor_style: &EditorStyle,
  201    workspace: Option<WeakView<Workspace>>,
  202    cx: &mut WindowContext,
  203) -> InteractiveText {
  204    let code_span_background_color = cx
  205        .theme()
  206        .colors()
  207        .editor_document_highlight_read_background;
  208
  209    let highlights = gpui::combine_highlights(
  210        parsed.highlights.iter().filter_map(|(range, highlight)| {
  211            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  212            Some((range.clone(), highlight))
  213        }),
  214        parsed
  215            .regions
  216            .iter()
  217            .zip(&parsed.region_ranges)
  218            .filter_map(|(region, range)| {
  219                if region.code {
  220                    Some((
  221                        range.clone(),
  222                        HighlightStyle {
  223                            background_color: Some(code_span_background_color),
  224                            ..Default::default()
  225                        },
  226                    ))
  227                } else {
  228                    None
  229                }
  230            }),
  231    );
  232
  233    let mut links = Vec::new();
  234    let mut link_ranges = Vec::new();
  235    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  236        if let Some(link) = region.link.clone() {
  237            links.push(link);
  238            link_ranges.push(range.clone());
  239        }
  240    }
  241
  242    InteractiveText::new(
  243        element_id,
  244        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  245    )
  246    .on_click(link_ranges, move |clicked_range_ix, cx| {
  247        match &links[clicked_range_ix] {
  248            markdown::Link::Web { url } => cx.open_url(url),
  249            markdown::Link::Path { path } => {
  250                if let Some(workspace) = &workspace {
  251                    _ = workspace.update(cx, |workspace, cx| {
  252                        workspace.open_abs_path(path.clone(), false, cx).detach();
  253                    });
  254                }
  255            }
  256        }
  257    })
  258}
  259
  260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  261pub enum InlayId {
  262    InlineCompletion(usize),
  263    Hint(usize),
  264}
  265
  266impl InlayId {
  267    fn id(&self) -> usize {
  268        match self {
  269            Self::InlineCompletion(id) => *id,
  270            Self::Hint(id) => *id,
  271        }
  272    }
  273}
  274
  275enum DiffRowHighlight {}
  276enum DocumentHighlightRead {}
  277enum DocumentHighlightWrite {}
  278enum InputComposition {}
  279
  280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  281pub enum Navigated {
  282    Yes,
  283    No,
  284}
  285
  286impl Navigated {
  287    pub fn from_bool(yes: bool) -> Navigated {
  288        if yes {
  289            Navigated::Yes
  290        } else {
  291            Navigated::No
  292        }
  293    }
  294}
  295
  296pub fn init_settings(cx: &mut AppContext) {
  297    EditorSettings::register(cx);
  298}
  299
  300pub fn init(cx: &mut AppContext) {
  301    init_settings(cx);
  302
  303    workspace::register_project_item::<Editor>(cx);
  304    workspace::FollowableViewRegistry::register::<Editor>(cx);
  305    workspace::register_serializable_item::<Editor>(cx);
  306
  307    cx.observe_new_views(
  308        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  309            workspace.register_action(Editor::new_file);
  310            workspace.register_action(Editor::new_file_vertical);
  311            workspace.register_action(Editor::new_file_horizontal);
  312        },
  313    )
  314    .detach();
  315
  316    cx.on_action(move |_: &workspace::NewFile, cx| {
  317        let app_state = workspace::AppState::global(cx);
  318        if let Some(app_state) = app_state.upgrade() {
  319            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  320                Editor::new_file(workspace, &Default::default(), cx)
  321            })
  322            .detach();
  323        }
  324    });
  325    cx.on_action(move |_: &workspace::NewWindow, cx| {
  326        let app_state = workspace::AppState::global(cx);
  327        if let Some(app_state) = app_state.upgrade() {
  328            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  329                Editor::new_file(workspace, &Default::default(), cx)
  330            })
  331            .detach();
  332        }
  333    });
  334    git::project_diff::init(cx);
  335}
  336
  337pub struct SearchWithinRange;
  338
  339trait InvalidationRegion {
  340    fn ranges(&self) -> &[Range<Anchor>];
  341}
  342
  343#[derive(Clone, Debug, PartialEq)]
  344pub enum SelectPhase {
  345    Begin {
  346        position: DisplayPoint,
  347        add: bool,
  348        click_count: usize,
  349    },
  350    BeginColumnar {
  351        position: DisplayPoint,
  352        reset: bool,
  353        goal_column: u32,
  354    },
  355    Extend {
  356        position: DisplayPoint,
  357        click_count: usize,
  358    },
  359    Update {
  360        position: DisplayPoint,
  361        goal_column: u32,
  362        scroll_delta: gpui::Point<f32>,
  363    },
  364    End,
  365}
  366
  367#[derive(Clone, Debug)]
  368pub enum SelectMode {
  369    Character,
  370    Word(Range<Anchor>),
  371    Line(Range<Anchor>),
  372    All,
  373}
  374
  375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  376pub enum EditorMode {
  377    SingleLine { auto_width: bool },
  378    AutoHeight { max_lines: usize },
  379    Full,
  380}
  381
  382#[derive(Copy, Clone, Debug)]
  383pub enum SoftWrap {
  384    /// Prefer not to wrap at all.
  385    ///
  386    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  387    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  388    GitDiff,
  389    /// Prefer a single line generally, unless an overly long line is encountered.
  390    None,
  391    /// Soft wrap lines that exceed the editor width.
  392    EditorWidth,
  393    /// Soft wrap lines at the preferred line length.
  394    Column(u32),
  395    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  396    Bounded(u32),
  397}
  398
  399#[derive(Clone)]
  400pub struct EditorStyle {
  401    pub background: Hsla,
  402    pub local_player: PlayerColor,
  403    pub text: TextStyle,
  404    pub scrollbar_width: Pixels,
  405    pub syntax: Arc<SyntaxTheme>,
  406    pub status: StatusColors,
  407    pub inlay_hints_style: HighlightStyle,
  408    pub inline_completion_styles: InlineCompletionStyles,
  409    pub unnecessary_code_fade: f32,
  410}
  411
  412impl Default for EditorStyle {
  413    fn default() -> Self {
  414        Self {
  415            background: Hsla::default(),
  416            local_player: PlayerColor::default(),
  417            text: TextStyle::default(),
  418            scrollbar_width: Pixels::default(),
  419            syntax: Default::default(),
  420            // HACK: Status colors don't have a real default.
  421            // We should look into removing the status colors from the editor
  422            // style and retrieve them directly from the theme.
  423            status: StatusColors::dark(),
  424            inlay_hints_style: HighlightStyle::default(),
  425            inline_completion_styles: InlineCompletionStyles {
  426                insertion: HighlightStyle::default(),
  427                whitespace: HighlightStyle::default(),
  428            },
  429            unnecessary_code_fade: Default::default(),
  430        }
  431    }
  432}
  433
  434pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  435    let show_background = language_settings::language_settings(None, None, cx)
  436        .inlay_hints
  437        .show_background;
  438
  439    HighlightStyle {
  440        color: Some(cx.theme().status().hint),
  441        background_color: show_background.then(|| cx.theme().status().hint_background),
  442        ..HighlightStyle::default()
  443    }
  444}
  445
  446pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
  447    InlineCompletionStyles {
  448        insertion: HighlightStyle {
  449            color: Some(cx.theme().status().predictive),
  450            ..HighlightStyle::default()
  451        },
  452        whitespace: HighlightStyle {
  453            background_color: Some(cx.theme().status().created_background),
  454            ..HighlightStyle::default()
  455        },
  456    }
  457}
  458
  459type CompletionId = usize;
  460
  461#[derive(Debug, Clone)]
  462struct InlineCompletionMenuHint {
  463    provider_name: &'static str,
  464    text: InlineCompletionText,
  465}
  466
  467#[derive(Clone, Debug)]
  468enum InlineCompletionText {
  469    Move(SharedString),
  470    Edit {
  471        text: SharedString,
  472        highlights: Vec<(Range<usize>, HighlightStyle)>,
  473    },
  474}
  475
  476enum InlineCompletion {
  477    Edit(Vec<(Range<Anchor>, String)>),
  478    Move(Anchor),
  479}
  480
  481struct InlineCompletionState {
  482    inlay_ids: Vec<InlayId>,
  483    completion: InlineCompletion,
  484    invalidation_range: Range<Anchor>,
  485}
  486
  487enum InlineCompletionHighlight {}
  488
  489#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  490struct EditorActionId(usize);
  491
  492impl EditorActionId {
  493    pub fn post_inc(&mut self) -> Self {
  494        let answer = self.0;
  495
  496        *self = Self(answer + 1);
  497
  498        Self(answer)
  499    }
  500}
  501
  502// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  503// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  504
  505type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  506type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  507
  508#[derive(Default)]
  509struct ScrollbarMarkerState {
  510    scrollbar_size: Size<Pixels>,
  511    dirty: bool,
  512    markers: Arc<[PaintQuad]>,
  513    pending_refresh: Option<Task<Result<()>>>,
  514}
  515
  516impl ScrollbarMarkerState {
  517    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  518        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  519    }
  520}
  521
  522#[derive(Clone, Debug)]
  523struct RunnableTasks {
  524    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  525    offset: MultiBufferOffset,
  526    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  527    column: u32,
  528    // Values of all named captures, including those starting with '_'
  529    extra_variables: HashMap<String, String>,
  530    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  531    context_range: Range<BufferOffset>,
  532}
  533
  534impl RunnableTasks {
  535    fn resolve<'a>(
  536        &'a self,
  537        cx: &'a task::TaskContext,
  538    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  539        self.templates.iter().filter_map(|(kind, template)| {
  540            template
  541                .resolve_task(&kind.to_id_base(), cx)
  542                .map(|task| (kind.clone(), task))
  543        })
  544    }
  545}
  546
  547#[derive(Clone)]
  548struct ResolvedTasks {
  549    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  550    position: Anchor,
  551}
  552#[derive(Copy, Clone, Debug)]
  553struct MultiBufferOffset(usize);
  554#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  555struct BufferOffset(usize);
  556
  557// Addons allow storing per-editor state in other crates (e.g. Vim)
  558pub trait Addon: 'static {
  559    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  560
  561    fn to_any(&self) -> &dyn std::any::Any;
  562}
  563
  564#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  565pub enum IsVimMode {
  566    Yes,
  567    No,
  568}
  569
  570/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  571///
  572/// See the [module level documentation](self) for more information.
  573pub struct Editor {
  574    focus_handle: FocusHandle,
  575    last_focused_descendant: Option<WeakFocusHandle>,
  576    /// The text buffer being edited
  577    buffer: Model<MultiBuffer>,
  578    /// Map of how text in the buffer should be displayed.
  579    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  580    pub display_map: Model<DisplayMap>,
  581    pub selections: SelectionsCollection,
  582    pub scroll_manager: ScrollManager,
  583    /// When inline assist editors are linked, they all render cursors because
  584    /// typing enters text into each of them, even the ones that aren't focused.
  585    pub(crate) show_cursor_when_unfocused: bool,
  586    columnar_selection_tail: Option<Anchor>,
  587    add_selections_state: Option<AddSelectionsState>,
  588    select_next_state: Option<SelectNextState>,
  589    select_prev_state: Option<SelectNextState>,
  590    selection_history: SelectionHistory,
  591    autoclose_regions: Vec<AutocloseRegion>,
  592    snippet_stack: InvalidationStack<SnippetState>,
  593    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  594    ime_transaction: Option<TransactionId>,
  595    active_diagnostics: Option<ActiveDiagnosticGroup>,
  596    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  597
  598    project: Option<Model<Project>>,
  599    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  600    completion_provider: Option<Box<dyn CompletionProvider>>,
  601    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  602    blink_manager: Model<BlinkManager>,
  603    show_cursor_names: bool,
  604    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  605    pub show_local_selections: bool,
  606    mode: EditorMode,
  607    show_breadcrumbs: bool,
  608    show_gutter: bool,
  609    show_scrollbars: bool,
  610    show_line_numbers: Option<bool>,
  611    use_relative_line_numbers: Option<bool>,
  612    show_git_diff_gutter: Option<bool>,
  613    show_code_actions: Option<bool>,
  614    show_runnables: Option<bool>,
  615    show_wrap_guides: Option<bool>,
  616    show_indent_guides: Option<bool>,
  617    placeholder_text: Option<Arc<str>>,
  618    highlight_order: usize,
  619    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  620    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  621    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  622    scrollbar_marker_state: ScrollbarMarkerState,
  623    active_indent_guides_state: ActiveIndentGuidesState,
  624    nav_history: Option<ItemNavHistory>,
  625    context_menu: RefCell<Option<CodeContextMenu>>,
  626    mouse_context_menu: Option<MouseContextMenu>,
  627    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  628    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  629    signature_help_state: SignatureHelpState,
  630    auto_signature_help: Option<bool>,
  631    find_all_references_task_sources: Vec<Anchor>,
  632    next_completion_id: CompletionId,
  633    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  634    code_actions_task: Option<Task<Result<()>>>,
  635    document_highlights_task: Option<Task<()>>,
  636    linked_editing_range_task: Option<Task<Option<()>>>,
  637    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  638    pending_rename: Option<RenameState>,
  639    searchable: bool,
  640    cursor_shape: CursorShape,
  641    current_line_highlight: Option<CurrentLineHighlight>,
  642    collapse_matches: bool,
  643    autoindent_mode: Option<AutoindentMode>,
  644    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  645    input_enabled: bool,
  646    use_modal_editing: bool,
  647    read_only: bool,
  648    leader_peer_id: Option<PeerId>,
  649    remote_id: Option<ViewId>,
  650    hover_state: HoverState,
  651    gutter_hovered: bool,
  652    hovered_link_state: Option<HoveredLinkState>,
  653    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  654    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  655    active_inline_completion: Option<InlineCompletionState>,
  656    // enable_inline_completions is a switch that Vim can use to disable
  657    // inline completions based on its mode.
  658    enable_inline_completions: bool,
  659    show_inline_completions_override: Option<bool>,
  660    inlay_hint_cache: InlayHintCache,
  661    diff_map: DiffMap,
  662    next_inlay_id: usize,
  663    _subscriptions: Vec<Subscription>,
  664    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  665    gutter_dimensions: GutterDimensions,
  666    style: Option<EditorStyle>,
  667    text_style_refinement: Option<TextStyleRefinement>,
  668    next_editor_action_id: EditorActionId,
  669    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  670    use_autoclose: bool,
  671    use_auto_surround: bool,
  672    auto_replace_emoji_shortcode: bool,
  673    show_git_blame_gutter: bool,
  674    show_git_blame_inline: bool,
  675    show_git_blame_inline_delay_task: Option<Task<()>>,
  676    git_blame_inline_enabled: bool,
  677    serialize_dirty_buffers: bool,
  678    show_selection_menu: Option<bool>,
  679    blame: Option<Model<GitBlame>>,
  680    blame_subscription: Option<Subscription>,
  681    custom_context_menu: Option<
  682        Box<
  683            dyn 'static
  684                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  685        >,
  686    >,
  687    last_bounds: Option<Bounds<Pixels>>,
  688    expect_bounds_change: Option<Bounds<Pixels>>,
  689    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  690    tasks_update_task: Option<Task<()>>,
  691    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  692    breadcrumb_header: Option<String>,
  693    focused_block: Option<FocusedBlock>,
  694    next_scroll_position: NextScrollCursorCenterTopBottom,
  695    addons: HashMap<TypeId, Box<dyn Addon>>,
  696    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  697    toggle_fold_multiple_buffers: Task<()>,
  698    _scroll_cursor_center_top_bottom_task: Task<()>,
  699}
  700
  701#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  702enum NextScrollCursorCenterTopBottom {
  703    #[default]
  704    Center,
  705    Top,
  706    Bottom,
  707}
  708
  709impl NextScrollCursorCenterTopBottom {
  710    fn next(&self) -> Self {
  711        match self {
  712            Self::Center => Self::Top,
  713            Self::Top => Self::Bottom,
  714            Self::Bottom => Self::Center,
  715        }
  716    }
  717}
  718
  719#[derive(Clone)]
  720pub struct EditorSnapshot {
  721    pub mode: EditorMode,
  722    show_gutter: bool,
  723    show_line_numbers: Option<bool>,
  724    show_git_diff_gutter: Option<bool>,
  725    show_code_actions: Option<bool>,
  726    show_runnables: Option<bool>,
  727    git_blame_gutter_max_author_length: Option<usize>,
  728    pub display_snapshot: DisplaySnapshot,
  729    pub placeholder_text: Option<Arc<str>>,
  730    diff_map: DiffMapSnapshot,
  731    is_focused: bool,
  732    scroll_anchor: ScrollAnchor,
  733    ongoing_scroll: OngoingScroll,
  734    current_line_highlight: CurrentLineHighlight,
  735    gutter_hovered: bool,
  736}
  737
  738const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  739
  740#[derive(Default, Debug, Clone, Copy)]
  741pub struct GutterDimensions {
  742    pub left_padding: Pixels,
  743    pub right_padding: Pixels,
  744    pub width: Pixels,
  745    pub margin: Pixels,
  746    pub git_blame_entries_width: Option<Pixels>,
  747}
  748
  749impl GutterDimensions {
  750    /// The full width of the space taken up by the gutter.
  751    pub fn full_width(&self) -> Pixels {
  752        self.margin + self.width
  753    }
  754
  755    /// The width of the space reserved for the fold indicators,
  756    /// use alongside 'justify_end' and `gutter_width` to
  757    /// right align content with the line numbers
  758    pub fn fold_area_width(&self) -> Pixels {
  759        self.margin + self.right_padding
  760    }
  761}
  762
  763#[derive(Debug)]
  764pub struct RemoteSelection {
  765    pub replica_id: ReplicaId,
  766    pub selection: Selection<Anchor>,
  767    pub cursor_shape: CursorShape,
  768    pub peer_id: PeerId,
  769    pub line_mode: bool,
  770    pub participant_index: Option<ParticipantIndex>,
  771    pub user_name: Option<SharedString>,
  772}
  773
  774#[derive(Clone, Debug)]
  775struct SelectionHistoryEntry {
  776    selections: Arc<[Selection<Anchor>]>,
  777    select_next_state: Option<SelectNextState>,
  778    select_prev_state: Option<SelectNextState>,
  779    add_selections_state: Option<AddSelectionsState>,
  780}
  781
  782enum SelectionHistoryMode {
  783    Normal,
  784    Undoing,
  785    Redoing,
  786}
  787
  788#[derive(Clone, PartialEq, Eq, Hash)]
  789struct HoveredCursor {
  790    replica_id: u16,
  791    selection_id: usize,
  792}
  793
  794impl Default for SelectionHistoryMode {
  795    fn default() -> Self {
  796        Self::Normal
  797    }
  798}
  799
  800#[derive(Default)]
  801struct SelectionHistory {
  802    #[allow(clippy::type_complexity)]
  803    selections_by_transaction:
  804        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  805    mode: SelectionHistoryMode,
  806    undo_stack: VecDeque<SelectionHistoryEntry>,
  807    redo_stack: VecDeque<SelectionHistoryEntry>,
  808}
  809
  810impl SelectionHistory {
  811    fn insert_transaction(
  812        &mut self,
  813        transaction_id: TransactionId,
  814        selections: Arc<[Selection<Anchor>]>,
  815    ) {
  816        self.selections_by_transaction
  817            .insert(transaction_id, (selections, None));
  818    }
  819
  820    #[allow(clippy::type_complexity)]
  821    fn transaction(
  822        &self,
  823        transaction_id: TransactionId,
  824    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  825        self.selections_by_transaction.get(&transaction_id)
  826    }
  827
  828    #[allow(clippy::type_complexity)]
  829    fn transaction_mut(
  830        &mut self,
  831        transaction_id: TransactionId,
  832    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  833        self.selections_by_transaction.get_mut(&transaction_id)
  834    }
  835
  836    fn push(&mut self, entry: SelectionHistoryEntry) {
  837        if !entry.selections.is_empty() {
  838            match self.mode {
  839                SelectionHistoryMode::Normal => {
  840                    self.push_undo(entry);
  841                    self.redo_stack.clear();
  842                }
  843                SelectionHistoryMode::Undoing => self.push_redo(entry),
  844                SelectionHistoryMode::Redoing => self.push_undo(entry),
  845            }
  846        }
  847    }
  848
  849    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  850        if self
  851            .undo_stack
  852            .back()
  853            .map_or(true, |e| e.selections != entry.selections)
  854        {
  855            self.undo_stack.push_back(entry);
  856            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  857                self.undo_stack.pop_front();
  858            }
  859        }
  860    }
  861
  862    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  863        if self
  864            .redo_stack
  865            .back()
  866            .map_or(true, |e| e.selections != entry.selections)
  867        {
  868            self.redo_stack.push_back(entry);
  869            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  870                self.redo_stack.pop_front();
  871            }
  872        }
  873    }
  874}
  875
  876struct RowHighlight {
  877    index: usize,
  878    range: Range<Anchor>,
  879    color: Hsla,
  880    should_autoscroll: bool,
  881}
  882
  883#[derive(Clone, Debug)]
  884struct AddSelectionsState {
  885    above: bool,
  886    stack: Vec<usize>,
  887}
  888
  889#[derive(Clone)]
  890struct SelectNextState {
  891    query: AhoCorasick,
  892    wordwise: bool,
  893    done: bool,
  894}
  895
  896impl std::fmt::Debug for SelectNextState {
  897    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  898        f.debug_struct(std::any::type_name::<Self>())
  899            .field("wordwise", &self.wordwise)
  900            .field("done", &self.done)
  901            .finish()
  902    }
  903}
  904
  905#[derive(Debug)]
  906struct AutocloseRegion {
  907    selection_id: usize,
  908    range: Range<Anchor>,
  909    pair: BracketPair,
  910}
  911
  912#[derive(Debug)]
  913struct SnippetState {
  914    ranges: Vec<Vec<Range<Anchor>>>,
  915    active_index: usize,
  916    choices: Vec<Option<Vec<String>>>,
  917}
  918
  919#[doc(hidden)]
  920pub struct RenameState {
  921    pub range: Range<Anchor>,
  922    pub old_name: Arc<str>,
  923    pub editor: View<Editor>,
  924    block_id: CustomBlockId,
  925}
  926
  927struct InvalidationStack<T>(Vec<T>);
  928
  929struct RegisteredInlineCompletionProvider {
  930    provider: Arc<dyn InlineCompletionProviderHandle>,
  931    _subscription: Subscription,
  932}
  933
  934#[derive(Debug)]
  935struct ActiveDiagnosticGroup {
  936    primary_range: Range<Anchor>,
  937    primary_message: String,
  938    group_id: usize,
  939    blocks: HashMap<CustomBlockId, Diagnostic>,
  940    is_valid: bool,
  941}
  942
  943#[derive(Serialize, Deserialize, Clone, Debug)]
  944pub struct ClipboardSelection {
  945    pub len: usize,
  946    pub is_entire_line: bool,
  947    pub first_line_indent: u32,
  948}
  949
  950#[derive(Debug)]
  951pub(crate) struct NavigationData {
  952    cursor_anchor: Anchor,
  953    cursor_position: Point,
  954    scroll_anchor: ScrollAnchor,
  955    scroll_top_row: u32,
  956}
  957
  958#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  959pub enum GotoDefinitionKind {
  960    Symbol,
  961    Declaration,
  962    Type,
  963    Implementation,
  964}
  965
  966#[derive(Debug, Clone)]
  967enum InlayHintRefreshReason {
  968    Toggle(bool),
  969    SettingsChange(InlayHintSettings),
  970    NewLinesShown,
  971    BufferEdited(HashSet<Arc<Language>>),
  972    RefreshRequested,
  973    ExcerptsRemoved(Vec<ExcerptId>),
  974}
  975
  976impl InlayHintRefreshReason {
  977    fn description(&self) -> &'static str {
  978        match self {
  979            Self::Toggle(_) => "toggle",
  980            Self::SettingsChange(_) => "settings change",
  981            Self::NewLinesShown => "new lines shown",
  982            Self::BufferEdited(_) => "buffer edited",
  983            Self::RefreshRequested => "refresh requested",
  984            Self::ExcerptsRemoved(_) => "excerpts removed",
  985        }
  986    }
  987}
  988
  989pub enum FormatTarget {
  990    Buffers,
  991    Ranges(Vec<Range<MultiBufferPoint>>),
  992}
  993
  994pub(crate) struct FocusedBlock {
  995    id: BlockId,
  996    focus_handle: WeakFocusHandle,
  997}
  998
  999#[derive(Clone)]
 1000enum JumpData {
 1001    MultiBufferRow {
 1002        row: MultiBufferRow,
 1003        line_offset_from_top: u32,
 1004    },
 1005    MultiBufferPoint {
 1006        excerpt_id: ExcerptId,
 1007        position: Point,
 1008        anchor: text::Anchor,
 1009        line_offset_from_top: u32,
 1010    },
 1011}
 1012
 1013impl Editor {
 1014    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1015        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1016        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1017        Self::new(
 1018            EditorMode::SingleLine { auto_width: false },
 1019            buffer,
 1020            None,
 1021            false,
 1022            cx,
 1023        )
 1024    }
 1025
 1026    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1027        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1028        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1029        Self::new(EditorMode::Full, buffer, None, false, cx)
 1030    }
 1031
 1032    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1033        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1034        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1035        Self::new(
 1036            EditorMode::SingleLine { auto_width: true },
 1037            buffer,
 1038            None,
 1039            false,
 1040            cx,
 1041        )
 1042    }
 1043
 1044    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1045        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1046        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1047        Self::new(
 1048            EditorMode::AutoHeight { max_lines },
 1049            buffer,
 1050            None,
 1051            false,
 1052            cx,
 1053        )
 1054    }
 1055
 1056    pub fn for_buffer(
 1057        buffer: Model<Buffer>,
 1058        project: Option<Model<Project>>,
 1059        cx: &mut ViewContext<Self>,
 1060    ) -> Self {
 1061        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1062        Self::new(EditorMode::Full, buffer, project, false, cx)
 1063    }
 1064
 1065    pub fn for_multibuffer(
 1066        buffer: Model<MultiBuffer>,
 1067        project: Option<Model<Project>>,
 1068        show_excerpt_controls: bool,
 1069        cx: &mut ViewContext<Self>,
 1070    ) -> Self {
 1071        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1072    }
 1073
 1074    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1075        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1076        let mut clone = Self::new(
 1077            self.mode,
 1078            self.buffer.clone(),
 1079            self.project.clone(),
 1080            show_excerpt_controls,
 1081            cx,
 1082        );
 1083        self.display_map.update(cx, |display_map, cx| {
 1084            let snapshot = display_map.snapshot(cx);
 1085            clone.display_map.update(cx, |display_map, cx| {
 1086                display_map.set_state(&snapshot, cx);
 1087            });
 1088        });
 1089        clone.selections.clone_state(&self.selections);
 1090        clone.scroll_manager.clone_state(&self.scroll_manager);
 1091        clone.searchable = self.searchable;
 1092        clone
 1093    }
 1094
 1095    pub fn new(
 1096        mode: EditorMode,
 1097        buffer: Model<MultiBuffer>,
 1098        project: Option<Model<Project>>,
 1099        show_excerpt_controls: bool,
 1100        cx: &mut ViewContext<Self>,
 1101    ) -> Self {
 1102        let style = cx.text_style();
 1103        let font_size = style.font_size.to_pixels(cx.rem_size());
 1104        let editor = cx.view().downgrade();
 1105        let fold_placeholder = FoldPlaceholder {
 1106            constrain_width: true,
 1107            render: Arc::new(move |fold_id, fold_range, cx| {
 1108                let editor = editor.clone();
 1109                div()
 1110                    .id(fold_id)
 1111                    .bg(cx.theme().colors().ghost_element_background)
 1112                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1113                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1114                    .rounded_sm()
 1115                    .size_full()
 1116                    .cursor_pointer()
 1117                    .child("")
 1118                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1119                    .on_click(move |_, cx| {
 1120                        editor
 1121                            .update(cx, |editor, cx| {
 1122                                editor.unfold_ranges(
 1123                                    &[fold_range.start..fold_range.end],
 1124                                    true,
 1125                                    false,
 1126                                    cx,
 1127                                );
 1128                                cx.stop_propagation();
 1129                            })
 1130                            .ok();
 1131                    })
 1132                    .into_any()
 1133            }),
 1134            merge_adjacent: true,
 1135            ..Default::default()
 1136        };
 1137        let display_map = cx.new_model(|cx| {
 1138            DisplayMap::new(
 1139                buffer.clone(),
 1140                style.font(),
 1141                font_size,
 1142                None,
 1143                show_excerpt_controls,
 1144                FILE_HEADER_HEIGHT,
 1145                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1146                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1147                fold_placeholder,
 1148                cx,
 1149            )
 1150        });
 1151
 1152        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1153
 1154        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1155
 1156        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1157            .then(|| language_settings::SoftWrap::None);
 1158
 1159        let mut project_subscriptions = Vec::new();
 1160        if mode == EditorMode::Full {
 1161            if let Some(project) = project.as_ref() {
 1162                if buffer.read(cx).is_singleton() {
 1163                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1164                        cx.emit(EditorEvent::TitleChanged);
 1165                    }));
 1166                }
 1167                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1168                    if let project::Event::RefreshInlayHints = event {
 1169                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1170                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1171                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1172                            let focus_handle = editor.focus_handle(cx);
 1173                            if focus_handle.is_focused(cx) {
 1174                                let snapshot = buffer.read(cx).snapshot();
 1175                                for (range, snippet) in snippet_edits {
 1176                                    let editor_range =
 1177                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1178                                    editor
 1179                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1180                                        .ok();
 1181                                }
 1182                            }
 1183                        }
 1184                    }
 1185                }));
 1186                if let Some(task_inventory) = project
 1187                    .read(cx)
 1188                    .task_store()
 1189                    .read(cx)
 1190                    .task_inventory()
 1191                    .cloned()
 1192                {
 1193                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1194                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1195                    }));
 1196                }
 1197            }
 1198        }
 1199
 1200        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1201
 1202        let inlay_hint_settings =
 1203            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1204        let focus_handle = cx.focus_handle();
 1205        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1206        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1207            .detach();
 1208        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1209            .detach();
 1210        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1211
 1212        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1213            Some(false)
 1214        } else {
 1215            None
 1216        };
 1217
 1218        let mut code_action_providers = Vec::new();
 1219        if let Some(project) = project.clone() {
 1220            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1221            code_action_providers.push(Rc::new(project) as Rc<_>);
 1222        }
 1223
 1224        let mut this = Self {
 1225            focus_handle,
 1226            show_cursor_when_unfocused: false,
 1227            last_focused_descendant: None,
 1228            buffer: buffer.clone(),
 1229            display_map: display_map.clone(),
 1230            selections,
 1231            scroll_manager: ScrollManager::new(cx),
 1232            columnar_selection_tail: None,
 1233            add_selections_state: None,
 1234            select_next_state: None,
 1235            select_prev_state: None,
 1236            selection_history: Default::default(),
 1237            autoclose_regions: Default::default(),
 1238            snippet_stack: Default::default(),
 1239            select_larger_syntax_node_stack: Vec::new(),
 1240            ime_transaction: Default::default(),
 1241            active_diagnostics: None,
 1242            soft_wrap_mode_override,
 1243            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1244            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1245            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1246            project,
 1247            blink_manager: blink_manager.clone(),
 1248            show_local_selections: true,
 1249            show_scrollbars: true,
 1250            mode,
 1251            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1252            show_gutter: mode == EditorMode::Full,
 1253            show_line_numbers: None,
 1254            use_relative_line_numbers: None,
 1255            show_git_diff_gutter: None,
 1256            show_code_actions: None,
 1257            show_runnables: None,
 1258            show_wrap_guides: None,
 1259            show_indent_guides,
 1260            placeholder_text: None,
 1261            highlight_order: 0,
 1262            highlighted_rows: HashMap::default(),
 1263            background_highlights: Default::default(),
 1264            gutter_highlights: TreeMap::default(),
 1265            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1266            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1267            nav_history: None,
 1268            context_menu: RefCell::new(None),
 1269            mouse_context_menu: None,
 1270            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1271            completion_tasks: Default::default(),
 1272            signature_help_state: SignatureHelpState::default(),
 1273            auto_signature_help: None,
 1274            find_all_references_task_sources: Vec::new(),
 1275            next_completion_id: 0,
 1276            next_inlay_id: 0,
 1277            code_action_providers,
 1278            available_code_actions: Default::default(),
 1279            code_actions_task: Default::default(),
 1280            document_highlights_task: Default::default(),
 1281            linked_editing_range_task: Default::default(),
 1282            pending_rename: Default::default(),
 1283            searchable: true,
 1284            cursor_shape: EditorSettings::get_global(cx)
 1285                .cursor_shape
 1286                .unwrap_or_default(),
 1287            current_line_highlight: None,
 1288            autoindent_mode: Some(AutoindentMode::EachLine),
 1289            collapse_matches: false,
 1290            workspace: None,
 1291            input_enabled: true,
 1292            use_modal_editing: mode == EditorMode::Full,
 1293            read_only: false,
 1294            use_autoclose: true,
 1295            use_auto_surround: true,
 1296            auto_replace_emoji_shortcode: false,
 1297            leader_peer_id: None,
 1298            remote_id: None,
 1299            hover_state: Default::default(),
 1300            hovered_link_state: Default::default(),
 1301            inline_completion_provider: None,
 1302            active_inline_completion: None,
 1303            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1304            diff_map: DiffMap::default(),
 1305            gutter_hovered: false,
 1306            pixel_position_of_newest_cursor: None,
 1307            last_bounds: None,
 1308            expect_bounds_change: None,
 1309            gutter_dimensions: GutterDimensions::default(),
 1310            style: None,
 1311            show_cursor_names: false,
 1312            hovered_cursors: Default::default(),
 1313            next_editor_action_id: EditorActionId::default(),
 1314            editor_actions: Rc::default(),
 1315            show_inline_completions_override: None,
 1316            enable_inline_completions: true,
 1317            custom_context_menu: None,
 1318            show_git_blame_gutter: false,
 1319            show_git_blame_inline: false,
 1320            show_selection_menu: None,
 1321            show_git_blame_inline_delay_task: None,
 1322            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1323            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1324                .session
 1325                .restore_unsaved_buffers,
 1326            blame: None,
 1327            blame_subscription: None,
 1328            tasks: Default::default(),
 1329            _subscriptions: vec![
 1330                cx.observe(&buffer, Self::on_buffer_changed),
 1331                cx.subscribe(&buffer, Self::on_buffer_event),
 1332                cx.observe(&display_map, Self::on_display_map_changed),
 1333                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1334                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1335                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1336                cx.observe_window_activation(|editor, cx| {
 1337                    let active = cx.is_window_active();
 1338                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1339                        if active {
 1340                            blink_manager.enable(cx);
 1341                        } else {
 1342                            blink_manager.disable(cx);
 1343                        }
 1344                    });
 1345                }),
 1346            ],
 1347            tasks_update_task: None,
 1348            linked_edit_ranges: Default::default(),
 1349            previous_search_ranges: None,
 1350            breadcrumb_header: None,
 1351            focused_block: None,
 1352            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1353            addons: HashMap::default(),
 1354            registered_buffers: HashMap::default(),
 1355            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1356            toggle_fold_multiple_buffers: Task::ready(()),
 1357            text_style_refinement: None,
 1358        };
 1359        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1360        this._subscriptions.extend(project_subscriptions);
 1361
 1362        this.end_selection(cx);
 1363        this.scroll_manager.show_scrollbar(cx);
 1364
 1365        if mode == EditorMode::Full {
 1366            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1367            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1368
 1369            if this.git_blame_inline_enabled {
 1370                this.git_blame_inline_enabled = true;
 1371                this.start_git_blame_inline(false, cx);
 1372            }
 1373
 1374            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1375                if let Some(project) = this.project.as_ref() {
 1376                    let lsp_store = project.read(cx).lsp_store();
 1377                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1378                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1379                    });
 1380                    this.registered_buffers
 1381                        .insert(buffer.read(cx).remote_id(), handle);
 1382                }
 1383            }
 1384        }
 1385
 1386        this.report_editor_event("Editor Opened", None, cx);
 1387        this
 1388    }
 1389
 1390    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1391        self.mouse_context_menu
 1392            .as_ref()
 1393            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1394    }
 1395
 1396    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1397        let mut key_context = KeyContext::new_with_defaults();
 1398        key_context.add("Editor");
 1399        let mode = match self.mode {
 1400            EditorMode::SingleLine { .. } => "single_line",
 1401            EditorMode::AutoHeight { .. } => "auto_height",
 1402            EditorMode::Full => "full",
 1403        };
 1404
 1405        if EditorSettings::jupyter_enabled(cx) {
 1406            key_context.add("jupyter");
 1407        }
 1408
 1409        key_context.set("mode", mode);
 1410        if self.pending_rename.is_some() {
 1411            key_context.add("renaming");
 1412        }
 1413        match self.context_menu.borrow().as_ref() {
 1414            Some(CodeContextMenu::Completions(_)) => {
 1415                key_context.add("menu");
 1416                key_context.add("showing_completions")
 1417            }
 1418            Some(CodeContextMenu::CodeActions(_)) => {
 1419                key_context.add("menu");
 1420                key_context.add("showing_code_actions")
 1421            }
 1422            None => {}
 1423        }
 1424
 1425        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1426        if !self.focus_handle(cx).contains_focused(cx)
 1427            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1428        {
 1429            for addon in self.addons.values() {
 1430                addon.extend_key_context(&mut key_context, cx)
 1431            }
 1432        }
 1433
 1434        if let Some(extension) = self
 1435            .buffer
 1436            .read(cx)
 1437            .as_singleton()
 1438            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1439        {
 1440            key_context.set("extension", extension.to_string());
 1441        }
 1442
 1443        if self.has_active_inline_completion() {
 1444            key_context.add("copilot_suggestion");
 1445            key_context.add("inline_completion");
 1446        }
 1447
 1448        if !self
 1449            .selections
 1450            .disjoint
 1451            .iter()
 1452            .all(|selection| selection.start == selection.end)
 1453        {
 1454            key_context.add("selection");
 1455        }
 1456
 1457        key_context
 1458    }
 1459
 1460    pub fn new_file(
 1461        workspace: &mut Workspace,
 1462        _: &workspace::NewFile,
 1463        cx: &mut ViewContext<Workspace>,
 1464    ) {
 1465        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1466            "Failed to create buffer",
 1467            cx,
 1468            |e, _| match e.error_code() {
 1469                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1470                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1471                e.error_tag("required").unwrap_or("the latest version")
 1472            )),
 1473                _ => None,
 1474            },
 1475        );
 1476    }
 1477
 1478    pub fn new_in_workspace(
 1479        workspace: &mut Workspace,
 1480        cx: &mut ViewContext<Workspace>,
 1481    ) -> Task<Result<View<Editor>>> {
 1482        let project = workspace.project().clone();
 1483        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1484
 1485        cx.spawn(|workspace, mut cx| async move {
 1486            let buffer = create.await?;
 1487            workspace.update(&mut cx, |workspace, cx| {
 1488                let editor =
 1489                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1490                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1491                editor
 1492            })
 1493        })
 1494    }
 1495
 1496    fn new_file_vertical(
 1497        workspace: &mut Workspace,
 1498        _: &workspace::NewFileSplitVertical,
 1499        cx: &mut ViewContext<Workspace>,
 1500    ) {
 1501        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1502    }
 1503
 1504    fn new_file_horizontal(
 1505        workspace: &mut Workspace,
 1506        _: &workspace::NewFileSplitHorizontal,
 1507        cx: &mut ViewContext<Workspace>,
 1508    ) {
 1509        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1510    }
 1511
 1512    fn new_file_in_direction(
 1513        workspace: &mut Workspace,
 1514        direction: SplitDirection,
 1515        cx: &mut ViewContext<Workspace>,
 1516    ) {
 1517        let project = workspace.project().clone();
 1518        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1519
 1520        cx.spawn(|workspace, mut cx| async move {
 1521            let buffer = create.await?;
 1522            workspace.update(&mut cx, move |workspace, cx| {
 1523                workspace.split_item(
 1524                    direction,
 1525                    Box::new(
 1526                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1527                    ),
 1528                    cx,
 1529                )
 1530            })?;
 1531            anyhow::Ok(())
 1532        })
 1533        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1534            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1535                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1536                e.error_tag("required").unwrap_or("the latest version")
 1537            )),
 1538            _ => None,
 1539        });
 1540    }
 1541
 1542    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1543        self.leader_peer_id
 1544    }
 1545
 1546    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1547        &self.buffer
 1548    }
 1549
 1550    pub fn workspace(&self) -> Option<View<Workspace>> {
 1551        self.workspace.as_ref()?.0.upgrade()
 1552    }
 1553
 1554    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1555        self.buffer().read(cx).title(cx)
 1556    }
 1557
 1558    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1559        let git_blame_gutter_max_author_length = self
 1560            .render_git_blame_gutter(cx)
 1561            .then(|| {
 1562                if let Some(blame) = self.blame.as_ref() {
 1563                    let max_author_length =
 1564                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1565                    Some(max_author_length)
 1566                } else {
 1567                    None
 1568                }
 1569            })
 1570            .flatten();
 1571
 1572        EditorSnapshot {
 1573            mode: self.mode,
 1574            show_gutter: self.show_gutter,
 1575            show_line_numbers: self.show_line_numbers,
 1576            show_git_diff_gutter: self.show_git_diff_gutter,
 1577            show_code_actions: self.show_code_actions,
 1578            show_runnables: self.show_runnables,
 1579            git_blame_gutter_max_author_length,
 1580            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1581            scroll_anchor: self.scroll_manager.anchor(),
 1582            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1583            placeholder_text: self.placeholder_text.clone(),
 1584            diff_map: self.diff_map.snapshot(),
 1585            is_focused: self.focus_handle.is_focused(cx),
 1586            current_line_highlight: self
 1587                .current_line_highlight
 1588                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1589            gutter_hovered: self.gutter_hovered,
 1590        }
 1591    }
 1592
 1593    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1594        self.buffer.read(cx).language_at(point, cx)
 1595    }
 1596
 1597    pub fn file_at<T: ToOffset>(
 1598        &self,
 1599        point: T,
 1600        cx: &AppContext,
 1601    ) -> Option<Arc<dyn language::File>> {
 1602        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1603    }
 1604
 1605    pub fn active_excerpt(
 1606        &self,
 1607        cx: &AppContext,
 1608    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1609        self.buffer
 1610            .read(cx)
 1611            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1612    }
 1613
 1614    pub fn mode(&self) -> EditorMode {
 1615        self.mode
 1616    }
 1617
 1618    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1619        self.collaboration_hub.as_deref()
 1620    }
 1621
 1622    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1623        self.collaboration_hub = Some(hub);
 1624    }
 1625
 1626    pub fn set_custom_context_menu(
 1627        &mut self,
 1628        f: impl 'static
 1629            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1630    ) {
 1631        self.custom_context_menu = Some(Box::new(f))
 1632    }
 1633
 1634    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1635        self.completion_provider = provider;
 1636    }
 1637
 1638    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1639        self.semantics_provider.clone()
 1640    }
 1641
 1642    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1643        self.semantics_provider = provider;
 1644    }
 1645
 1646    pub fn set_inline_completion_provider<T>(
 1647        &mut self,
 1648        provider: Option<Model<T>>,
 1649        cx: &mut ViewContext<Self>,
 1650    ) where
 1651        T: InlineCompletionProvider,
 1652    {
 1653        self.inline_completion_provider =
 1654            provider.map(|provider| RegisteredInlineCompletionProvider {
 1655                _subscription: cx.observe(&provider, |this, _, cx| {
 1656                    if this.focus_handle.is_focused(cx) {
 1657                        this.update_visible_inline_completion(cx);
 1658                    }
 1659                }),
 1660                provider: Arc::new(provider),
 1661            });
 1662        self.refresh_inline_completion(false, false, cx);
 1663    }
 1664
 1665    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1666        self.placeholder_text.as_deref()
 1667    }
 1668
 1669    pub fn set_placeholder_text(
 1670        &mut self,
 1671        placeholder_text: impl Into<Arc<str>>,
 1672        cx: &mut ViewContext<Self>,
 1673    ) {
 1674        let placeholder_text = Some(placeholder_text.into());
 1675        if self.placeholder_text != placeholder_text {
 1676            self.placeholder_text = placeholder_text;
 1677            cx.notify();
 1678        }
 1679    }
 1680
 1681    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1682        self.cursor_shape = cursor_shape;
 1683
 1684        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1685        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1686
 1687        cx.notify();
 1688    }
 1689
 1690    pub fn set_current_line_highlight(
 1691        &mut self,
 1692        current_line_highlight: Option<CurrentLineHighlight>,
 1693    ) {
 1694        self.current_line_highlight = current_line_highlight;
 1695    }
 1696
 1697    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1698        self.collapse_matches = collapse_matches;
 1699    }
 1700
 1701    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1702        let buffers = self.buffer.read(cx).all_buffers();
 1703        let Some(lsp_store) = self.lsp_store(cx) else {
 1704            return;
 1705        };
 1706        lsp_store.update(cx, |lsp_store, cx| {
 1707            for buffer in buffers {
 1708                self.registered_buffers
 1709                    .entry(buffer.read(cx).remote_id())
 1710                    .or_insert_with(|| {
 1711                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1712                    });
 1713            }
 1714        })
 1715    }
 1716
 1717    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1718        if self.collapse_matches {
 1719            return range.start..range.start;
 1720        }
 1721        range.clone()
 1722    }
 1723
 1724    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1725        if self.display_map.read(cx).clip_at_line_ends != clip {
 1726            self.display_map
 1727                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1728        }
 1729    }
 1730
 1731    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1732        self.input_enabled = input_enabled;
 1733    }
 1734
 1735    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 1736        self.enable_inline_completions = enabled;
 1737    }
 1738
 1739    pub fn set_autoindent(&mut self, autoindent: bool) {
 1740        if autoindent {
 1741            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1742        } else {
 1743            self.autoindent_mode = None;
 1744        }
 1745    }
 1746
 1747    pub fn read_only(&self, cx: &AppContext) -> bool {
 1748        self.read_only || self.buffer.read(cx).read_only()
 1749    }
 1750
 1751    pub fn set_read_only(&mut self, read_only: bool) {
 1752        self.read_only = read_only;
 1753    }
 1754
 1755    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1756        self.use_autoclose = autoclose;
 1757    }
 1758
 1759    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1760        self.use_auto_surround = auto_surround;
 1761    }
 1762
 1763    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1764        self.auto_replace_emoji_shortcode = auto_replace;
 1765    }
 1766
 1767    pub fn toggle_inline_completions(
 1768        &mut self,
 1769        _: &ToggleInlineCompletions,
 1770        cx: &mut ViewContext<Self>,
 1771    ) {
 1772        if self.show_inline_completions_override.is_some() {
 1773            self.set_show_inline_completions(None, cx);
 1774        } else {
 1775            let cursor = self.selections.newest_anchor().head();
 1776            if let Some((buffer, cursor_buffer_position)) =
 1777                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1778            {
 1779                let show_inline_completions =
 1780                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1781                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1782            }
 1783        }
 1784    }
 1785
 1786    pub fn set_show_inline_completions(
 1787        &mut self,
 1788        show_inline_completions: Option<bool>,
 1789        cx: &mut ViewContext<Self>,
 1790    ) {
 1791        self.show_inline_completions_override = show_inline_completions;
 1792        self.refresh_inline_completion(false, true, cx);
 1793    }
 1794
 1795    pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
 1796        let cursor = self.selections.newest_anchor().head();
 1797        if let Some((buffer, buffer_position)) =
 1798            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1799        {
 1800            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1801        } else {
 1802            false
 1803        }
 1804    }
 1805
 1806    fn should_show_inline_completions(
 1807        &self,
 1808        buffer: &Model<Buffer>,
 1809        buffer_position: language::Anchor,
 1810        cx: &AppContext,
 1811    ) -> bool {
 1812        if !self.snippet_stack.is_empty() {
 1813            return false;
 1814        }
 1815
 1816        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1817            return false;
 1818        }
 1819
 1820        if let Some(provider) = self.inline_completion_provider() {
 1821            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1822                show_inline_completions
 1823            } else {
 1824                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1825            }
 1826        } else {
 1827            false
 1828        }
 1829    }
 1830
 1831    fn inline_completions_disabled_in_scope(
 1832        &self,
 1833        buffer: &Model<Buffer>,
 1834        buffer_position: language::Anchor,
 1835        cx: &AppContext,
 1836    ) -> bool {
 1837        let snapshot = buffer.read(cx).snapshot();
 1838        let settings = snapshot.settings_at(buffer_position, cx);
 1839
 1840        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1841            return false;
 1842        };
 1843
 1844        scope.override_name().map_or(false, |scope_name| {
 1845            settings
 1846                .inline_completions_disabled_in
 1847                .iter()
 1848                .any(|s| s == scope_name)
 1849        })
 1850    }
 1851
 1852    pub fn set_use_modal_editing(&mut self, to: bool) {
 1853        self.use_modal_editing = to;
 1854    }
 1855
 1856    pub fn use_modal_editing(&self) -> bool {
 1857        self.use_modal_editing
 1858    }
 1859
 1860    fn selections_did_change(
 1861        &mut self,
 1862        local: bool,
 1863        old_cursor_position: &Anchor,
 1864        show_completions: bool,
 1865        cx: &mut ViewContext<Self>,
 1866    ) {
 1867        cx.invalidate_character_coordinates();
 1868
 1869        // Copy selections to primary selection buffer
 1870        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1871        if local {
 1872            let selections = self.selections.all::<usize>(cx);
 1873            let buffer_handle = self.buffer.read(cx).read(cx);
 1874
 1875            let mut text = String::new();
 1876            for (index, selection) in selections.iter().enumerate() {
 1877                let text_for_selection = buffer_handle
 1878                    .text_for_range(selection.start..selection.end)
 1879                    .collect::<String>();
 1880
 1881                text.push_str(&text_for_selection);
 1882                if index != selections.len() - 1 {
 1883                    text.push('\n');
 1884                }
 1885            }
 1886
 1887            if !text.is_empty() {
 1888                cx.write_to_primary(ClipboardItem::new_string(text));
 1889            }
 1890        }
 1891
 1892        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1893            self.buffer.update(cx, |buffer, cx| {
 1894                buffer.set_active_selections(
 1895                    &self.selections.disjoint_anchors(),
 1896                    self.selections.line_mode,
 1897                    self.cursor_shape,
 1898                    cx,
 1899                )
 1900            });
 1901        }
 1902        let display_map = self
 1903            .display_map
 1904            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1905        let buffer = &display_map.buffer_snapshot;
 1906        self.add_selections_state = None;
 1907        self.select_next_state = None;
 1908        self.select_prev_state = None;
 1909        self.select_larger_syntax_node_stack.clear();
 1910        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1911        self.snippet_stack
 1912            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1913        self.take_rename(false, cx);
 1914
 1915        let new_cursor_position = self.selections.newest_anchor().head();
 1916
 1917        self.push_to_nav_history(
 1918            *old_cursor_position,
 1919            Some(new_cursor_position.to_point(buffer)),
 1920            cx,
 1921        );
 1922
 1923        if local {
 1924            let new_cursor_position = self.selections.newest_anchor().head();
 1925            let mut context_menu = self.context_menu.borrow_mut();
 1926            let completion_menu = match context_menu.as_ref() {
 1927                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1928                _ => {
 1929                    *context_menu = None;
 1930                    None
 1931                }
 1932            };
 1933
 1934            if let Some(completion_menu) = completion_menu {
 1935                let cursor_position = new_cursor_position.to_offset(buffer);
 1936                let (word_range, kind) =
 1937                    buffer.surrounding_word(completion_menu.initial_position, true);
 1938                if kind == Some(CharKind::Word)
 1939                    && word_range.to_inclusive().contains(&cursor_position)
 1940                {
 1941                    let mut completion_menu = completion_menu.clone();
 1942                    drop(context_menu);
 1943
 1944                    let query = Self::completion_query(buffer, cursor_position);
 1945                    cx.spawn(move |this, mut cx| async move {
 1946                        completion_menu
 1947                            .filter(query.as_deref(), cx.background_executor().clone())
 1948                            .await;
 1949
 1950                        this.update(&mut cx, |this, cx| {
 1951                            let mut context_menu = this.context_menu.borrow_mut();
 1952                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1953                            else {
 1954                                return;
 1955                            };
 1956
 1957                            if menu.id > completion_menu.id {
 1958                                return;
 1959                            }
 1960
 1961                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1962                            drop(context_menu);
 1963                            cx.notify();
 1964                        })
 1965                    })
 1966                    .detach();
 1967
 1968                    if show_completions {
 1969                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1970                    }
 1971                } else {
 1972                    drop(context_menu);
 1973                    self.hide_context_menu(cx);
 1974                }
 1975            } else {
 1976                drop(context_menu);
 1977            }
 1978
 1979            hide_hover(self, cx);
 1980
 1981            if old_cursor_position.to_display_point(&display_map).row()
 1982                != new_cursor_position.to_display_point(&display_map).row()
 1983            {
 1984                self.available_code_actions.take();
 1985            }
 1986            self.refresh_code_actions(cx);
 1987            self.refresh_document_highlights(cx);
 1988            refresh_matching_bracket_highlights(self, cx);
 1989            self.update_visible_inline_completion(cx);
 1990            linked_editing_ranges::refresh_linked_ranges(self, cx);
 1991            if self.git_blame_inline_enabled {
 1992                self.start_inline_blame_timer(cx);
 1993            }
 1994        }
 1995
 1996        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 1997        cx.emit(EditorEvent::SelectionsChanged { local });
 1998
 1999        if self.selections.disjoint_anchors().len() == 1 {
 2000            cx.emit(SearchEvent::ActiveMatchChanged)
 2001        }
 2002        cx.notify();
 2003    }
 2004
 2005    pub fn change_selections<R>(
 2006        &mut self,
 2007        autoscroll: Option<Autoscroll>,
 2008        cx: &mut ViewContext<Self>,
 2009        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2010    ) -> R {
 2011        self.change_selections_inner(autoscroll, true, cx, change)
 2012    }
 2013
 2014    pub fn change_selections_inner<R>(
 2015        &mut self,
 2016        autoscroll: Option<Autoscroll>,
 2017        request_completions: bool,
 2018        cx: &mut ViewContext<Self>,
 2019        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2020    ) -> R {
 2021        let old_cursor_position = self.selections.newest_anchor().head();
 2022        self.push_to_selection_history();
 2023
 2024        let (changed, result) = self.selections.change_with(cx, change);
 2025
 2026        if changed {
 2027            if let Some(autoscroll) = autoscroll {
 2028                self.request_autoscroll(autoscroll, cx);
 2029            }
 2030            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2031
 2032            if self.should_open_signature_help_automatically(
 2033                &old_cursor_position,
 2034                self.signature_help_state.backspace_pressed(),
 2035                cx,
 2036            ) {
 2037                self.show_signature_help(&ShowSignatureHelp, cx);
 2038            }
 2039            self.signature_help_state.set_backspace_pressed(false);
 2040        }
 2041
 2042        result
 2043    }
 2044
 2045    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2046    where
 2047        I: IntoIterator<Item = (Range<S>, T)>,
 2048        S: ToOffset,
 2049        T: Into<Arc<str>>,
 2050    {
 2051        if self.read_only(cx) {
 2052            return;
 2053        }
 2054
 2055        self.buffer
 2056            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2057    }
 2058
 2059    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2060    where
 2061        I: IntoIterator<Item = (Range<S>, T)>,
 2062        S: ToOffset,
 2063        T: Into<Arc<str>>,
 2064    {
 2065        if self.read_only(cx) {
 2066            return;
 2067        }
 2068
 2069        self.buffer.update(cx, |buffer, cx| {
 2070            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2071        });
 2072    }
 2073
 2074    pub fn edit_with_block_indent<I, S, T>(
 2075        &mut self,
 2076        edits: I,
 2077        original_indent_columns: Vec<u32>,
 2078        cx: &mut ViewContext<Self>,
 2079    ) where
 2080        I: IntoIterator<Item = (Range<S>, T)>,
 2081        S: ToOffset,
 2082        T: Into<Arc<str>>,
 2083    {
 2084        if self.read_only(cx) {
 2085            return;
 2086        }
 2087
 2088        self.buffer.update(cx, |buffer, cx| {
 2089            buffer.edit(
 2090                edits,
 2091                Some(AutoindentMode::Block {
 2092                    original_indent_columns,
 2093                }),
 2094                cx,
 2095            )
 2096        });
 2097    }
 2098
 2099    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2100        self.hide_context_menu(cx);
 2101
 2102        match phase {
 2103            SelectPhase::Begin {
 2104                position,
 2105                add,
 2106                click_count,
 2107            } => self.begin_selection(position, add, click_count, cx),
 2108            SelectPhase::BeginColumnar {
 2109                position,
 2110                goal_column,
 2111                reset,
 2112            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2113            SelectPhase::Extend {
 2114                position,
 2115                click_count,
 2116            } => self.extend_selection(position, click_count, cx),
 2117            SelectPhase::Update {
 2118                position,
 2119                goal_column,
 2120                scroll_delta,
 2121            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2122            SelectPhase::End => self.end_selection(cx),
 2123        }
 2124    }
 2125
 2126    fn extend_selection(
 2127        &mut self,
 2128        position: DisplayPoint,
 2129        click_count: usize,
 2130        cx: &mut ViewContext<Self>,
 2131    ) {
 2132        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2133        let tail = self.selections.newest::<usize>(cx).tail();
 2134        self.begin_selection(position, false, click_count, cx);
 2135
 2136        let position = position.to_offset(&display_map, Bias::Left);
 2137        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2138
 2139        let mut pending_selection = self
 2140            .selections
 2141            .pending_anchor()
 2142            .expect("extend_selection not called with pending selection");
 2143        if position >= tail {
 2144            pending_selection.start = tail_anchor;
 2145        } else {
 2146            pending_selection.end = tail_anchor;
 2147            pending_selection.reversed = true;
 2148        }
 2149
 2150        let mut pending_mode = self.selections.pending_mode().unwrap();
 2151        match &mut pending_mode {
 2152            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2153            _ => {}
 2154        }
 2155
 2156        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2157            s.set_pending(pending_selection, pending_mode)
 2158        });
 2159    }
 2160
 2161    fn begin_selection(
 2162        &mut self,
 2163        position: DisplayPoint,
 2164        add: bool,
 2165        click_count: usize,
 2166        cx: &mut ViewContext<Self>,
 2167    ) {
 2168        if !self.focus_handle.is_focused(cx) {
 2169            self.last_focused_descendant = None;
 2170            cx.focus(&self.focus_handle);
 2171        }
 2172
 2173        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2174        let buffer = &display_map.buffer_snapshot;
 2175        let newest_selection = self.selections.newest_anchor().clone();
 2176        let position = display_map.clip_point(position, Bias::Left);
 2177
 2178        let start;
 2179        let end;
 2180        let mode;
 2181        let mut auto_scroll;
 2182        match click_count {
 2183            1 => {
 2184                start = buffer.anchor_before(position.to_point(&display_map));
 2185                end = start;
 2186                mode = SelectMode::Character;
 2187                auto_scroll = true;
 2188            }
 2189            2 => {
 2190                let range = movement::surrounding_word(&display_map, position);
 2191                start = buffer.anchor_before(range.start.to_point(&display_map));
 2192                end = buffer.anchor_before(range.end.to_point(&display_map));
 2193                mode = SelectMode::Word(start..end);
 2194                auto_scroll = true;
 2195            }
 2196            3 => {
 2197                let position = display_map
 2198                    .clip_point(position, Bias::Left)
 2199                    .to_point(&display_map);
 2200                let line_start = display_map.prev_line_boundary(position).0;
 2201                let next_line_start = buffer.clip_point(
 2202                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2203                    Bias::Left,
 2204                );
 2205                start = buffer.anchor_before(line_start);
 2206                end = buffer.anchor_before(next_line_start);
 2207                mode = SelectMode::Line(start..end);
 2208                auto_scroll = true;
 2209            }
 2210            _ => {
 2211                start = buffer.anchor_before(0);
 2212                end = buffer.anchor_before(buffer.len());
 2213                mode = SelectMode::All;
 2214                auto_scroll = false;
 2215            }
 2216        }
 2217        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2218
 2219        let point_to_delete: Option<usize> = {
 2220            let selected_points: Vec<Selection<Point>> =
 2221                self.selections.disjoint_in_range(start..end, cx);
 2222
 2223            if !add || click_count > 1 {
 2224                None
 2225            } else if !selected_points.is_empty() {
 2226                Some(selected_points[0].id)
 2227            } else {
 2228                let clicked_point_already_selected =
 2229                    self.selections.disjoint.iter().find(|selection| {
 2230                        selection.start.to_point(buffer) == start.to_point(buffer)
 2231                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2232                    });
 2233
 2234                clicked_point_already_selected.map(|selection| selection.id)
 2235            }
 2236        };
 2237
 2238        let selections_count = self.selections.count();
 2239
 2240        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2241            if let Some(point_to_delete) = point_to_delete {
 2242                s.delete(point_to_delete);
 2243
 2244                if selections_count == 1 {
 2245                    s.set_pending_anchor_range(start..end, mode);
 2246                }
 2247            } else {
 2248                if !add {
 2249                    s.clear_disjoint();
 2250                } else if click_count > 1 {
 2251                    s.delete(newest_selection.id)
 2252                }
 2253
 2254                s.set_pending_anchor_range(start..end, mode);
 2255            }
 2256        });
 2257    }
 2258
 2259    fn begin_columnar_selection(
 2260        &mut self,
 2261        position: DisplayPoint,
 2262        goal_column: u32,
 2263        reset: bool,
 2264        cx: &mut ViewContext<Self>,
 2265    ) {
 2266        if !self.focus_handle.is_focused(cx) {
 2267            self.last_focused_descendant = None;
 2268            cx.focus(&self.focus_handle);
 2269        }
 2270
 2271        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2272
 2273        if reset {
 2274            let pointer_position = display_map
 2275                .buffer_snapshot
 2276                .anchor_before(position.to_point(&display_map));
 2277
 2278            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2279                s.clear_disjoint();
 2280                s.set_pending_anchor_range(
 2281                    pointer_position..pointer_position,
 2282                    SelectMode::Character,
 2283                );
 2284            });
 2285        }
 2286
 2287        let tail = self.selections.newest::<Point>(cx).tail();
 2288        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2289
 2290        if !reset {
 2291            self.select_columns(
 2292                tail.to_display_point(&display_map),
 2293                position,
 2294                goal_column,
 2295                &display_map,
 2296                cx,
 2297            );
 2298        }
 2299    }
 2300
 2301    fn update_selection(
 2302        &mut self,
 2303        position: DisplayPoint,
 2304        goal_column: u32,
 2305        scroll_delta: gpui::Point<f32>,
 2306        cx: &mut ViewContext<Self>,
 2307    ) {
 2308        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2309
 2310        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2311            let tail = tail.to_display_point(&display_map);
 2312            self.select_columns(tail, position, goal_column, &display_map, cx);
 2313        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2314            let buffer = self.buffer.read(cx).snapshot(cx);
 2315            let head;
 2316            let tail;
 2317            let mode = self.selections.pending_mode().unwrap();
 2318            match &mode {
 2319                SelectMode::Character => {
 2320                    head = position.to_point(&display_map);
 2321                    tail = pending.tail().to_point(&buffer);
 2322                }
 2323                SelectMode::Word(original_range) => {
 2324                    let original_display_range = original_range.start.to_display_point(&display_map)
 2325                        ..original_range.end.to_display_point(&display_map);
 2326                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2327                        ..original_display_range.end.to_point(&display_map);
 2328                    if movement::is_inside_word(&display_map, position)
 2329                        || original_display_range.contains(&position)
 2330                    {
 2331                        let word_range = movement::surrounding_word(&display_map, position);
 2332                        if word_range.start < original_display_range.start {
 2333                            head = word_range.start.to_point(&display_map);
 2334                        } else {
 2335                            head = word_range.end.to_point(&display_map);
 2336                        }
 2337                    } else {
 2338                        head = position.to_point(&display_map);
 2339                    }
 2340
 2341                    if head <= original_buffer_range.start {
 2342                        tail = original_buffer_range.end;
 2343                    } else {
 2344                        tail = original_buffer_range.start;
 2345                    }
 2346                }
 2347                SelectMode::Line(original_range) => {
 2348                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2349
 2350                    let position = display_map
 2351                        .clip_point(position, Bias::Left)
 2352                        .to_point(&display_map);
 2353                    let line_start = display_map.prev_line_boundary(position).0;
 2354                    let next_line_start = buffer.clip_point(
 2355                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2356                        Bias::Left,
 2357                    );
 2358
 2359                    if line_start < original_range.start {
 2360                        head = line_start
 2361                    } else {
 2362                        head = next_line_start
 2363                    }
 2364
 2365                    if head <= original_range.start {
 2366                        tail = original_range.end;
 2367                    } else {
 2368                        tail = original_range.start;
 2369                    }
 2370                }
 2371                SelectMode::All => {
 2372                    return;
 2373                }
 2374            };
 2375
 2376            if head < tail {
 2377                pending.start = buffer.anchor_before(head);
 2378                pending.end = buffer.anchor_before(tail);
 2379                pending.reversed = true;
 2380            } else {
 2381                pending.start = buffer.anchor_before(tail);
 2382                pending.end = buffer.anchor_before(head);
 2383                pending.reversed = false;
 2384            }
 2385
 2386            self.change_selections(None, cx, |s| {
 2387                s.set_pending(pending, mode);
 2388            });
 2389        } else {
 2390            log::error!("update_selection dispatched with no pending selection");
 2391            return;
 2392        }
 2393
 2394        self.apply_scroll_delta(scroll_delta, cx);
 2395        cx.notify();
 2396    }
 2397
 2398    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2399        self.columnar_selection_tail.take();
 2400        if self.selections.pending_anchor().is_some() {
 2401            let selections = self.selections.all::<usize>(cx);
 2402            self.change_selections(None, cx, |s| {
 2403                s.select(selections);
 2404                s.clear_pending();
 2405            });
 2406        }
 2407    }
 2408
 2409    fn select_columns(
 2410        &mut self,
 2411        tail: DisplayPoint,
 2412        head: DisplayPoint,
 2413        goal_column: u32,
 2414        display_map: &DisplaySnapshot,
 2415        cx: &mut ViewContext<Self>,
 2416    ) {
 2417        let start_row = cmp::min(tail.row(), head.row());
 2418        let end_row = cmp::max(tail.row(), head.row());
 2419        let start_column = cmp::min(tail.column(), goal_column);
 2420        let end_column = cmp::max(tail.column(), goal_column);
 2421        let reversed = start_column < tail.column();
 2422
 2423        let selection_ranges = (start_row.0..=end_row.0)
 2424            .map(DisplayRow)
 2425            .filter_map(|row| {
 2426                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2427                    let start = display_map
 2428                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2429                        .to_point(display_map);
 2430                    let end = display_map
 2431                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2432                        .to_point(display_map);
 2433                    if reversed {
 2434                        Some(end..start)
 2435                    } else {
 2436                        Some(start..end)
 2437                    }
 2438                } else {
 2439                    None
 2440                }
 2441            })
 2442            .collect::<Vec<_>>();
 2443
 2444        self.change_selections(None, cx, |s| {
 2445            s.select_ranges(selection_ranges);
 2446        });
 2447        cx.notify();
 2448    }
 2449
 2450    pub fn has_pending_nonempty_selection(&self) -> bool {
 2451        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2452            Some(Selection { start, end, .. }) => start != end,
 2453            None => false,
 2454        };
 2455
 2456        pending_nonempty_selection
 2457            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2458    }
 2459
 2460    pub fn has_pending_selection(&self) -> bool {
 2461        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2462    }
 2463
 2464    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2465        if self.clear_expanded_diff_hunks(cx) {
 2466            cx.notify();
 2467            return;
 2468        }
 2469        if self.dismiss_menus_and_popups(true, cx) {
 2470            return;
 2471        }
 2472
 2473        if self.mode == EditorMode::Full
 2474            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2475        {
 2476            return;
 2477        }
 2478
 2479        cx.propagate();
 2480    }
 2481
 2482    pub fn dismiss_menus_and_popups(
 2483        &mut self,
 2484        should_report_inline_completion_event: bool,
 2485        cx: &mut ViewContext<Self>,
 2486    ) -> bool {
 2487        if self.take_rename(false, cx).is_some() {
 2488            return true;
 2489        }
 2490
 2491        if hide_hover(self, cx) {
 2492            return true;
 2493        }
 2494
 2495        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2496            return true;
 2497        }
 2498
 2499        if self.hide_context_menu(cx).is_some() {
 2500            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2501                self.update_visible_inline_completion(cx);
 2502            }
 2503            return true;
 2504        }
 2505
 2506        if self.mouse_context_menu.take().is_some() {
 2507            return true;
 2508        }
 2509
 2510        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2511            return true;
 2512        }
 2513
 2514        if self.snippet_stack.pop().is_some() {
 2515            return true;
 2516        }
 2517
 2518        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2519            self.dismiss_diagnostics(cx);
 2520            return true;
 2521        }
 2522
 2523        false
 2524    }
 2525
 2526    fn linked_editing_ranges_for(
 2527        &self,
 2528        selection: Range<text::Anchor>,
 2529        cx: &AppContext,
 2530    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2531        if self.linked_edit_ranges.is_empty() {
 2532            return None;
 2533        }
 2534        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2535            selection.end.buffer_id.and_then(|end_buffer_id| {
 2536                if selection.start.buffer_id != Some(end_buffer_id) {
 2537                    return None;
 2538                }
 2539                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2540                let snapshot = buffer.read(cx).snapshot();
 2541                self.linked_edit_ranges
 2542                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2543                    .map(|ranges| (ranges, snapshot, buffer))
 2544            })?;
 2545        use text::ToOffset as TO;
 2546        // find offset from the start of current range to current cursor position
 2547        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2548
 2549        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2550        let start_difference = start_offset - start_byte_offset;
 2551        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2552        let end_difference = end_offset - start_byte_offset;
 2553        // Current range has associated linked ranges.
 2554        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2555        for range in linked_ranges.iter() {
 2556            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2557            let end_offset = start_offset + end_difference;
 2558            let start_offset = start_offset + start_difference;
 2559            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2560                continue;
 2561            }
 2562            if self.selections.disjoint_anchor_ranges().any(|s| {
 2563                if s.start.buffer_id != selection.start.buffer_id
 2564                    || s.end.buffer_id != selection.end.buffer_id
 2565                {
 2566                    return false;
 2567                }
 2568                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2569                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2570            }) {
 2571                continue;
 2572            }
 2573            let start = buffer_snapshot.anchor_after(start_offset);
 2574            let end = buffer_snapshot.anchor_after(end_offset);
 2575            linked_edits
 2576                .entry(buffer.clone())
 2577                .or_default()
 2578                .push(start..end);
 2579        }
 2580        Some(linked_edits)
 2581    }
 2582
 2583    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2584        let text: Arc<str> = text.into();
 2585
 2586        if self.read_only(cx) {
 2587            return;
 2588        }
 2589
 2590        let selections = self.selections.all_adjusted(cx);
 2591        let mut bracket_inserted = false;
 2592        let mut edits = Vec::new();
 2593        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2594        let mut new_selections = Vec::with_capacity(selections.len());
 2595        let mut new_autoclose_regions = Vec::new();
 2596        let snapshot = self.buffer.read(cx).read(cx);
 2597
 2598        for (selection, autoclose_region) in
 2599            self.selections_with_autoclose_regions(selections, &snapshot)
 2600        {
 2601            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2602                // Determine if the inserted text matches the opening or closing
 2603                // bracket of any of this language's bracket pairs.
 2604                let mut bracket_pair = None;
 2605                let mut is_bracket_pair_start = false;
 2606                let mut is_bracket_pair_end = false;
 2607                if !text.is_empty() {
 2608                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2609                    //  and they are removing the character that triggered IME popup.
 2610                    for (pair, enabled) in scope.brackets() {
 2611                        if !pair.close && !pair.surround {
 2612                            continue;
 2613                        }
 2614
 2615                        if enabled && pair.start.ends_with(text.as_ref()) {
 2616                            let prefix_len = pair.start.len() - text.len();
 2617                            let preceding_text_matches_prefix = prefix_len == 0
 2618                                || (selection.start.column >= (prefix_len as u32)
 2619                                    && snapshot.contains_str_at(
 2620                                        Point::new(
 2621                                            selection.start.row,
 2622                                            selection.start.column - (prefix_len as u32),
 2623                                        ),
 2624                                        &pair.start[..prefix_len],
 2625                                    ));
 2626                            if preceding_text_matches_prefix {
 2627                                bracket_pair = Some(pair.clone());
 2628                                is_bracket_pair_start = true;
 2629                                break;
 2630                            }
 2631                        }
 2632                        if pair.end.as_str() == text.as_ref() {
 2633                            bracket_pair = Some(pair.clone());
 2634                            is_bracket_pair_end = true;
 2635                            break;
 2636                        }
 2637                    }
 2638                }
 2639
 2640                if let Some(bracket_pair) = bracket_pair {
 2641                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2642                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2643                    let auto_surround =
 2644                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2645                    if selection.is_empty() {
 2646                        if is_bracket_pair_start {
 2647                            // If the inserted text is a suffix of an opening bracket and the
 2648                            // selection is preceded by the rest of the opening bracket, then
 2649                            // insert the closing bracket.
 2650                            let following_text_allows_autoclose = snapshot
 2651                                .chars_at(selection.start)
 2652                                .next()
 2653                                .map_or(true, |c| scope.should_autoclose_before(c));
 2654
 2655                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2656                                && bracket_pair.start.len() == 1
 2657                            {
 2658                                let target = bracket_pair.start.chars().next().unwrap();
 2659                                let current_line_count = snapshot
 2660                                    .reversed_chars_at(selection.start)
 2661                                    .take_while(|&c| c != '\n')
 2662                                    .filter(|&c| c == target)
 2663                                    .count();
 2664                                current_line_count % 2 == 1
 2665                            } else {
 2666                                false
 2667                            };
 2668
 2669                            if autoclose
 2670                                && bracket_pair.close
 2671                                && following_text_allows_autoclose
 2672                                && !is_closing_quote
 2673                            {
 2674                                let anchor = snapshot.anchor_before(selection.end);
 2675                                new_selections.push((selection.map(|_| anchor), text.len()));
 2676                                new_autoclose_regions.push((
 2677                                    anchor,
 2678                                    text.len(),
 2679                                    selection.id,
 2680                                    bracket_pair.clone(),
 2681                                ));
 2682                                edits.push((
 2683                                    selection.range(),
 2684                                    format!("{}{}", text, bracket_pair.end).into(),
 2685                                ));
 2686                                bracket_inserted = true;
 2687                                continue;
 2688                            }
 2689                        }
 2690
 2691                        if let Some(region) = autoclose_region {
 2692                            // If the selection is followed by an auto-inserted closing bracket,
 2693                            // then don't insert that closing bracket again; just move the selection
 2694                            // past the closing bracket.
 2695                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2696                                && text.as_ref() == region.pair.end.as_str();
 2697                            if should_skip {
 2698                                let anchor = snapshot.anchor_after(selection.end);
 2699                                new_selections
 2700                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2701                                continue;
 2702                            }
 2703                        }
 2704
 2705                        let always_treat_brackets_as_autoclosed = snapshot
 2706                            .settings_at(selection.start, cx)
 2707                            .always_treat_brackets_as_autoclosed;
 2708                        if always_treat_brackets_as_autoclosed
 2709                            && is_bracket_pair_end
 2710                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2711                        {
 2712                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2713                            // and the inserted text is a closing bracket and the selection is followed
 2714                            // by the closing bracket then move the selection past the closing bracket.
 2715                            let anchor = snapshot.anchor_after(selection.end);
 2716                            new_selections.push((selection.map(|_| anchor), text.len()));
 2717                            continue;
 2718                        }
 2719                    }
 2720                    // If an opening bracket is 1 character long and is typed while
 2721                    // text is selected, then surround that text with the bracket pair.
 2722                    else if auto_surround
 2723                        && bracket_pair.surround
 2724                        && is_bracket_pair_start
 2725                        && bracket_pair.start.chars().count() == 1
 2726                    {
 2727                        edits.push((selection.start..selection.start, text.clone()));
 2728                        edits.push((
 2729                            selection.end..selection.end,
 2730                            bracket_pair.end.as_str().into(),
 2731                        ));
 2732                        bracket_inserted = true;
 2733                        new_selections.push((
 2734                            Selection {
 2735                                id: selection.id,
 2736                                start: snapshot.anchor_after(selection.start),
 2737                                end: snapshot.anchor_before(selection.end),
 2738                                reversed: selection.reversed,
 2739                                goal: selection.goal,
 2740                            },
 2741                            0,
 2742                        ));
 2743                        continue;
 2744                    }
 2745                }
 2746            }
 2747
 2748            if self.auto_replace_emoji_shortcode
 2749                && selection.is_empty()
 2750                && text.as_ref().ends_with(':')
 2751            {
 2752                if let Some(possible_emoji_short_code) =
 2753                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2754                {
 2755                    if !possible_emoji_short_code.is_empty() {
 2756                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2757                            let emoji_shortcode_start = Point::new(
 2758                                selection.start.row,
 2759                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2760                            );
 2761
 2762                            // Remove shortcode from buffer
 2763                            edits.push((
 2764                                emoji_shortcode_start..selection.start,
 2765                                "".to_string().into(),
 2766                            ));
 2767                            new_selections.push((
 2768                                Selection {
 2769                                    id: selection.id,
 2770                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2771                                    end: snapshot.anchor_before(selection.start),
 2772                                    reversed: selection.reversed,
 2773                                    goal: selection.goal,
 2774                                },
 2775                                0,
 2776                            ));
 2777
 2778                            // Insert emoji
 2779                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2780                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2781                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2782
 2783                            continue;
 2784                        }
 2785                    }
 2786                }
 2787            }
 2788
 2789            // If not handling any auto-close operation, then just replace the selected
 2790            // text with the given input and move the selection to the end of the
 2791            // newly inserted text.
 2792            let anchor = snapshot.anchor_after(selection.end);
 2793            if !self.linked_edit_ranges.is_empty() {
 2794                let start_anchor = snapshot.anchor_before(selection.start);
 2795
 2796                let is_word_char = text.chars().next().map_or(true, |char| {
 2797                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2798                    classifier.is_word(char)
 2799                });
 2800
 2801                if is_word_char {
 2802                    if let Some(ranges) = self
 2803                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2804                    {
 2805                        for (buffer, edits) in ranges {
 2806                            linked_edits
 2807                                .entry(buffer.clone())
 2808                                .or_default()
 2809                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2810                        }
 2811                    }
 2812                }
 2813            }
 2814
 2815            new_selections.push((selection.map(|_| anchor), 0));
 2816            edits.push((selection.start..selection.end, text.clone()));
 2817        }
 2818
 2819        drop(snapshot);
 2820
 2821        self.transact(cx, |this, cx| {
 2822            this.buffer.update(cx, |buffer, cx| {
 2823                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2824            });
 2825            for (buffer, edits) in linked_edits {
 2826                buffer.update(cx, |buffer, cx| {
 2827                    let snapshot = buffer.snapshot();
 2828                    let edits = edits
 2829                        .into_iter()
 2830                        .map(|(range, text)| {
 2831                            use text::ToPoint as TP;
 2832                            let end_point = TP::to_point(&range.end, &snapshot);
 2833                            let start_point = TP::to_point(&range.start, &snapshot);
 2834                            (start_point..end_point, text)
 2835                        })
 2836                        .sorted_by_key(|(range, _)| range.start)
 2837                        .collect::<Vec<_>>();
 2838                    buffer.edit(edits, None, cx);
 2839                })
 2840            }
 2841            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2842            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2843            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2844            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2845                .zip(new_selection_deltas)
 2846                .map(|(selection, delta)| Selection {
 2847                    id: selection.id,
 2848                    start: selection.start + delta,
 2849                    end: selection.end + delta,
 2850                    reversed: selection.reversed,
 2851                    goal: SelectionGoal::None,
 2852                })
 2853                .collect::<Vec<_>>();
 2854
 2855            let mut i = 0;
 2856            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2857                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2858                let start = map.buffer_snapshot.anchor_before(position);
 2859                let end = map.buffer_snapshot.anchor_after(position);
 2860                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2861                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2862                        Ordering::Less => i += 1,
 2863                        Ordering::Greater => break,
 2864                        Ordering::Equal => {
 2865                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2866                                Ordering::Less => i += 1,
 2867                                Ordering::Equal => break,
 2868                                Ordering::Greater => break,
 2869                            }
 2870                        }
 2871                    }
 2872                }
 2873                this.autoclose_regions.insert(
 2874                    i,
 2875                    AutocloseRegion {
 2876                        selection_id,
 2877                        range: start..end,
 2878                        pair,
 2879                    },
 2880                );
 2881            }
 2882
 2883            let had_active_inline_completion = this.has_active_inline_completion();
 2884            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2885                s.select(new_selections)
 2886            });
 2887
 2888            if !bracket_inserted {
 2889                if let Some(on_type_format_task) =
 2890                    this.trigger_on_type_formatting(text.to_string(), cx)
 2891                {
 2892                    on_type_format_task.detach_and_log_err(cx);
 2893                }
 2894            }
 2895
 2896            let editor_settings = EditorSettings::get_global(cx);
 2897            if bracket_inserted
 2898                && (editor_settings.auto_signature_help
 2899                    || editor_settings.show_signature_help_after_edits)
 2900            {
 2901                this.show_signature_help(&ShowSignatureHelp, cx);
 2902            }
 2903
 2904            let trigger_in_words =
 2905                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2906            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2907            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2908            this.refresh_inline_completion(true, false, cx);
 2909        });
 2910    }
 2911
 2912    fn find_possible_emoji_shortcode_at_position(
 2913        snapshot: &MultiBufferSnapshot,
 2914        position: Point,
 2915    ) -> Option<String> {
 2916        let mut chars = Vec::new();
 2917        let mut found_colon = false;
 2918        for char in snapshot.reversed_chars_at(position).take(100) {
 2919            // Found a possible emoji shortcode in the middle of the buffer
 2920            if found_colon {
 2921                if char.is_whitespace() {
 2922                    chars.reverse();
 2923                    return Some(chars.iter().collect());
 2924                }
 2925                // If the previous character is not a whitespace, we are in the middle of a word
 2926                // and we only want to complete the shortcode if the word is made up of other emojis
 2927                let mut containing_word = String::new();
 2928                for ch in snapshot
 2929                    .reversed_chars_at(position)
 2930                    .skip(chars.len() + 1)
 2931                    .take(100)
 2932                {
 2933                    if ch.is_whitespace() {
 2934                        break;
 2935                    }
 2936                    containing_word.push(ch);
 2937                }
 2938                let containing_word = containing_word.chars().rev().collect::<String>();
 2939                if util::word_consists_of_emojis(containing_word.as_str()) {
 2940                    chars.reverse();
 2941                    return Some(chars.iter().collect());
 2942                }
 2943            }
 2944
 2945            if char.is_whitespace() || !char.is_ascii() {
 2946                return None;
 2947            }
 2948            if char == ':' {
 2949                found_colon = true;
 2950            } else {
 2951                chars.push(char);
 2952            }
 2953        }
 2954        // Found a possible emoji shortcode at the beginning of the buffer
 2955        chars.reverse();
 2956        Some(chars.iter().collect())
 2957    }
 2958
 2959    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2960        self.transact(cx, |this, cx| {
 2961            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2962                let selections = this.selections.all::<usize>(cx);
 2963                let multi_buffer = this.buffer.read(cx);
 2964                let buffer = multi_buffer.snapshot(cx);
 2965                selections
 2966                    .iter()
 2967                    .map(|selection| {
 2968                        let start_point = selection.start.to_point(&buffer);
 2969                        let mut indent =
 2970                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2971                        indent.len = cmp::min(indent.len, start_point.column);
 2972                        let start = selection.start;
 2973                        let end = selection.end;
 2974                        let selection_is_empty = start == end;
 2975                        let language_scope = buffer.language_scope_at(start);
 2976                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2977                            &language_scope
 2978                        {
 2979                            let leading_whitespace_len = buffer
 2980                                .reversed_chars_at(start)
 2981                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2982                                .map(|c| c.len_utf8())
 2983                                .sum::<usize>();
 2984
 2985                            let trailing_whitespace_len = buffer
 2986                                .chars_at(end)
 2987                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2988                                .map(|c| c.len_utf8())
 2989                                .sum::<usize>();
 2990
 2991                            let insert_extra_newline =
 2992                                language.brackets().any(|(pair, enabled)| {
 2993                                    let pair_start = pair.start.trim_end();
 2994                                    let pair_end = pair.end.trim_start();
 2995
 2996                                    enabled
 2997                                        && pair.newline
 2998                                        && buffer.contains_str_at(
 2999                                            end + trailing_whitespace_len,
 3000                                            pair_end,
 3001                                        )
 3002                                        && buffer.contains_str_at(
 3003                                            (start - leading_whitespace_len)
 3004                                                .saturating_sub(pair_start.len()),
 3005                                            pair_start,
 3006                                        )
 3007                                });
 3008
 3009                            // Comment extension on newline is allowed only for cursor selections
 3010                            let comment_delimiter = maybe!({
 3011                                if !selection_is_empty {
 3012                                    return None;
 3013                                }
 3014
 3015                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3016                                    return None;
 3017                                }
 3018
 3019                                let delimiters = language.line_comment_prefixes();
 3020                                let max_len_of_delimiter =
 3021                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3022                                let (snapshot, range) =
 3023                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3024
 3025                                let mut index_of_first_non_whitespace = 0;
 3026                                let comment_candidate = snapshot
 3027                                    .chars_for_range(range)
 3028                                    .skip_while(|c| {
 3029                                        let should_skip = c.is_whitespace();
 3030                                        if should_skip {
 3031                                            index_of_first_non_whitespace += 1;
 3032                                        }
 3033                                        should_skip
 3034                                    })
 3035                                    .take(max_len_of_delimiter)
 3036                                    .collect::<String>();
 3037                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3038                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3039                                })?;
 3040                                let cursor_is_placed_after_comment_marker =
 3041                                    index_of_first_non_whitespace + comment_prefix.len()
 3042                                        <= start_point.column as usize;
 3043                                if cursor_is_placed_after_comment_marker {
 3044                                    Some(comment_prefix.clone())
 3045                                } else {
 3046                                    None
 3047                                }
 3048                            });
 3049                            (comment_delimiter, insert_extra_newline)
 3050                        } else {
 3051                            (None, false)
 3052                        };
 3053
 3054                        let capacity_for_delimiter = comment_delimiter
 3055                            .as_deref()
 3056                            .map(str::len)
 3057                            .unwrap_or_default();
 3058                        let mut new_text =
 3059                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3060                        new_text.push('\n');
 3061                        new_text.extend(indent.chars());
 3062                        if let Some(delimiter) = &comment_delimiter {
 3063                            new_text.push_str(delimiter);
 3064                        }
 3065                        if insert_extra_newline {
 3066                            new_text = new_text.repeat(2);
 3067                        }
 3068
 3069                        let anchor = buffer.anchor_after(end);
 3070                        let new_selection = selection.map(|_| anchor);
 3071                        (
 3072                            (start..end, new_text),
 3073                            (insert_extra_newline, new_selection),
 3074                        )
 3075                    })
 3076                    .unzip()
 3077            };
 3078
 3079            this.edit_with_autoindent(edits, cx);
 3080            let buffer = this.buffer.read(cx).snapshot(cx);
 3081            let new_selections = selection_fixup_info
 3082                .into_iter()
 3083                .map(|(extra_newline_inserted, new_selection)| {
 3084                    let mut cursor = new_selection.end.to_point(&buffer);
 3085                    if extra_newline_inserted {
 3086                        cursor.row -= 1;
 3087                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3088                    }
 3089                    new_selection.map(|_| cursor)
 3090                })
 3091                .collect();
 3092
 3093            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3094            this.refresh_inline_completion(true, false, cx);
 3095        });
 3096    }
 3097
 3098    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3099        let buffer = self.buffer.read(cx);
 3100        let snapshot = buffer.snapshot(cx);
 3101
 3102        let mut edits = Vec::new();
 3103        let mut rows = Vec::new();
 3104
 3105        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3106            let cursor = selection.head();
 3107            let row = cursor.row;
 3108
 3109            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3110
 3111            let newline = "\n".to_string();
 3112            edits.push((start_of_line..start_of_line, newline));
 3113
 3114            rows.push(row + rows_inserted as u32);
 3115        }
 3116
 3117        self.transact(cx, |editor, cx| {
 3118            editor.edit(edits, cx);
 3119
 3120            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3121                let mut index = 0;
 3122                s.move_cursors_with(|map, _, _| {
 3123                    let row = rows[index];
 3124                    index += 1;
 3125
 3126                    let point = Point::new(row, 0);
 3127                    let boundary = map.next_line_boundary(point).1;
 3128                    let clipped = map.clip_point(boundary, Bias::Left);
 3129
 3130                    (clipped, SelectionGoal::None)
 3131                });
 3132            });
 3133
 3134            let mut indent_edits = Vec::new();
 3135            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3136            for row in rows {
 3137                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3138                for (row, indent) in indents {
 3139                    if indent.len == 0 {
 3140                        continue;
 3141                    }
 3142
 3143                    let text = match indent.kind {
 3144                        IndentKind::Space => " ".repeat(indent.len as usize),
 3145                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3146                    };
 3147                    let point = Point::new(row.0, 0);
 3148                    indent_edits.push((point..point, text));
 3149                }
 3150            }
 3151            editor.edit(indent_edits, cx);
 3152        });
 3153    }
 3154
 3155    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3156        let buffer = self.buffer.read(cx);
 3157        let snapshot = buffer.snapshot(cx);
 3158
 3159        let mut edits = Vec::new();
 3160        let mut rows = Vec::new();
 3161        let mut rows_inserted = 0;
 3162
 3163        for selection in self.selections.all_adjusted(cx) {
 3164            let cursor = selection.head();
 3165            let row = cursor.row;
 3166
 3167            let point = Point::new(row + 1, 0);
 3168            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3169
 3170            let newline = "\n".to_string();
 3171            edits.push((start_of_line..start_of_line, newline));
 3172
 3173            rows_inserted += 1;
 3174            rows.push(row + rows_inserted);
 3175        }
 3176
 3177        self.transact(cx, |editor, cx| {
 3178            editor.edit(edits, cx);
 3179
 3180            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3181                let mut index = 0;
 3182                s.move_cursors_with(|map, _, _| {
 3183                    let row = rows[index];
 3184                    index += 1;
 3185
 3186                    let point = Point::new(row, 0);
 3187                    let boundary = map.next_line_boundary(point).1;
 3188                    let clipped = map.clip_point(boundary, Bias::Left);
 3189
 3190                    (clipped, SelectionGoal::None)
 3191                });
 3192            });
 3193
 3194            let mut indent_edits = Vec::new();
 3195            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3196            for row in rows {
 3197                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3198                for (row, indent) in indents {
 3199                    if indent.len == 0 {
 3200                        continue;
 3201                    }
 3202
 3203                    let text = match indent.kind {
 3204                        IndentKind::Space => " ".repeat(indent.len as usize),
 3205                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3206                    };
 3207                    let point = Point::new(row.0, 0);
 3208                    indent_edits.push((point..point, text));
 3209                }
 3210            }
 3211            editor.edit(indent_edits, cx);
 3212        });
 3213    }
 3214
 3215    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3216        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3217            original_indent_columns: Vec::new(),
 3218        });
 3219        self.insert_with_autoindent_mode(text, autoindent, cx);
 3220    }
 3221
 3222    fn insert_with_autoindent_mode(
 3223        &mut self,
 3224        text: &str,
 3225        autoindent_mode: Option<AutoindentMode>,
 3226        cx: &mut ViewContext<Self>,
 3227    ) {
 3228        if self.read_only(cx) {
 3229            return;
 3230        }
 3231
 3232        let text: Arc<str> = text.into();
 3233        self.transact(cx, |this, cx| {
 3234            let old_selections = this.selections.all_adjusted(cx);
 3235            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3236                let anchors = {
 3237                    let snapshot = buffer.read(cx);
 3238                    old_selections
 3239                        .iter()
 3240                        .map(|s| {
 3241                            let anchor = snapshot.anchor_after(s.head());
 3242                            s.map(|_| anchor)
 3243                        })
 3244                        .collect::<Vec<_>>()
 3245                };
 3246                buffer.edit(
 3247                    old_selections
 3248                        .iter()
 3249                        .map(|s| (s.start..s.end, text.clone())),
 3250                    autoindent_mode,
 3251                    cx,
 3252                );
 3253                anchors
 3254            });
 3255
 3256            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3257                s.select_anchors(selection_anchors);
 3258            })
 3259        });
 3260    }
 3261
 3262    fn trigger_completion_on_input(
 3263        &mut self,
 3264        text: &str,
 3265        trigger_in_words: bool,
 3266        cx: &mut ViewContext<Self>,
 3267    ) {
 3268        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3269            self.show_completions(
 3270                &ShowCompletions {
 3271                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3272                },
 3273                cx,
 3274            );
 3275        } else {
 3276            self.hide_context_menu(cx);
 3277        }
 3278    }
 3279
 3280    fn is_completion_trigger(
 3281        &self,
 3282        text: &str,
 3283        trigger_in_words: bool,
 3284        cx: &mut ViewContext<Self>,
 3285    ) -> bool {
 3286        let position = self.selections.newest_anchor().head();
 3287        let multibuffer = self.buffer.read(cx);
 3288        let Some(buffer) = position
 3289            .buffer_id
 3290            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3291        else {
 3292            return false;
 3293        };
 3294
 3295        if let Some(completion_provider) = &self.completion_provider {
 3296            completion_provider.is_completion_trigger(
 3297                &buffer,
 3298                position.text_anchor,
 3299                text,
 3300                trigger_in_words,
 3301                cx,
 3302            )
 3303        } else {
 3304            false
 3305        }
 3306    }
 3307
 3308    /// If any empty selections is touching the start of its innermost containing autoclose
 3309    /// region, expand it to select the brackets.
 3310    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3311        let selections = self.selections.all::<usize>(cx);
 3312        let buffer = self.buffer.read(cx).read(cx);
 3313        let new_selections = self
 3314            .selections_with_autoclose_regions(selections, &buffer)
 3315            .map(|(mut selection, region)| {
 3316                if !selection.is_empty() {
 3317                    return selection;
 3318                }
 3319
 3320                if let Some(region) = region {
 3321                    let mut range = region.range.to_offset(&buffer);
 3322                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3323                        range.start -= region.pair.start.len();
 3324                        if buffer.contains_str_at(range.start, &region.pair.start)
 3325                            && buffer.contains_str_at(range.end, &region.pair.end)
 3326                        {
 3327                            range.end += region.pair.end.len();
 3328                            selection.start = range.start;
 3329                            selection.end = range.end;
 3330
 3331                            return selection;
 3332                        }
 3333                    }
 3334                }
 3335
 3336                let always_treat_brackets_as_autoclosed = buffer
 3337                    .settings_at(selection.start, cx)
 3338                    .always_treat_brackets_as_autoclosed;
 3339
 3340                if !always_treat_brackets_as_autoclosed {
 3341                    return selection;
 3342                }
 3343
 3344                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3345                    for (pair, enabled) in scope.brackets() {
 3346                        if !enabled || !pair.close {
 3347                            continue;
 3348                        }
 3349
 3350                        if buffer.contains_str_at(selection.start, &pair.end) {
 3351                            let pair_start_len = pair.start.len();
 3352                            if buffer.contains_str_at(
 3353                                selection.start.saturating_sub(pair_start_len),
 3354                                &pair.start,
 3355                            ) {
 3356                                selection.start -= pair_start_len;
 3357                                selection.end += pair.end.len();
 3358
 3359                                return selection;
 3360                            }
 3361                        }
 3362                    }
 3363                }
 3364
 3365                selection
 3366            })
 3367            .collect();
 3368
 3369        drop(buffer);
 3370        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3371    }
 3372
 3373    /// Iterate the given selections, and for each one, find the smallest surrounding
 3374    /// autoclose region. This uses the ordering of the selections and the autoclose
 3375    /// regions to avoid repeated comparisons.
 3376    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3377        &'a self,
 3378        selections: impl IntoIterator<Item = Selection<D>>,
 3379        buffer: &'a MultiBufferSnapshot,
 3380    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3381        let mut i = 0;
 3382        let mut regions = self.autoclose_regions.as_slice();
 3383        selections.into_iter().map(move |selection| {
 3384            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3385
 3386            let mut enclosing = None;
 3387            while let Some(pair_state) = regions.get(i) {
 3388                if pair_state.range.end.to_offset(buffer) < range.start {
 3389                    regions = &regions[i + 1..];
 3390                    i = 0;
 3391                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3392                    break;
 3393                } else {
 3394                    if pair_state.selection_id == selection.id {
 3395                        enclosing = Some(pair_state);
 3396                    }
 3397                    i += 1;
 3398                }
 3399            }
 3400
 3401            (selection, enclosing)
 3402        })
 3403    }
 3404
 3405    /// Remove any autoclose regions that no longer contain their selection.
 3406    fn invalidate_autoclose_regions(
 3407        &mut self,
 3408        mut selections: &[Selection<Anchor>],
 3409        buffer: &MultiBufferSnapshot,
 3410    ) {
 3411        self.autoclose_regions.retain(|state| {
 3412            let mut i = 0;
 3413            while let Some(selection) = selections.get(i) {
 3414                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3415                    selections = &selections[1..];
 3416                    continue;
 3417                }
 3418                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3419                    break;
 3420                }
 3421                if selection.id == state.selection_id {
 3422                    return true;
 3423                } else {
 3424                    i += 1;
 3425                }
 3426            }
 3427            false
 3428        });
 3429    }
 3430
 3431    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3432        let offset = position.to_offset(buffer);
 3433        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3434        if offset > word_range.start && kind == Some(CharKind::Word) {
 3435            Some(
 3436                buffer
 3437                    .text_for_range(word_range.start..offset)
 3438                    .collect::<String>(),
 3439            )
 3440        } else {
 3441            None
 3442        }
 3443    }
 3444
 3445    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3446        self.refresh_inlay_hints(
 3447            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3448            cx,
 3449        );
 3450    }
 3451
 3452    pub fn inlay_hints_enabled(&self) -> bool {
 3453        self.inlay_hint_cache.enabled
 3454    }
 3455
 3456    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3457        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3458            return;
 3459        }
 3460
 3461        let reason_description = reason.description();
 3462        let ignore_debounce = matches!(
 3463            reason,
 3464            InlayHintRefreshReason::SettingsChange(_)
 3465                | InlayHintRefreshReason::Toggle(_)
 3466                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3467        );
 3468        let (invalidate_cache, required_languages) = match reason {
 3469            InlayHintRefreshReason::Toggle(enabled) => {
 3470                self.inlay_hint_cache.enabled = enabled;
 3471                if enabled {
 3472                    (InvalidationStrategy::RefreshRequested, None)
 3473                } else {
 3474                    self.inlay_hint_cache.clear();
 3475                    self.splice_inlays(
 3476                        self.visible_inlay_hints(cx)
 3477                            .iter()
 3478                            .map(|inlay| inlay.id)
 3479                            .collect(),
 3480                        Vec::new(),
 3481                        cx,
 3482                    );
 3483                    return;
 3484                }
 3485            }
 3486            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3487                match self.inlay_hint_cache.update_settings(
 3488                    &self.buffer,
 3489                    new_settings,
 3490                    self.visible_inlay_hints(cx),
 3491                    cx,
 3492                ) {
 3493                    ControlFlow::Break(Some(InlaySplice {
 3494                        to_remove,
 3495                        to_insert,
 3496                    })) => {
 3497                        self.splice_inlays(to_remove, to_insert, cx);
 3498                        return;
 3499                    }
 3500                    ControlFlow::Break(None) => return,
 3501                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3502                }
 3503            }
 3504            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3505                if let Some(InlaySplice {
 3506                    to_remove,
 3507                    to_insert,
 3508                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3509                {
 3510                    self.splice_inlays(to_remove, to_insert, cx);
 3511                }
 3512                return;
 3513            }
 3514            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3515            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3516                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3517            }
 3518            InlayHintRefreshReason::RefreshRequested => {
 3519                (InvalidationStrategy::RefreshRequested, None)
 3520            }
 3521        };
 3522
 3523        if let Some(InlaySplice {
 3524            to_remove,
 3525            to_insert,
 3526        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3527            reason_description,
 3528            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3529            invalidate_cache,
 3530            ignore_debounce,
 3531            cx,
 3532        ) {
 3533            self.splice_inlays(to_remove, to_insert, cx);
 3534        }
 3535    }
 3536
 3537    fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
 3538        self.display_map
 3539            .read(cx)
 3540            .current_inlays()
 3541            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3542            .cloned()
 3543            .collect()
 3544    }
 3545
 3546    pub fn excerpts_for_inlay_hints_query(
 3547        &self,
 3548        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3549        cx: &mut ViewContext<Editor>,
 3550    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3551        let Some(project) = self.project.as_ref() else {
 3552            return HashMap::default();
 3553        };
 3554        let project = project.read(cx);
 3555        let multi_buffer = self.buffer().read(cx);
 3556        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3557        let multi_buffer_visible_start = self
 3558            .scroll_manager
 3559            .anchor()
 3560            .anchor
 3561            .to_point(&multi_buffer_snapshot);
 3562        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3563            multi_buffer_visible_start
 3564                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3565            Bias::Left,
 3566        );
 3567        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3568        multi_buffer_snapshot
 3569            .range_to_buffer_ranges(multi_buffer_visible_range)
 3570            .into_iter()
 3571            .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
 3572            .filter_map(|(excerpt, excerpt_visible_range)| {
 3573                let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
 3574                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3575                let worktree_entry = buffer_worktree
 3576                    .read(cx)
 3577                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3578                if worktree_entry.is_ignored {
 3579                    return None;
 3580                }
 3581
 3582                let language = excerpt.buffer().language()?;
 3583                if let Some(restrict_to_languages) = restrict_to_languages {
 3584                    if !restrict_to_languages.contains(language) {
 3585                        return None;
 3586                    }
 3587                }
 3588                Some((
 3589                    excerpt.id(),
 3590                    (
 3591                        multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
 3592                        excerpt.buffer().version().clone(),
 3593                        excerpt_visible_range,
 3594                    ),
 3595                ))
 3596            })
 3597            .collect()
 3598    }
 3599
 3600    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3601        TextLayoutDetails {
 3602            text_system: cx.text_system().clone(),
 3603            editor_style: self.style.clone().unwrap(),
 3604            rem_size: cx.rem_size(),
 3605            scroll_anchor: self.scroll_manager.anchor(),
 3606            visible_rows: self.visible_line_count(),
 3607            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3608        }
 3609    }
 3610
 3611    pub fn splice_inlays(
 3612        &self,
 3613        to_remove: Vec<InlayId>,
 3614        to_insert: Vec<Inlay>,
 3615        cx: &mut ViewContext<Self>,
 3616    ) {
 3617        self.display_map.update(cx, |display_map, cx| {
 3618            display_map.splice_inlays(to_remove, to_insert, cx)
 3619        });
 3620        cx.notify();
 3621    }
 3622
 3623    fn trigger_on_type_formatting(
 3624        &self,
 3625        input: String,
 3626        cx: &mut ViewContext<Self>,
 3627    ) -> Option<Task<Result<()>>> {
 3628        if input.len() != 1 {
 3629            return None;
 3630        }
 3631
 3632        let project = self.project.as_ref()?;
 3633        let position = self.selections.newest_anchor().head();
 3634        let (buffer, buffer_position) = self
 3635            .buffer
 3636            .read(cx)
 3637            .text_anchor_for_position(position, cx)?;
 3638
 3639        let settings = language_settings::language_settings(
 3640            buffer
 3641                .read(cx)
 3642                .language_at(buffer_position)
 3643                .map(|l| l.name()),
 3644            buffer.read(cx).file(),
 3645            cx,
 3646        );
 3647        if !settings.use_on_type_format {
 3648            return None;
 3649        }
 3650
 3651        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3652        // hence we do LSP request & edit on host side only — add formats to host's history.
 3653        let push_to_lsp_host_history = true;
 3654        // If this is not the host, append its history with new edits.
 3655        let push_to_client_history = project.read(cx).is_via_collab();
 3656
 3657        let on_type_formatting = project.update(cx, |project, cx| {
 3658            project.on_type_format(
 3659                buffer.clone(),
 3660                buffer_position,
 3661                input,
 3662                push_to_lsp_host_history,
 3663                cx,
 3664            )
 3665        });
 3666        Some(cx.spawn(|editor, mut cx| async move {
 3667            if let Some(transaction) = on_type_formatting.await? {
 3668                if push_to_client_history {
 3669                    buffer
 3670                        .update(&mut cx, |buffer, _| {
 3671                            buffer.push_transaction(transaction, Instant::now());
 3672                        })
 3673                        .ok();
 3674                }
 3675                editor.update(&mut cx, |editor, cx| {
 3676                    editor.refresh_document_highlights(cx);
 3677                })?;
 3678            }
 3679            Ok(())
 3680        }))
 3681    }
 3682
 3683    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3684        if self.pending_rename.is_some() {
 3685            return;
 3686        }
 3687
 3688        let Some(provider) = self.completion_provider.as_ref() else {
 3689            return;
 3690        };
 3691
 3692        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3693            return;
 3694        }
 3695
 3696        let position = self.selections.newest_anchor().head();
 3697        let (buffer, buffer_position) =
 3698            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3699                output
 3700            } else {
 3701                return;
 3702            };
 3703        let show_completion_documentation = buffer
 3704            .read(cx)
 3705            .snapshot()
 3706            .settings_at(buffer_position, cx)
 3707            .show_completion_documentation;
 3708
 3709        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3710
 3711        let trigger_kind = match &options.trigger {
 3712            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3713                CompletionTriggerKind::TRIGGER_CHARACTER
 3714            }
 3715            _ => CompletionTriggerKind::INVOKED,
 3716        };
 3717        let completion_context = CompletionContext {
 3718            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3719                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3720                    Some(String::from(trigger))
 3721                } else {
 3722                    None
 3723                }
 3724            }),
 3725            trigger_kind,
 3726        };
 3727        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3728        let sort_completions = provider.sort_completions();
 3729
 3730        let id = post_inc(&mut self.next_completion_id);
 3731        let task = cx.spawn(|editor, mut cx| {
 3732            async move {
 3733                editor.update(&mut cx, |this, _| {
 3734                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3735                })?;
 3736                let completions = completions.await.log_err();
 3737                let menu = if let Some(completions) = completions {
 3738                    let mut menu = CompletionsMenu::new(
 3739                        id,
 3740                        sort_completions,
 3741                        show_completion_documentation,
 3742                        position,
 3743                        buffer.clone(),
 3744                        completions.into(),
 3745                    );
 3746
 3747                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3748                        .await;
 3749
 3750                    menu.visible().then_some(menu)
 3751                } else {
 3752                    None
 3753                };
 3754
 3755                editor.update(&mut cx, |editor, cx| {
 3756                    match editor.context_menu.borrow().as_ref() {
 3757                        None => {}
 3758                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3759                            if prev_menu.id > id {
 3760                                return;
 3761                            }
 3762                        }
 3763                        _ => return,
 3764                    }
 3765
 3766                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3767                        let mut menu = menu.unwrap();
 3768                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3769
 3770                        if editor.show_inline_completions_in_menu(cx) {
 3771                            if let Some(hint) = editor.inline_completion_menu_hint(cx) {
 3772                                menu.show_inline_completion_hint(hint);
 3773                            }
 3774                        } else {
 3775                            editor.discard_inline_completion(false, cx);
 3776                        }
 3777
 3778                        *editor.context_menu.borrow_mut() =
 3779                            Some(CodeContextMenu::Completions(menu));
 3780
 3781                        cx.notify();
 3782                    } else if editor.completion_tasks.len() <= 1 {
 3783                        // If there are no more completion tasks and the last menu was
 3784                        // empty, we should hide it.
 3785                        let was_hidden = editor.hide_context_menu(cx).is_none();
 3786                        // If it was already hidden and we don't show inline
 3787                        // completions in the menu, we should also show the
 3788                        // inline-completion when available.
 3789                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3790                            editor.update_visible_inline_completion(cx);
 3791                        }
 3792                    }
 3793                })?;
 3794
 3795                Ok::<_, anyhow::Error>(())
 3796            }
 3797            .log_err()
 3798        });
 3799
 3800        self.completion_tasks.push((id, task));
 3801    }
 3802
 3803    pub fn confirm_completion(
 3804        &mut self,
 3805        action: &ConfirmCompletion,
 3806        cx: &mut ViewContext<Self>,
 3807    ) -> Option<Task<Result<()>>> {
 3808        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3809    }
 3810
 3811    pub fn compose_completion(
 3812        &mut self,
 3813        action: &ComposeCompletion,
 3814        cx: &mut ViewContext<Self>,
 3815    ) -> Option<Task<Result<()>>> {
 3816        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3817    }
 3818
 3819    fn do_completion(
 3820        &mut self,
 3821        item_ix: Option<usize>,
 3822        intent: CompletionIntent,
 3823        cx: &mut ViewContext<Editor>,
 3824    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3825        use language::ToOffset as _;
 3826
 3827        let completions_menu =
 3828            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3829                menu
 3830            } else {
 3831                return None;
 3832            };
 3833
 3834        let entries = completions_menu.entries.borrow();
 3835        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3836        let mat = match mat {
 3837            CompletionEntry::InlineCompletionHint { .. } => {
 3838                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3839                cx.stop_propagation();
 3840                return Some(Task::ready(Ok(())));
 3841            }
 3842            CompletionEntry::Match(mat) => {
 3843                if self.show_inline_completions_in_menu(cx) {
 3844                    self.discard_inline_completion(true, cx);
 3845                }
 3846                mat
 3847            }
 3848        };
 3849        let candidate_id = mat.candidate_id;
 3850        drop(entries);
 3851
 3852        let buffer_handle = completions_menu.buffer;
 3853        let completion = completions_menu
 3854            .completions
 3855            .borrow()
 3856            .get(candidate_id)?
 3857            .clone();
 3858        cx.stop_propagation();
 3859
 3860        let snippet;
 3861        let text;
 3862
 3863        if completion.is_snippet() {
 3864            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3865            text = snippet.as_ref().unwrap().text.clone();
 3866        } else {
 3867            snippet = None;
 3868            text = completion.new_text.clone();
 3869        };
 3870        let selections = self.selections.all::<usize>(cx);
 3871        let buffer = buffer_handle.read(cx);
 3872        let old_range = completion.old_range.to_offset(buffer);
 3873        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3874
 3875        let newest_selection = self.selections.newest_anchor();
 3876        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3877            return None;
 3878        }
 3879
 3880        let lookbehind = newest_selection
 3881            .start
 3882            .text_anchor
 3883            .to_offset(buffer)
 3884            .saturating_sub(old_range.start);
 3885        let lookahead = old_range
 3886            .end
 3887            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3888        let mut common_prefix_len = old_text
 3889            .bytes()
 3890            .zip(text.bytes())
 3891            .take_while(|(a, b)| a == b)
 3892            .count();
 3893
 3894        let snapshot = self.buffer.read(cx).snapshot(cx);
 3895        let mut range_to_replace: Option<Range<isize>> = None;
 3896        let mut ranges = Vec::new();
 3897        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3898        for selection in &selections {
 3899            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3900                let start = selection.start.saturating_sub(lookbehind);
 3901                let end = selection.end + lookahead;
 3902                if selection.id == newest_selection.id {
 3903                    range_to_replace = Some(
 3904                        ((start + common_prefix_len) as isize - selection.start as isize)
 3905                            ..(end as isize - selection.start as isize),
 3906                    );
 3907                }
 3908                ranges.push(start + common_prefix_len..end);
 3909            } else {
 3910                common_prefix_len = 0;
 3911                ranges.clear();
 3912                ranges.extend(selections.iter().map(|s| {
 3913                    if s.id == newest_selection.id {
 3914                        range_to_replace = Some(
 3915                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3916                                - selection.start as isize
 3917                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3918                                    - selection.start as isize,
 3919                        );
 3920                        old_range.clone()
 3921                    } else {
 3922                        s.start..s.end
 3923                    }
 3924                }));
 3925                break;
 3926            }
 3927            if !self.linked_edit_ranges.is_empty() {
 3928                let start_anchor = snapshot.anchor_before(selection.head());
 3929                let end_anchor = snapshot.anchor_after(selection.tail());
 3930                if let Some(ranges) = self
 3931                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3932                {
 3933                    for (buffer, edits) in ranges {
 3934                        linked_edits.entry(buffer.clone()).or_default().extend(
 3935                            edits
 3936                                .into_iter()
 3937                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3938                        );
 3939                    }
 3940                }
 3941            }
 3942        }
 3943        let text = &text[common_prefix_len..];
 3944
 3945        cx.emit(EditorEvent::InputHandled {
 3946            utf16_range_to_replace: range_to_replace,
 3947            text: text.into(),
 3948        });
 3949
 3950        self.transact(cx, |this, cx| {
 3951            if let Some(mut snippet) = snippet {
 3952                snippet.text = text.to_string();
 3953                for tabstop in snippet
 3954                    .tabstops
 3955                    .iter_mut()
 3956                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3957                {
 3958                    tabstop.start -= common_prefix_len as isize;
 3959                    tabstop.end -= common_prefix_len as isize;
 3960                }
 3961
 3962                this.insert_snippet(&ranges, snippet, cx).log_err();
 3963            } else {
 3964                this.buffer.update(cx, |buffer, cx| {
 3965                    buffer.edit(
 3966                        ranges.iter().map(|range| (range.clone(), text)),
 3967                        this.autoindent_mode.clone(),
 3968                        cx,
 3969                    );
 3970                });
 3971            }
 3972            for (buffer, edits) in linked_edits {
 3973                buffer.update(cx, |buffer, cx| {
 3974                    let snapshot = buffer.snapshot();
 3975                    let edits = edits
 3976                        .into_iter()
 3977                        .map(|(range, text)| {
 3978                            use text::ToPoint as TP;
 3979                            let end_point = TP::to_point(&range.end, &snapshot);
 3980                            let start_point = TP::to_point(&range.start, &snapshot);
 3981                            (start_point..end_point, text)
 3982                        })
 3983                        .sorted_by_key(|(range, _)| range.start)
 3984                        .collect::<Vec<_>>();
 3985                    buffer.edit(edits, None, cx);
 3986                })
 3987            }
 3988
 3989            this.refresh_inline_completion(true, false, cx);
 3990        });
 3991
 3992        let show_new_completions_on_confirm = completion
 3993            .confirm
 3994            .as_ref()
 3995            .map_or(false, |confirm| confirm(intent, cx));
 3996        if show_new_completions_on_confirm {
 3997            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3998        }
 3999
 4000        let provider = self.completion_provider.as_ref()?;
 4001        drop(completion);
 4002        let apply_edits = provider.apply_additional_edits_for_completion(
 4003            buffer_handle,
 4004            completions_menu.completions.clone(),
 4005            candidate_id,
 4006            true,
 4007            cx,
 4008        );
 4009
 4010        let editor_settings = EditorSettings::get_global(cx);
 4011        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4012            // After the code completion is finished, users often want to know what signatures are needed.
 4013            // so we should automatically call signature_help
 4014            self.show_signature_help(&ShowSignatureHelp, cx);
 4015        }
 4016
 4017        Some(cx.foreground_executor().spawn(async move {
 4018            apply_edits.await?;
 4019            Ok(())
 4020        }))
 4021    }
 4022
 4023    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4024        let mut context_menu = self.context_menu.borrow_mut();
 4025        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4026            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4027                // Toggle if we're selecting the same one
 4028                *context_menu = None;
 4029                cx.notify();
 4030                return;
 4031            } else {
 4032                // Otherwise, clear it and start a new one
 4033                *context_menu = None;
 4034                cx.notify();
 4035            }
 4036        }
 4037        drop(context_menu);
 4038        let snapshot = self.snapshot(cx);
 4039        let deployed_from_indicator = action.deployed_from_indicator;
 4040        let mut task = self.code_actions_task.take();
 4041        let action = action.clone();
 4042        cx.spawn(|editor, mut cx| async move {
 4043            while let Some(prev_task) = task {
 4044                prev_task.await.log_err();
 4045                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4046            }
 4047
 4048            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4049                if editor.focus_handle.is_focused(cx) {
 4050                    let multibuffer_point = action
 4051                        .deployed_from_indicator
 4052                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4053                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4054                    let (buffer, buffer_row) = snapshot
 4055                        .buffer_snapshot
 4056                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4057                        .and_then(|(buffer_snapshot, range)| {
 4058                            editor
 4059                                .buffer
 4060                                .read(cx)
 4061                                .buffer(buffer_snapshot.remote_id())
 4062                                .map(|buffer| (buffer, range.start.row))
 4063                        })?;
 4064                    let (_, code_actions) = editor
 4065                        .available_code_actions
 4066                        .clone()
 4067                        .and_then(|(location, code_actions)| {
 4068                            let snapshot = location.buffer.read(cx).snapshot();
 4069                            let point_range = location.range.to_point(&snapshot);
 4070                            let point_range = point_range.start.row..=point_range.end.row;
 4071                            if point_range.contains(&buffer_row) {
 4072                                Some((location, code_actions))
 4073                            } else {
 4074                                None
 4075                            }
 4076                        })
 4077                        .unzip();
 4078                    let buffer_id = buffer.read(cx).remote_id();
 4079                    let tasks = editor
 4080                        .tasks
 4081                        .get(&(buffer_id, buffer_row))
 4082                        .map(|t| Arc::new(t.to_owned()));
 4083                    if tasks.is_none() && code_actions.is_none() {
 4084                        return None;
 4085                    }
 4086
 4087                    editor.completion_tasks.clear();
 4088                    editor.discard_inline_completion(false, cx);
 4089                    let task_context =
 4090                        tasks
 4091                            .as_ref()
 4092                            .zip(editor.project.clone())
 4093                            .map(|(tasks, project)| {
 4094                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4095                            });
 4096
 4097                    Some(cx.spawn(|editor, mut cx| async move {
 4098                        let task_context = match task_context {
 4099                            Some(task_context) => task_context.await,
 4100                            None => None,
 4101                        };
 4102                        let resolved_tasks =
 4103                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4104                                Rc::new(ResolvedTasks {
 4105                                    templates: tasks.resolve(&task_context).collect(),
 4106                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4107                                        multibuffer_point.row,
 4108                                        tasks.column,
 4109                                    )),
 4110                                })
 4111                            });
 4112                        let spawn_straight_away = resolved_tasks
 4113                            .as_ref()
 4114                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4115                            && code_actions
 4116                                .as_ref()
 4117                                .map_or(true, |actions| actions.is_empty());
 4118                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4119                            *editor.context_menu.borrow_mut() =
 4120                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4121                                    buffer,
 4122                                    actions: CodeActionContents {
 4123                                        tasks: resolved_tasks,
 4124                                        actions: code_actions,
 4125                                    },
 4126                                    selected_item: Default::default(),
 4127                                    scroll_handle: UniformListScrollHandle::default(),
 4128                                    deployed_from_indicator,
 4129                                }));
 4130                            if spawn_straight_away {
 4131                                if let Some(task) = editor.confirm_code_action(
 4132                                    &ConfirmCodeAction { item_ix: Some(0) },
 4133                                    cx,
 4134                                ) {
 4135                                    cx.notify();
 4136                                    return task;
 4137                                }
 4138                            }
 4139                            cx.notify();
 4140                            Task::ready(Ok(()))
 4141                        }) {
 4142                            task.await
 4143                        } else {
 4144                            Ok(())
 4145                        }
 4146                    }))
 4147                } else {
 4148                    Some(Task::ready(Ok(())))
 4149                }
 4150            })?;
 4151            if let Some(task) = spawned_test_task {
 4152                task.await?;
 4153            }
 4154
 4155            Ok::<_, anyhow::Error>(())
 4156        })
 4157        .detach_and_log_err(cx);
 4158    }
 4159
 4160    pub fn confirm_code_action(
 4161        &mut self,
 4162        action: &ConfirmCodeAction,
 4163        cx: &mut ViewContext<Self>,
 4164    ) -> Option<Task<Result<()>>> {
 4165        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4166            menu
 4167        } else {
 4168            return None;
 4169        };
 4170        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4171        let action = actions_menu.actions.get(action_ix)?;
 4172        let title = action.label();
 4173        let buffer = actions_menu.buffer;
 4174        let workspace = self.workspace()?;
 4175
 4176        match action {
 4177            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4178                workspace.update(cx, |workspace, cx| {
 4179                    workspace::tasks::schedule_resolved_task(
 4180                        workspace,
 4181                        task_source_kind,
 4182                        resolved_task,
 4183                        false,
 4184                        cx,
 4185                    );
 4186
 4187                    Some(Task::ready(Ok(())))
 4188                })
 4189            }
 4190            CodeActionsItem::CodeAction {
 4191                excerpt_id,
 4192                action,
 4193                provider,
 4194            } => {
 4195                let apply_code_action =
 4196                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4197                let workspace = workspace.downgrade();
 4198                Some(cx.spawn(|editor, cx| async move {
 4199                    let project_transaction = apply_code_action.await?;
 4200                    Self::open_project_transaction(
 4201                        &editor,
 4202                        workspace,
 4203                        project_transaction,
 4204                        title,
 4205                        cx,
 4206                    )
 4207                    .await
 4208                }))
 4209            }
 4210        }
 4211    }
 4212
 4213    pub async fn open_project_transaction(
 4214        this: &WeakView<Editor>,
 4215        workspace: WeakView<Workspace>,
 4216        transaction: ProjectTransaction,
 4217        title: String,
 4218        mut cx: AsyncWindowContext,
 4219    ) -> Result<()> {
 4220        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4221        cx.update(|cx| {
 4222            entries.sort_unstable_by_key(|(buffer, _)| {
 4223                buffer.read(cx).file().map(|f| f.path().clone())
 4224            });
 4225        })?;
 4226
 4227        // If the project transaction's edits are all contained within this editor, then
 4228        // avoid opening a new editor to display them.
 4229
 4230        if let Some((buffer, transaction)) = entries.first() {
 4231            if entries.len() == 1 {
 4232                let excerpt = this.update(&mut cx, |editor, cx| {
 4233                    editor
 4234                        .buffer()
 4235                        .read(cx)
 4236                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4237                })?;
 4238                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4239                    if excerpted_buffer == *buffer {
 4240                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4241                            let excerpt_range = excerpt_range.to_offset(buffer);
 4242                            buffer
 4243                                .edited_ranges_for_transaction::<usize>(transaction)
 4244                                .all(|range| {
 4245                                    excerpt_range.start <= range.start
 4246                                        && excerpt_range.end >= range.end
 4247                                })
 4248                        })?;
 4249
 4250                        if all_edits_within_excerpt {
 4251                            return Ok(());
 4252                        }
 4253                    }
 4254                }
 4255            }
 4256        } else {
 4257            return Ok(());
 4258        }
 4259
 4260        let mut ranges_to_highlight = Vec::new();
 4261        let excerpt_buffer = cx.new_model(|cx| {
 4262            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4263            for (buffer_handle, transaction) in &entries {
 4264                let buffer = buffer_handle.read(cx);
 4265                ranges_to_highlight.extend(
 4266                    multibuffer.push_excerpts_with_context_lines(
 4267                        buffer_handle.clone(),
 4268                        buffer
 4269                            .edited_ranges_for_transaction::<usize>(transaction)
 4270                            .collect(),
 4271                        DEFAULT_MULTIBUFFER_CONTEXT,
 4272                        cx,
 4273                    ),
 4274                );
 4275            }
 4276            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4277            multibuffer
 4278        })?;
 4279
 4280        workspace.update(&mut cx, |workspace, cx| {
 4281            let project = workspace.project().clone();
 4282            let editor =
 4283                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4284            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4285            editor.update(cx, |editor, cx| {
 4286                editor.highlight_background::<Self>(
 4287                    &ranges_to_highlight,
 4288                    |theme| theme.editor_highlighted_line_background,
 4289                    cx,
 4290                );
 4291            });
 4292        })?;
 4293
 4294        Ok(())
 4295    }
 4296
 4297    pub fn clear_code_action_providers(&mut self) {
 4298        self.code_action_providers.clear();
 4299        self.available_code_actions.take();
 4300    }
 4301
 4302    pub fn add_code_action_provider(
 4303        &mut self,
 4304        provider: Rc<dyn CodeActionProvider>,
 4305        cx: &mut ViewContext<Self>,
 4306    ) {
 4307        if self
 4308            .code_action_providers
 4309            .iter()
 4310            .any(|existing_provider| existing_provider.id() == provider.id())
 4311        {
 4312            return;
 4313        }
 4314
 4315        self.code_action_providers.push(provider);
 4316        self.refresh_code_actions(cx);
 4317    }
 4318
 4319    pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
 4320        self.code_action_providers
 4321            .retain(|provider| provider.id() != id);
 4322        self.refresh_code_actions(cx);
 4323    }
 4324
 4325    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4326        let buffer = self.buffer.read(cx);
 4327        let newest_selection = self.selections.newest_anchor().clone();
 4328        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4329        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4330        if start_buffer != end_buffer {
 4331            return None;
 4332        }
 4333
 4334        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4335            cx.background_executor()
 4336                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4337                .await;
 4338
 4339            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4340                let providers = this.code_action_providers.clone();
 4341                let tasks = this
 4342                    .code_action_providers
 4343                    .iter()
 4344                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4345                    .collect::<Vec<_>>();
 4346                (providers, tasks)
 4347            })?;
 4348
 4349            let mut actions = Vec::new();
 4350            for (provider, provider_actions) in
 4351                providers.into_iter().zip(future::join_all(tasks).await)
 4352            {
 4353                if let Some(provider_actions) = provider_actions.log_err() {
 4354                    actions.extend(provider_actions.into_iter().map(|action| {
 4355                        AvailableCodeAction {
 4356                            excerpt_id: newest_selection.start.excerpt_id,
 4357                            action,
 4358                            provider: provider.clone(),
 4359                        }
 4360                    }));
 4361                }
 4362            }
 4363
 4364            this.update(&mut cx, |this, cx| {
 4365                this.available_code_actions = if actions.is_empty() {
 4366                    None
 4367                } else {
 4368                    Some((
 4369                        Location {
 4370                            buffer: start_buffer,
 4371                            range: start..end,
 4372                        },
 4373                        actions.into(),
 4374                    ))
 4375                };
 4376                cx.notify();
 4377            })
 4378        }));
 4379        None
 4380    }
 4381
 4382    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4383        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4384            self.show_git_blame_inline = false;
 4385
 4386            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4387                cx.background_executor().timer(delay).await;
 4388
 4389                this.update(&mut cx, |this, cx| {
 4390                    this.show_git_blame_inline = true;
 4391                    cx.notify();
 4392                })
 4393                .log_err();
 4394            }));
 4395        }
 4396    }
 4397
 4398    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4399        if self.pending_rename.is_some() {
 4400            return None;
 4401        }
 4402
 4403        let provider = self.semantics_provider.clone()?;
 4404        let buffer = self.buffer.read(cx);
 4405        let newest_selection = self.selections.newest_anchor().clone();
 4406        let cursor_position = newest_selection.head();
 4407        let (cursor_buffer, cursor_buffer_position) =
 4408            buffer.text_anchor_for_position(cursor_position, cx)?;
 4409        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4410        if cursor_buffer != tail_buffer {
 4411            return None;
 4412        }
 4413        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4414        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4415            cx.background_executor()
 4416                .timer(Duration::from_millis(debounce))
 4417                .await;
 4418
 4419            let highlights = if let Some(highlights) = cx
 4420                .update(|cx| {
 4421                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4422                })
 4423                .ok()
 4424                .flatten()
 4425            {
 4426                highlights.await.log_err()
 4427            } else {
 4428                None
 4429            };
 4430
 4431            if let Some(highlights) = highlights {
 4432                this.update(&mut cx, |this, cx| {
 4433                    if this.pending_rename.is_some() {
 4434                        return;
 4435                    }
 4436
 4437                    let buffer_id = cursor_position.buffer_id;
 4438                    let buffer = this.buffer.read(cx);
 4439                    if !buffer
 4440                        .text_anchor_for_position(cursor_position, cx)
 4441                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4442                    {
 4443                        return;
 4444                    }
 4445
 4446                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4447                    let mut write_ranges = Vec::new();
 4448                    let mut read_ranges = Vec::new();
 4449                    for highlight in highlights {
 4450                        for (excerpt_id, excerpt_range) in
 4451                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4452                        {
 4453                            let start = highlight
 4454                                .range
 4455                                .start
 4456                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4457                            let end = highlight
 4458                                .range
 4459                                .end
 4460                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4461                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4462                                continue;
 4463                            }
 4464
 4465                            let range = Anchor {
 4466                                buffer_id,
 4467                                excerpt_id,
 4468                                text_anchor: start,
 4469                            }..Anchor {
 4470                                buffer_id,
 4471                                excerpt_id,
 4472                                text_anchor: end,
 4473                            };
 4474                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4475                                write_ranges.push(range);
 4476                            } else {
 4477                                read_ranges.push(range);
 4478                            }
 4479                        }
 4480                    }
 4481
 4482                    this.highlight_background::<DocumentHighlightRead>(
 4483                        &read_ranges,
 4484                        |theme| theme.editor_document_highlight_read_background,
 4485                        cx,
 4486                    );
 4487                    this.highlight_background::<DocumentHighlightWrite>(
 4488                        &write_ranges,
 4489                        |theme| theme.editor_document_highlight_write_background,
 4490                        cx,
 4491                    );
 4492                    cx.notify();
 4493                })
 4494                .log_err();
 4495            }
 4496        }));
 4497        None
 4498    }
 4499
 4500    pub fn refresh_inline_completion(
 4501        &mut self,
 4502        debounce: bool,
 4503        user_requested: bool,
 4504        cx: &mut ViewContext<Self>,
 4505    ) -> Option<()> {
 4506        let provider = self.inline_completion_provider()?;
 4507        let cursor = self.selections.newest_anchor().head();
 4508        let (buffer, cursor_buffer_position) =
 4509            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4510
 4511        if !user_requested
 4512            && (!self.enable_inline_completions
 4513                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4514                || !self.is_focused(cx)
 4515                || buffer.read(cx).is_empty())
 4516        {
 4517            self.discard_inline_completion(false, cx);
 4518            return None;
 4519        }
 4520
 4521        self.update_visible_inline_completion(cx);
 4522        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4523        Some(())
 4524    }
 4525
 4526    fn cycle_inline_completion(
 4527        &mut self,
 4528        direction: Direction,
 4529        cx: &mut ViewContext<Self>,
 4530    ) -> Option<()> {
 4531        let provider = self.inline_completion_provider()?;
 4532        let cursor = self.selections.newest_anchor().head();
 4533        let (buffer, cursor_buffer_position) =
 4534            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4535        if !self.enable_inline_completions
 4536            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4537        {
 4538            return None;
 4539        }
 4540
 4541        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4542        self.update_visible_inline_completion(cx);
 4543
 4544        Some(())
 4545    }
 4546
 4547    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4548        if !self.has_active_inline_completion() {
 4549            self.refresh_inline_completion(false, true, cx);
 4550            return;
 4551        }
 4552
 4553        self.update_visible_inline_completion(cx);
 4554    }
 4555
 4556    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4557        self.show_cursor_names(cx);
 4558    }
 4559
 4560    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4561        self.show_cursor_names = true;
 4562        cx.notify();
 4563        cx.spawn(|this, mut cx| async move {
 4564            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4565            this.update(&mut cx, |this, cx| {
 4566                this.show_cursor_names = false;
 4567                cx.notify()
 4568            })
 4569            .ok()
 4570        })
 4571        .detach();
 4572    }
 4573
 4574    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4575        if self.has_active_inline_completion() {
 4576            self.cycle_inline_completion(Direction::Next, cx);
 4577        } else {
 4578            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4579            if is_copilot_disabled {
 4580                cx.propagate();
 4581            }
 4582        }
 4583    }
 4584
 4585    pub fn previous_inline_completion(
 4586        &mut self,
 4587        _: &PreviousInlineCompletion,
 4588        cx: &mut ViewContext<Self>,
 4589    ) {
 4590        if self.has_active_inline_completion() {
 4591            self.cycle_inline_completion(Direction::Prev, cx);
 4592        } else {
 4593            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4594            if is_copilot_disabled {
 4595                cx.propagate();
 4596            }
 4597        }
 4598    }
 4599
 4600    pub fn accept_inline_completion(
 4601        &mut self,
 4602        _: &AcceptInlineCompletion,
 4603        cx: &mut ViewContext<Self>,
 4604    ) {
 4605        let buffer = self.buffer.read(cx);
 4606        let snapshot = buffer.snapshot(cx);
 4607        let selection = self.selections.newest_adjusted(cx);
 4608        let cursor = selection.head();
 4609        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4610        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4611        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4612        {
 4613            if cursor.column < suggested_indent.len
 4614                && cursor.column <= current_indent.len
 4615                && current_indent.len <= suggested_indent.len
 4616            {
 4617                self.tab(&Default::default(), cx);
 4618                return;
 4619            }
 4620        }
 4621
 4622        if self.show_inline_completions_in_menu(cx) {
 4623            self.hide_context_menu(cx);
 4624        }
 4625
 4626        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 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 let Some(provider) = self.inline_completion_provider() {
 4641                    provider.accept(cx);
 4642                }
 4643
 4644                let snapshot = self.buffer.read(cx).snapshot(cx);
 4645                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4646
 4647                self.buffer.update(cx, |buffer, cx| {
 4648                    buffer.edit(edits.iter().cloned(), None, cx)
 4649                });
 4650
 4651                self.change_selections(None, cx, |s| {
 4652                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4653                });
 4654
 4655                self.update_visible_inline_completion(cx);
 4656                if self.active_inline_completion.is_none() {
 4657                    self.refresh_inline_completion(true, true, cx);
 4658                }
 4659
 4660                cx.notify();
 4661            }
 4662        }
 4663    }
 4664
 4665    pub fn accept_partial_inline_completion(
 4666        &mut self,
 4667        _: &AcceptPartialInlineCompletion,
 4668        cx: &mut ViewContext<Self>,
 4669    ) {
 4670        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4671            return;
 4672        };
 4673        if self.selections.count() != 1 {
 4674            return;
 4675        }
 4676
 4677        self.report_inline_completion_event(true, cx);
 4678
 4679        match &active_inline_completion.completion {
 4680            InlineCompletion::Move(position) => {
 4681                let position = *position;
 4682                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4683                    selections.select_anchor_ranges([position..position]);
 4684                });
 4685            }
 4686            InlineCompletion::Edit(edits) => {
 4687                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4688                    let text = edits[0].1.as_str();
 4689                    let mut partial_completion = text
 4690                        .chars()
 4691                        .by_ref()
 4692                        .take_while(|c| c.is_alphabetic())
 4693                        .collect::<String>();
 4694                    if partial_completion.is_empty() {
 4695                        partial_completion = text
 4696                            .chars()
 4697                            .by_ref()
 4698                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4699                            .collect::<String>();
 4700                    }
 4701
 4702                    cx.emit(EditorEvent::InputHandled {
 4703                        utf16_range_to_replace: None,
 4704                        text: partial_completion.clone().into(),
 4705                    });
 4706
 4707                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4708
 4709                    self.refresh_inline_completion(true, true, cx);
 4710                    cx.notify();
 4711                }
 4712            }
 4713        }
 4714    }
 4715
 4716    fn discard_inline_completion(
 4717        &mut self,
 4718        should_report_inline_completion_event: bool,
 4719        cx: &mut ViewContext<Self>,
 4720    ) -> bool {
 4721        if should_report_inline_completion_event {
 4722            self.report_inline_completion_event(false, cx);
 4723        }
 4724
 4725        if let Some(provider) = self.inline_completion_provider() {
 4726            provider.discard(cx);
 4727        }
 4728
 4729        self.take_active_inline_completion(cx).is_some()
 4730    }
 4731
 4732    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4733        let Some(provider) = self.inline_completion_provider() else {
 4734            return;
 4735        };
 4736        let Some(project) = self.project.as_ref() else {
 4737            return;
 4738        };
 4739        let Some((_, buffer, _)) = self
 4740            .buffer
 4741            .read(cx)
 4742            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4743        else {
 4744            return;
 4745        };
 4746
 4747        let project = project.read(cx);
 4748        let extension = buffer
 4749            .read(cx)
 4750            .file()
 4751            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4752        project.client().telemetry().report_inline_completion_event(
 4753            provider.name().into(),
 4754            accepted,
 4755            extension,
 4756        );
 4757    }
 4758
 4759    pub fn has_active_inline_completion(&self) -> bool {
 4760        self.active_inline_completion.is_some()
 4761    }
 4762
 4763    fn take_active_inline_completion(
 4764        &mut self,
 4765        cx: &mut ViewContext<Self>,
 4766    ) -> Option<InlineCompletion> {
 4767        let active_inline_completion = self.active_inline_completion.take()?;
 4768        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4769        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4770        Some(active_inline_completion.completion)
 4771    }
 4772
 4773    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4774        let selection = self.selections.newest_anchor();
 4775        let cursor = selection.head();
 4776        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4777        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4778        let excerpt_id = cursor.excerpt_id;
 4779
 4780        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 4781            && (self.context_menu.borrow().is_some()
 4782                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 4783        if completions_menu_has_precedence
 4784            || !offset_selection.is_empty()
 4785            || self
 4786                .active_inline_completion
 4787                .as_ref()
 4788                .map_or(false, |completion| {
 4789                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4790                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4791                    !invalidation_range.contains(&offset_selection.head())
 4792                })
 4793        {
 4794            self.discard_inline_completion(false, cx);
 4795            return None;
 4796        }
 4797
 4798        self.take_active_inline_completion(cx);
 4799        let provider = self.inline_completion_provider()?;
 4800
 4801        let (buffer, cursor_buffer_position) =
 4802            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4803
 4804        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4805        let edits = completion
 4806            .edits
 4807            .into_iter()
 4808            .flat_map(|(range, new_text)| {
 4809                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4810                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4811                Some((start..end, new_text))
 4812            })
 4813            .collect::<Vec<_>>();
 4814        if edits.is_empty() {
 4815            return None;
 4816        }
 4817
 4818        let first_edit_start = edits.first().unwrap().0.start;
 4819        let edit_start_row = first_edit_start
 4820            .to_point(&multibuffer)
 4821            .row
 4822            .saturating_sub(2);
 4823
 4824        let last_edit_end = edits.last().unwrap().0.end;
 4825        let edit_end_row = cmp::min(
 4826            multibuffer.max_point().row,
 4827            last_edit_end.to_point(&multibuffer).row + 2,
 4828        );
 4829
 4830        let cursor_row = cursor.to_point(&multibuffer).row;
 4831
 4832        let mut inlay_ids = Vec::new();
 4833        let invalidation_row_range;
 4834        let completion;
 4835        if cursor_row < edit_start_row {
 4836            invalidation_row_range = cursor_row..edit_end_row;
 4837            completion = InlineCompletion::Move(first_edit_start);
 4838        } else if cursor_row > edit_end_row {
 4839            invalidation_row_range = edit_start_row..cursor_row;
 4840            completion = InlineCompletion::Move(first_edit_start);
 4841        } else {
 4842            if edits
 4843                .iter()
 4844                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4845            {
 4846                let mut inlays = Vec::new();
 4847                for (range, new_text) in &edits {
 4848                    let inlay = Inlay::inline_completion(
 4849                        post_inc(&mut self.next_inlay_id),
 4850                        range.start,
 4851                        new_text.as_str(),
 4852                    );
 4853                    inlay_ids.push(inlay.id);
 4854                    inlays.push(inlay);
 4855                }
 4856
 4857                self.splice_inlays(vec![], inlays, cx);
 4858            } else {
 4859                let background_color = cx.theme().status().deleted_background;
 4860                self.highlight_text::<InlineCompletionHighlight>(
 4861                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4862                    HighlightStyle {
 4863                        background_color: Some(background_color),
 4864                        ..Default::default()
 4865                    },
 4866                    cx,
 4867                );
 4868            }
 4869
 4870            invalidation_row_range = edit_start_row..edit_end_row;
 4871            completion = InlineCompletion::Edit(edits);
 4872        };
 4873
 4874        let invalidation_range = multibuffer
 4875            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4876            ..multibuffer.anchor_after(Point::new(
 4877                invalidation_row_range.end,
 4878                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4879            ));
 4880
 4881        self.active_inline_completion = Some(InlineCompletionState {
 4882            inlay_ids,
 4883            completion,
 4884            invalidation_range,
 4885        });
 4886
 4887        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 4888            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4889                match self.context_menu.borrow_mut().as_mut() {
 4890                    Some(CodeContextMenu::Completions(menu)) => {
 4891                        menu.show_inline_completion_hint(hint);
 4892                    }
 4893                    _ => {}
 4894                }
 4895            }
 4896        }
 4897
 4898        cx.notify();
 4899
 4900        Some(())
 4901    }
 4902
 4903    fn inline_completion_menu_hint(
 4904        &mut self,
 4905        cx: &mut ViewContext<Self>,
 4906    ) -> Option<InlineCompletionMenuHint> {
 4907        if self.has_active_inline_completion() {
 4908            let provider_name = self.inline_completion_provider()?.display_name();
 4909            let editor_snapshot = self.snapshot(cx);
 4910
 4911            let text = match &self.active_inline_completion.as_ref()?.completion {
 4912                InlineCompletion::Edit(edits) => {
 4913                    inline_completion_edit_text(&editor_snapshot, edits, true, cx)
 4914                }
 4915                InlineCompletion::Move(target) => {
 4916                    let target_point =
 4917                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4918                    let target_line = target_point.row + 1;
 4919                    InlineCompletionText::Move(
 4920                        format!("Jump to edit in line {}", target_line).into(),
 4921                    )
 4922                }
 4923            };
 4924
 4925            Some(InlineCompletionMenuHint {
 4926                provider_name,
 4927                text,
 4928            })
 4929        } else {
 4930            None
 4931        }
 4932    }
 4933
 4934    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4935        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4936    }
 4937
 4938    fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
 4939        EditorSettings::get_global(cx).show_inline_completions_in_menu
 4940            && self
 4941                .inline_completion_provider()
 4942                .map_or(false, |provider| provider.show_completions_in_menu())
 4943    }
 4944
 4945    fn render_code_actions_indicator(
 4946        &self,
 4947        _style: &EditorStyle,
 4948        row: DisplayRow,
 4949        is_active: bool,
 4950        cx: &mut ViewContext<Self>,
 4951    ) -> Option<IconButton> {
 4952        if self.available_code_actions.is_some() {
 4953            Some(
 4954                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4955                    .shape(ui::IconButtonShape::Square)
 4956                    .icon_size(IconSize::XSmall)
 4957                    .icon_color(Color::Muted)
 4958                    .toggle_state(is_active)
 4959                    .tooltip({
 4960                        let focus_handle = self.focus_handle.clone();
 4961                        move |cx| {
 4962                            Tooltip::for_action_in(
 4963                                "Toggle Code Actions",
 4964                                &ToggleCodeActions {
 4965                                    deployed_from_indicator: None,
 4966                                },
 4967                                &focus_handle,
 4968                                cx,
 4969                            )
 4970                        }
 4971                    })
 4972                    .on_click(cx.listener(move |editor, _e, cx| {
 4973                        editor.focus(cx);
 4974                        editor.toggle_code_actions(
 4975                            &ToggleCodeActions {
 4976                                deployed_from_indicator: Some(row),
 4977                            },
 4978                            cx,
 4979                        );
 4980                    })),
 4981            )
 4982        } else {
 4983            None
 4984        }
 4985    }
 4986
 4987    fn clear_tasks(&mut self) {
 4988        self.tasks.clear()
 4989    }
 4990
 4991    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4992        if self.tasks.insert(key, value).is_some() {
 4993            // This case should hopefully be rare, but just in case...
 4994            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4995        }
 4996    }
 4997
 4998    fn build_tasks_context(
 4999        project: &Model<Project>,
 5000        buffer: &Model<Buffer>,
 5001        buffer_row: u32,
 5002        tasks: &Arc<RunnableTasks>,
 5003        cx: &mut ViewContext<Self>,
 5004    ) -> Task<Option<task::TaskContext>> {
 5005        let position = Point::new(buffer_row, tasks.column);
 5006        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5007        let location = Location {
 5008            buffer: buffer.clone(),
 5009            range: range_start..range_start,
 5010        };
 5011        // Fill in the environmental variables from the tree-sitter captures
 5012        let mut captured_task_variables = TaskVariables::default();
 5013        for (capture_name, value) in tasks.extra_variables.clone() {
 5014            captured_task_variables.insert(
 5015                task::VariableName::Custom(capture_name.into()),
 5016                value.clone(),
 5017            );
 5018        }
 5019        project.update(cx, |project, cx| {
 5020            project.task_store().update(cx, |task_store, cx| {
 5021                task_store.task_context_for_location(captured_task_variables, location, cx)
 5022            })
 5023        })
 5024    }
 5025
 5026    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5027        let Some((workspace, _)) = self.workspace.clone() else {
 5028            return;
 5029        };
 5030        let Some(project) = self.project.clone() else {
 5031            return;
 5032        };
 5033
 5034        // Try to find a closest, enclosing node using tree-sitter that has a
 5035        // task
 5036        let Some((buffer, buffer_row, tasks)) = self
 5037            .find_enclosing_node_task(cx)
 5038            // Or find the task that's closest in row-distance.
 5039            .or_else(|| self.find_closest_task(cx))
 5040        else {
 5041            return;
 5042        };
 5043
 5044        let reveal_strategy = action.reveal;
 5045        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5046        cx.spawn(|_, mut cx| async move {
 5047            let context = task_context.await?;
 5048            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5049
 5050            let resolved = resolved_task.resolved.as_mut()?;
 5051            resolved.reveal = reveal_strategy;
 5052
 5053            workspace
 5054                .update(&mut cx, |workspace, cx| {
 5055                    workspace::tasks::schedule_resolved_task(
 5056                        workspace,
 5057                        task_source_kind,
 5058                        resolved_task,
 5059                        false,
 5060                        cx,
 5061                    );
 5062                })
 5063                .ok()
 5064        })
 5065        .detach();
 5066    }
 5067
 5068    fn find_closest_task(
 5069        &mut self,
 5070        cx: &mut ViewContext<Self>,
 5071    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5072        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5073
 5074        let ((buffer_id, row), tasks) = self
 5075            .tasks
 5076            .iter()
 5077            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5078
 5079        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5080        let tasks = Arc::new(tasks.to_owned());
 5081        Some((buffer, *row, tasks))
 5082    }
 5083
 5084    fn find_enclosing_node_task(
 5085        &mut self,
 5086        cx: &mut ViewContext<Self>,
 5087    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5088        let snapshot = self.buffer.read(cx).snapshot(cx);
 5089        let offset = self.selections.newest::<usize>(cx).head();
 5090        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5091        let buffer_id = excerpt.buffer().remote_id();
 5092
 5093        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5094        let mut cursor = layer.node().walk();
 5095
 5096        while cursor.goto_first_child_for_byte(offset).is_some() {
 5097            if cursor.node().end_byte() == offset {
 5098                cursor.goto_next_sibling();
 5099            }
 5100        }
 5101
 5102        // Ascend to the smallest ancestor that contains the range and has a task.
 5103        loop {
 5104            let node = cursor.node();
 5105            let node_range = node.byte_range();
 5106            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5107
 5108            // Check if this node contains our offset
 5109            if node_range.start <= offset && node_range.end >= offset {
 5110                // If it contains offset, check for task
 5111                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5112                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5113                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5114                }
 5115            }
 5116
 5117            if !cursor.goto_parent() {
 5118                break;
 5119            }
 5120        }
 5121        None
 5122    }
 5123
 5124    fn render_run_indicator(
 5125        &self,
 5126        _style: &EditorStyle,
 5127        is_active: bool,
 5128        row: DisplayRow,
 5129        cx: &mut ViewContext<Self>,
 5130    ) -> IconButton {
 5131        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5132            .shape(ui::IconButtonShape::Square)
 5133            .icon_size(IconSize::XSmall)
 5134            .icon_color(Color::Muted)
 5135            .toggle_state(is_active)
 5136            .on_click(cx.listener(move |editor, _e, cx| {
 5137                editor.focus(cx);
 5138                editor.toggle_code_actions(
 5139                    &ToggleCodeActions {
 5140                        deployed_from_indicator: Some(row),
 5141                    },
 5142                    cx,
 5143                );
 5144            }))
 5145    }
 5146
 5147    #[cfg(any(feature = "test-support", test))]
 5148    pub fn context_menu_visible(&self) -> bool {
 5149        self.context_menu
 5150            .borrow()
 5151            .as_ref()
 5152            .map_or(false, |menu| menu.visible())
 5153    }
 5154
 5155    #[cfg(feature = "test-support")]
 5156    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5157        self.context_menu
 5158            .borrow()
 5159            .as_ref()
 5160            .map_or(false, |menu| match menu {
 5161                CodeContextMenu::Completions(menu) => {
 5162                    menu.entries.borrow().first().map_or(false, |entry| {
 5163                        matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5164                    })
 5165                }
 5166                CodeContextMenu::CodeActions(_) => false,
 5167            })
 5168    }
 5169
 5170    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5171        self.context_menu
 5172            .borrow()
 5173            .as_ref()
 5174            .map(|menu| menu.origin(cursor_position))
 5175    }
 5176
 5177    fn render_context_menu(
 5178        &self,
 5179        style: &EditorStyle,
 5180        max_height_in_lines: u32,
 5181        cx: &mut ViewContext<Editor>,
 5182    ) -> Option<AnyElement> {
 5183        self.context_menu.borrow().as_ref().and_then(|menu| {
 5184            if menu.visible() {
 5185                Some(menu.render(style, max_height_in_lines, cx))
 5186            } else {
 5187                None
 5188            }
 5189        })
 5190    }
 5191
 5192    fn render_context_menu_aside(
 5193        &self,
 5194        style: &EditorStyle,
 5195        max_size: Size<Pixels>,
 5196        cx: &mut ViewContext<Editor>,
 5197    ) -> Option<AnyElement> {
 5198        self.context_menu.borrow().as_ref().and_then(|menu| {
 5199            if menu.visible() {
 5200                menu.render_aside(
 5201                    style,
 5202                    max_size,
 5203                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5204                    cx,
 5205                )
 5206            } else {
 5207                None
 5208            }
 5209        })
 5210    }
 5211
 5212    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5213        cx.notify();
 5214        self.completion_tasks.clear();
 5215        let context_menu = self.context_menu.borrow_mut().take();
 5216        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5217            self.update_visible_inline_completion(cx);
 5218        }
 5219        context_menu
 5220    }
 5221
 5222    fn show_snippet_choices(
 5223        &mut self,
 5224        choices: &Vec<String>,
 5225        selection: Range<Anchor>,
 5226        cx: &mut ViewContext<Self>,
 5227    ) {
 5228        if selection.start.buffer_id.is_none() {
 5229            return;
 5230        }
 5231        let buffer_id = selection.start.buffer_id.unwrap();
 5232        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5233        let id = post_inc(&mut self.next_completion_id);
 5234
 5235        if let Some(buffer) = buffer {
 5236            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5237                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5238            ));
 5239        }
 5240    }
 5241
 5242    pub fn insert_snippet(
 5243        &mut self,
 5244        insertion_ranges: &[Range<usize>],
 5245        snippet: Snippet,
 5246        cx: &mut ViewContext<Self>,
 5247    ) -> Result<()> {
 5248        struct Tabstop<T> {
 5249            is_end_tabstop: bool,
 5250            ranges: Vec<Range<T>>,
 5251            choices: Option<Vec<String>>,
 5252        }
 5253
 5254        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5255            let snippet_text: Arc<str> = snippet.text.clone().into();
 5256            buffer.edit(
 5257                insertion_ranges
 5258                    .iter()
 5259                    .cloned()
 5260                    .map(|range| (range, snippet_text.clone())),
 5261                Some(AutoindentMode::EachLine),
 5262                cx,
 5263            );
 5264
 5265            let snapshot = &*buffer.read(cx);
 5266            let snippet = &snippet;
 5267            snippet
 5268                .tabstops
 5269                .iter()
 5270                .map(|tabstop| {
 5271                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5272                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5273                    });
 5274                    let mut tabstop_ranges = tabstop
 5275                        .ranges
 5276                        .iter()
 5277                        .flat_map(|tabstop_range| {
 5278                            let mut delta = 0_isize;
 5279                            insertion_ranges.iter().map(move |insertion_range| {
 5280                                let insertion_start = insertion_range.start as isize + delta;
 5281                                delta +=
 5282                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5283
 5284                                let start = ((insertion_start + tabstop_range.start) as usize)
 5285                                    .min(snapshot.len());
 5286                                let end = ((insertion_start + tabstop_range.end) as usize)
 5287                                    .min(snapshot.len());
 5288                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5289                            })
 5290                        })
 5291                        .collect::<Vec<_>>();
 5292                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5293
 5294                    Tabstop {
 5295                        is_end_tabstop,
 5296                        ranges: tabstop_ranges,
 5297                        choices: tabstop.choices.clone(),
 5298                    }
 5299                })
 5300                .collect::<Vec<_>>()
 5301        });
 5302        if let Some(tabstop) = tabstops.first() {
 5303            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5304                s.select_ranges(tabstop.ranges.iter().cloned());
 5305            });
 5306
 5307            if let Some(choices) = &tabstop.choices {
 5308                if let Some(selection) = tabstop.ranges.first() {
 5309                    self.show_snippet_choices(choices, selection.clone(), cx)
 5310                }
 5311            }
 5312
 5313            // If we're already at the last tabstop and it's at the end of the snippet,
 5314            // we're done, we don't need to keep the state around.
 5315            if !tabstop.is_end_tabstop {
 5316                let choices = tabstops
 5317                    .iter()
 5318                    .map(|tabstop| tabstop.choices.clone())
 5319                    .collect();
 5320
 5321                let ranges = tabstops
 5322                    .into_iter()
 5323                    .map(|tabstop| tabstop.ranges)
 5324                    .collect::<Vec<_>>();
 5325
 5326                self.snippet_stack.push(SnippetState {
 5327                    active_index: 0,
 5328                    ranges,
 5329                    choices,
 5330                });
 5331            }
 5332
 5333            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5334            if self.autoclose_regions.is_empty() {
 5335                let snapshot = self.buffer.read(cx).snapshot(cx);
 5336                for selection in &mut self.selections.all::<Point>(cx) {
 5337                    let selection_head = selection.head();
 5338                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5339                        continue;
 5340                    };
 5341
 5342                    let mut bracket_pair = None;
 5343                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5344                    let prev_chars = snapshot
 5345                        .reversed_chars_at(selection_head)
 5346                        .collect::<String>();
 5347                    for (pair, enabled) in scope.brackets() {
 5348                        if enabled
 5349                            && pair.close
 5350                            && prev_chars.starts_with(pair.start.as_str())
 5351                            && next_chars.starts_with(pair.end.as_str())
 5352                        {
 5353                            bracket_pair = Some(pair.clone());
 5354                            break;
 5355                        }
 5356                    }
 5357                    if let Some(pair) = bracket_pair {
 5358                        let start = snapshot.anchor_after(selection_head);
 5359                        let end = snapshot.anchor_after(selection_head);
 5360                        self.autoclose_regions.push(AutocloseRegion {
 5361                            selection_id: selection.id,
 5362                            range: start..end,
 5363                            pair,
 5364                        });
 5365                    }
 5366                }
 5367            }
 5368        }
 5369        Ok(())
 5370    }
 5371
 5372    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5373        self.move_to_snippet_tabstop(Bias::Right, cx)
 5374    }
 5375
 5376    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5377        self.move_to_snippet_tabstop(Bias::Left, cx)
 5378    }
 5379
 5380    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5381        if let Some(mut snippet) = self.snippet_stack.pop() {
 5382            match bias {
 5383                Bias::Left => {
 5384                    if snippet.active_index > 0 {
 5385                        snippet.active_index -= 1;
 5386                    } else {
 5387                        self.snippet_stack.push(snippet);
 5388                        return false;
 5389                    }
 5390                }
 5391                Bias::Right => {
 5392                    if snippet.active_index + 1 < snippet.ranges.len() {
 5393                        snippet.active_index += 1;
 5394                    } else {
 5395                        self.snippet_stack.push(snippet);
 5396                        return false;
 5397                    }
 5398                }
 5399            }
 5400            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5401                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5402                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5403                });
 5404
 5405                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5406                    if let Some(selection) = current_ranges.first() {
 5407                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5408                    }
 5409                }
 5410
 5411                // If snippet state is not at the last tabstop, push it back on the stack
 5412                if snippet.active_index + 1 < snippet.ranges.len() {
 5413                    self.snippet_stack.push(snippet);
 5414                }
 5415                return true;
 5416            }
 5417        }
 5418
 5419        false
 5420    }
 5421
 5422    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5423        self.transact(cx, |this, cx| {
 5424            this.select_all(&SelectAll, cx);
 5425            this.insert("", cx);
 5426        });
 5427    }
 5428
 5429    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5430        self.transact(cx, |this, cx| {
 5431            this.select_autoclose_pair(cx);
 5432            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5433            if !this.linked_edit_ranges.is_empty() {
 5434                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5435                let snapshot = this.buffer.read(cx).snapshot(cx);
 5436
 5437                for selection in selections.iter() {
 5438                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5439                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5440                    if selection_start.buffer_id != selection_end.buffer_id {
 5441                        continue;
 5442                    }
 5443                    if let Some(ranges) =
 5444                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5445                    {
 5446                        for (buffer, entries) in ranges {
 5447                            linked_ranges.entry(buffer).or_default().extend(entries);
 5448                        }
 5449                    }
 5450                }
 5451            }
 5452
 5453            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5454            if !this.selections.line_mode {
 5455                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5456                for selection in &mut selections {
 5457                    if selection.is_empty() {
 5458                        let old_head = selection.head();
 5459                        let mut new_head =
 5460                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5461                                .to_point(&display_map);
 5462                        if let Some((buffer, line_buffer_range)) = display_map
 5463                            .buffer_snapshot
 5464                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5465                        {
 5466                            let indent_size =
 5467                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5468                            let indent_len = match indent_size.kind {
 5469                                IndentKind::Space => {
 5470                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5471                                }
 5472                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5473                            };
 5474                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5475                                let indent_len = indent_len.get();
 5476                                new_head = cmp::min(
 5477                                    new_head,
 5478                                    MultiBufferPoint::new(
 5479                                        old_head.row,
 5480                                        ((old_head.column - 1) / indent_len) * indent_len,
 5481                                    ),
 5482                                );
 5483                            }
 5484                        }
 5485
 5486                        selection.set_head(new_head, SelectionGoal::None);
 5487                    }
 5488                }
 5489            }
 5490
 5491            this.signature_help_state.set_backspace_pressed(true);
 5492            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5493            this.insert("", cx);
 5494            let empty_str: Arc<str> = Arc::from("");
 5495            for (buffer, edits) in linked_ranges {
 5496                let snapshot = buffer.read(cx).snapshot();
 5497                use text::ToPoint as TP;
 5498
 5499                let edits = edits
 5500                    .into_iter()
 5501                    .map(|range| {
 5502                        let end_point = TP::to_point(&range.end, &snapshot);
 5503                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5504
 5505                        if end_point == start_point {
 5506                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5507                                .saturating_sub(1);
 5508                            start_point =
 5509                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5510                        };
 5511
 5512                        (start_point..end_point, empty_str.clone())
 5513                    })
 5514                    .sorted_by_key(|(range, _)| range.start)
 5515                    .collect::<Vec<_>>();
 5516                buffer.update(cx, |this, cx| {
 5517                    this.edit(edits, None, cx);
 5518                })
 5519            }
 5520            this.refresh_inline_completion(true, false, cx);
 5521            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5522        });
 5523    }
 5524
 5525    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5526        self.transact(cx, |this, cx| {
 5527            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5528                let line_mode = s.line_mode;
 5529                s.move_with(|map, selection| {
 5530                    if selection.is_empty() && !line_mode {
 5531                        let cursor = movement::right(map, selection.head());
 5532                        selection.end = cursor;
 5533                        selection.reversed = true;
 5534                        selection.goal = SelectionGoal::None;
 5535                    }
 5536                })
 5537            });
 5538            this.insert("", cx);
 5539            this.refresh_inline_completion(true, false, cx);
 5540        });
 5541    }
 5542
 5543    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5544        if self.move_to_prev_snippet_tabstop(cx) {
 5545            return;
 5546        }
 5547
 5548        self.outdent(&Outdent, cx);
 5549    }
 5550
 5551    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5552        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5553            return;
 5554        }
 5555
 5556        let mut selections = self.selections.all_adjusted(cx);
 5557        let buffer = self.buffer.read(cx);
 5558        let snapshot = buffer.snapshot(cx);
 5559        let rows_iter = selections.iter().map(|s| s.head().row);
 5560        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5561
 5562        let mut edits = Vec::new();
 5563        let mut prev_edited_row = 0;
 5564        let mut row_delta = 0;
 5565        for selection in &mut selections {
 5566            if selection.start.row != prev_edited_row {
 5567                row_delta = 0;
 5568            }
 5569            prev_edited_row = selection.end.row;
 5570
 5571            // If the selection is non-empty, then increase the indentation of the selected lines.
 5572            if !selection.is_empty() {
 5573                row_delta =
 5574                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5575                continue;
 5576            }
 5577
 5578            // If the selection is empty and the cursor is in the leading whitespace before the
 5579            // suggested indentation, then auto-indent the line.
 5580            let cursor = selection.head();
 5581            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5582            if let Some(suggested_indent) =
 5583                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5584            {
 5585                if cursor.column < suggested_indent.len
 5586                    && cursor.column <= current_indent.len
 5587                    && current_indent.len <= suggested_indent.len
 5588                {
 5589                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5590                    selection.end = selection.start;
 5591                    if row_delta == 0 {
 5592                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5593                            cursor.row,
 5594                            current_indent,
 5595                            suggested_indent,
 5596                        ));
 5597                        row_delta = suggested_indent.len - current_indent.len;
 5598                    }
 5599                    continue;
 5600                }
 5601            }
 5602
 5603            // Otherwise, insert a hard or soft tab.
 5604            let settings = buffer.settings_at(cursor, cx);
 5605            let tab_size = if settings.hard_tabs {
 5606                IndentSize::tab()
 5607            } else {
 5608                let tab_size = settings.tab_size.get();
 5609                let char_column = snapshot
 5610                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5611                    .flat_map(str::chars)
 5612                    .count()
 5613                    + row_delta as usize;
 5614                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5615                IndentSize::spaces(chars_to_next_tab_stop)
 5616            };
 5617            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5618            selection.end = selection.start;
 5619            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5620            row_delta += tab_size.len;
 5621        }
 5622
 5623        self.transact(cx, |this, cx| {
 5624            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5625            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5626            this.refresh_inline_completion(true, false, cx);
 5627        });
 5628    }
 5629
 5630    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5631        if self.read_only(cx) {
 5632            return;
 5633        }
 5634        let mut selections = self.selections.all::<Point>(cx);
 5635        let mut prev_edited_row = 0;
 5636        let mut row_delta = 0;
 5637        let mut edits = Vec::new();
 5638        let buffer = self.buffer.read(cx);
 5639        let snapshot = buffer.snapshot(cx);
 5640        for selection in &mut selections {
 5641            if selection.start.row != prev_edited_row {
 5642                row_delta = 0;
 5643            }
 5644            prev_edited_row = selection.end.row;
 5645
 5646            row_delta =
 5647                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5648        }
 5649
 5650        self.transact(cx, |this, cx| {
 5651            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5652            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5653        });
 5654    }
 5655
 5656    fn indent_selection(
 5657        buffer: &MultiBuffer,
 5658        snapshot: &MultiBufferSnapshot,
 5659        selection: &mut Selection<Point>,
 5660        edits: &mut Vec<(Range<Point>, String)>,
 5661        delta_for_start_row: u32,
 5662        cx: &AppContext,
 5663    ) -> u32 {
 5664        let settings = buffer.settings_at(selection.start, cx);
 5665        let tab_size = settings.tab_size.get();
 5666        let indent_kind = if settings.hard_tabs {
 5667            IndentKind::Tab
 5668        } else {
 5669            IndentKind::Space
 5670        };
 5671        let mut start_row = selection.start.row;
 5672        let mut end_row = selection.end.row + 1;
 5673
 5674        // If a selection ends at the beginning of a line, don't indent
 5675        // that last line.
 5676        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5677            end_row -= 1;
 5678        }
 5679
 5680        // Avoid re-indenting a row that has already been indented by a
 5681        // previous selection, but still update this selection's column
 5682        // to reflect that indentation.
 5683        if delta_for_start_row > 0 {
 5684            start_row += 1;
 5685            selection.start.column += delta_for_start_row;
 5686            if selection.end.row == selection.start.row {
 5687                selection.end.column += delta_for_start_row;
 5688            }
 5689        }
 5690
 5691        let mut delta_for_end_row = 0;
 5692        let has_multiple_rows = start_row + 1 != end_row;
 5693        for row in start_row..end_row {
 5694            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5695            let indent_delta = match (current_indent.kind, indent_kind) {
 5696                (IndentKind::Space, IndentKind::Space) => {
 5697                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5698                    IndentSize::spaces(columns_to_next_tab_stop)
 5699                }
 5700                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5701                (_, IndentKind::Tab) => IndentSize::tab(),
 5702            };
 5703
 5704            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5705                0
 5706            } else {
 5707                selection.start.column
 5708            };
 5709            let row_start = Point::new(row, start);
 5710            edits.push((
 5711                row_start..row_start,
 5712                indent_delta.chars().collect::<String>(),
 5713            ));
 5714
 5715            // Update this selection's endpoints to reflect the indentation.
 5716            if row == selection.start.row {
 5717                selection.start.column += indent_delta.len;
 5718            }
 5719            if row == selection.end.row {
 5720                selection.end.column += indent_delta.len;
 5721                delta_for_end_row = indent_delta.len;
 5722            }
 5723        }
 5724
 5725        if selection.start.row == selection.end.row {
 5726            delta_for_start_row + delta_for_end_row
 5727        } else {
 5728            delta_for_end_row
 5729        }
 5730    }
 5731
 5732    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5733        if self.read_only(cx) {
 5734            return;
 5735        }
 5736        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5737        let selections = self.selections.all::<Point>(cx);
 5738        let mut deletion_ranges = Vec::new();
 5739        let mut last_outdent = None;
 5740        {
 5741            let buffer = self.buffer.read(cx);
 5742            let snapshot = buffer.snapshot(cx);
 5743            for selection in &selections {
 5744                let settings = buffer.settings_at(selection.start, cx);
 5745                let tab_size = settings.tab_size.get();
 5746                let mut rows = selection.spanned_rows(false, &display_map);
 5747
 5748                // Avoid re-outdenting a row that has already been outdented by a
 5749                // previous selection.
 5750                if let Some(last_row) = last_outdent {
 5751                    if last_row == rows.start {
 5752                        rows.start = rows.start.next_row();
 5753                    }
 5754                }
 5755                let has_multiple_rows = rows.len() > 1;
 5756                for row in rows.iter_rows() {
 5757                    let indent_size = snapshot.indent_size_for_line(row);
 5758                    if indent_size.len > 0 {
 5759                        let deletion_len = match indent_size.kind {
 5760                            IndentKind::Space => {
 5761                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5762                                if columns_to_prev_tab_stop == 0 {
 5763                                    tab_size
 5764                                } else {
 5765                                    columns_to_prev_tab_stop
 5766                                }
 5767                            }
 5768                            IndentKind::Tab => 1,
 5769                        };
 5770                        let start = if has_multiple_rows
 5771                            || deletion_len > selection.start.column
 5772                            || indent_size.len < selection.start.column
 5773                        {
 5774                            0
 5775                        } else {
 5776                            selection.start.column - deletion_len
 5777                        };
 5778                        deletion_ranges.push(
 5779                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5780                        );
 5781                        last_outdent = Some(row);
 5782                    }
 5783                }
 5784            }
 5785        }
 5786
 5787        self.transact(cx, |this, cx| {
 5788            this.buffer.update(cx, |buffer, cx| {
 5789                let empty_str: Arc<str> = Arc::default();
 5790                buffer.edit(
 5791                    deletion_ranges
 5792                        .into_iter()
 5793                        .map(|range| (range, empty_str.clone())),
 5794                    None,
 5795                    cx,
 5796                );
 5797            });
 5798            let selections = this.selections.all::<usize>(cx);
 5799            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5800        });
 5801    }
 5802
 5803    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5804        if self.read_only(cx) {
 5805            return;
 5806        }
 5807        let selections = self
 5808            .selections
 5809            .all::<usize>(cx)
 5810            .into_iter()
 5811            .map(|s| s.range());
 5812
 5813        self.transact(cx, |this, cx| {
 5814            this.buffer.update(cx, |buffer, cx| {
 5815                buffer.autoindent_ranges(selections, cx);
 5816            });
 5817            let selections = this.selections.all::<usize>(cx);
 5818            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5819        });
 5820    }
 5821
 5822    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5823        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5824        let selections = self.selections.all::<Point>(cx);
 5825
 5826        let mut new_cursors = Vec::new();
 5827        let mut edit_ranges = Vec::new();
 5828        let mut selections = selections.iter().peekable();
 5829        while let Some(selection) = selections.next() {
 5830            let mut rows = selection.spanned_rows(false, &display_map);
 5831            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5832
 5833            // Accumulate contiguous regions of rows that we want to delete.
 5834            while let Some(next_selection) = selections.peek() {
 5835                let next_rows = next_selection.spanned_rows(false, &display_map);
 5836                if next_rows.start <= rows.end {
 5837                    rows.end = next_rows.end;
 5838                    selections.next().unwrap();
 5839                } else {
 5840                    break;
 5841                }
 5842            }
 5843
 5844            let buffer = &display_map.buffer_snapshot;
 5845            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5846            let edit_end;
 5847            let cursor_buffer_row;
 5848            if buffer.max_point().row >= rows.end.0 {
 5849                // If there's a line after the range, delete the \n from the end of the row range
 5850                // and position the cursor on the next line.
 5851                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5852                cursor_buffer_row = rows.end;
 5853            } else {
 5854                // If there isn't a line after the range, delete the \n from the line before the
 5855                // start of the row range and position the cursor there.
 5856                edit_start = edit_start.saturating_sub(1);
 5857                edit_end = buffer.len();
 5858                cursor_buffer_row = rows.start.previous_row();
 5859            }
 5860
 5861            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5862            *cursor.column_mut() =
 5863                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5864
 5865            new_cursors.push((
 5866                selection.id,
 5867                buffer.anchor_after(cursor.to_point(&display_map)),
 5868            ));
 5869            edit_ranges.push(edit_start..edit_end);
 5870        }
 5871
 5872        self.transact(cx, |this, cx| {
 5873            let buffer = this.buffer.update(cx, |buffer, cx| {
 5874                let empty_str: Arc<str> = Arc::default();
 5875                buffer.edit(
 5876                    edit_ranges
 5877                        .into_iter()
 5878                        .map(|range| (range, empty_str.clone())),
 5879                    None,
 5880                    cx,
 5881                );
 5882                buffer.snapshot(cx)
 5883            });
 5884            let new_selections = new_cursors
 5885                .into_iter()
 5886                .map(|(id, cursor)| {
 5887                    let cursor = cursor.to_point(&buffer);
 5888                    Selection {
 5889                        id,
 5890                        start: cursor,
 5891                        end: cursor,
 5892                        reversed: false,
 5893                        goal: SelectionGoal::None,
 5894                    }
 5895                })
 5896                .collect();
 5897
 5898            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5899                s.select(new_selections);
 5900            });
 5901        });
 5902    }
 5903
 5904    pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
 5905        if self.read_only(cx) {
 5906            return;
 5907        }
 5908        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5909        for selection in self.selections.all::<Point>(cx) {
 5910            let start = MultiBufferRow(selection.start.row);
 5911            // Treat single line selections as if they include the next line. Otherwise this action
 5912            // would do nothing for single line selections individual cursors.
 5913            let end = if selection.start.row == selection.end.row {
 5914                MultiBufferRow(selection.start.row + 1)
 5915            } else {
 5916                MultiBufferRow(selection.end.row)
 5917            };
 5918
 5919            if let Some(last_row_range) = row_ranges.last_mut() {
 5920                if start <= last_row_range.end {
 5921                    last_row_range.end = end;
 5922                    continue;
 5923                }
 5924            }
 5925            row_ranges.push(start..end);
 5926        }
 5927
 5928        let snapshot = self.buffer.read(cx).snapshot(cx);
 5929        let mut cursor_positions = Vec::new();
 5930        for row_range in &row_ranges {
 5931            let anchor = snapshot.anchor_before(Point::new(
 5932                row_range.end.previous_row().0,
 5933                snapshot.line_len(row_range.end.previous_row()),
 5934            ));
 5935            cursor_positions.push(anchor..anchor);
 5936        }
 5937
 5938        self.transact(cx, |this, cx| {
 5939            for row_range in row_ranges.into_iter().rev() {
 5940                for row in row_range.iter_rows().rev() {
 5941                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5942                    let next_line_row = row.next_row();
 5943                    let indent = snapshot.indent_size_for_line(next_line_row);
 5944                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5945
 5946                    let replace =
 5947                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 5948                            " "
 5949                        } else {
 5950                            ""
 5951                        };
 5952
 5953                    this.buffer.update(cx, |buffer, cx| {
 5954                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5955                    });
 5956                }
 5957            }
 5958
 5959            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5960                s.select_anchor_ranges(cursor_positions)
 5961            });
 5962        });
 5963    }
 5964
 5965    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5966        self.join_lines_impl(true, cx);
 5967    }
 5968
 5969    pub fn sort_lines_case_sensitive(
 5970        &mut self,
 5971        _: &SortLinesCaseSensitive,
 5972        cx: &mut ViewContext<Self>,
 5973    ) {
 5974        self.manipulate_lines(cx, |lines| lines.sort())
 5975    }
 5976
 5977    pub fn sort_lines_case_insensitive(
 5978        &mut self,
 5979        _: &SortLinesCaseInsensitive,
 5980        cx: &mut ViewContext<Self>,
 5981    ) {
 5982        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5983    }
 5984
 5985    pub fn unique_lines_case_insensitive(
 5986        &mut self,
 5987        _: &UniqueLinesCaseInsensitive,
 5988        cx: &mut ViewContext<Self>,
 5989    ) {
 5990        self.manipulate_lines(cx, |lines| {
 5991            let mut seen = HashSet::default();
 5992            lines.retain(|line| seen.insert(line.to_lowercase()));
 5993        })
 5994    }
 5995
 5996    pub fn unique_lines_case_sensitive(
 5997        &mut self,
 5998        _: &UniqueLinesCaseSensitive,
 5999        cx: &mut ViewContext<Self>,
 6000    ) {
 6001        self.manipulate_lines(cx, |lines| {
 6002            let mut seen = HashSet::default();
 6003            lines.retain(|line| seen.insert(*line));
 6004        })
 6005    }
 6006
 6007    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6008        let mut revert_changes = HashMap::default();
 6009        let snapshot = self.snapshot(cx);
 6010        for hunk in hunks_for_ranges(
 6011            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 6012            &snapshot,
 6013        ) {
 6014            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6015        }
 6016        if !revert_changes.is_empty() {
 6017            self.transact(cx, |editor, cx| {
 6018                editor.revert(revert_changes, cx);
 6019            });
 6020        }
 6021    }
 6022
 6023    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6024        let Some(project) = self.project.clone() else {
 6025            return;
 6026        };
 6027        self.reload(project, cx).detach_and_notify_err(cx);
 6028    }
 6029
 6030    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6031        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 6032        if !revert_changes.is_empty() {
 6033            self.transact(cx, |editor, cx| {
 6034                editor.revert(revert_changes, cx);
 6035            });
 6036        }
 6037    }
 6038
 6039    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 6040        let snapshot = self.buffer.read(cx).read(cx);
 6041        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 6042            drop(snapshot);
 6043            let mut revert_changes = HashMap::default();
 6044            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6045            if !revert_changes.is_empty() {
 6046                self.revert(revert_changes, cx)
 6047            }
 6048        }
 6049    }
 6050
 6051    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6052        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6053            let project_path = buffer.read(cx).project_path(cx)?;
 6054            let project = self.project.as_ref()?.read(cx);
 6055            let entry = project.entry_for_path(&project_path, cx)?;
 6056            let parent = match &entry.canonical_path {
 6057                Some(canonical_path) => canonical_path.to_path_buf(),
 6058                None => project.absolute_path(&project_path, cx)?,
 6059            }
 6060            .parent()?
 6061            .to_path_buf();
 6062            Some(parent)
 6063        }) {
 6064            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6065        }
 6066    }
 6067
 6068    fn gather_revert_changes(
 6069        &mut self,
 6070        selections: &[Selection<Point>],
 6071        cx: &mut ViewContext<Editor>,
 6072    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6073        let mut revert_changes = HashMap::default();
 6074        let snapshot = self.snapshot(cx);
 6075        for hunk in hunks_for_selections(&snapshot, selections) {
 6076            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6077        }
 6078        revert_changes
 6079    }
 6080
 6081    pub fn prepare_revert_change(
 6082        &mut self,
 6083        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6084        hunk: &MultiBufferDiffHunk,
 6085        cx: &AppContext,
 6086    ) -> Option<()> {
 6087        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6088        let buffer = buffer.read(cx);
 6089        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6090        let original_text = change_set
 6091            .read(cx)
 6092            .base_text
 6093            .as_ref()?
 6094            .read(cx)
 6095            .as_rope()
 6096            .slice(hunk.diff_base_byte_range.clone());
 6097        let buffer_snapshot = buffer.snapshot();
 6098        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6099        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6100            probe
 6101                .0
 6102                .start
 6103                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6104                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6105        }) {
 6106            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6107            Some(())
 6108        } else {
 6109            None
 6110        }
 6111    }
 6112
 6113    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6114        self.manipulate_lines(cx, |lines| lines.reverse())
 6115    }
 6116
 6117    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6118        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6119    }
 6120
 6121    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6122    where
 6123        Fn: FnMut(&mut Vec<&str>),
 6124    {
 6125        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6126        let buffer = self.buffer.read(cx).snapshot(cx);
 6127
 6128        let mut edits = Vec::new();
 6129
 6130        let selections = self.selections.all::<Point>(cx);
 6131        let mut selections = selections.iter().peekable();
 6132        let mut contiguous_row_selections = Vec::new();
 6133        let mut new_selections = Vec::new();
 6134        let mut added_lines = 0;
 6135        let mut removed_lines = 0;
 6136
 6137        while let Some(selection) = selections.next() {
 6138            let (start_row, end_row) = consume_contiguous_rows(
 6139                &mut contiguous_row_selections,
 6140                selection,
 6141                &display_map,
 6142                &mut selections,
 6143            );
 6144
 6145            let start_point = Point::new(start_row.0, 0);
 6146            let end_point = Point::new(
 6147                end_row.previous_row().0,
 6148                buffer.line_len(end_row.previous_row()),
 6149            );
 6150            let text = buffer
 6151                .text_for_range(start_point..end_point)
 6152                .collect::<String>();
 6153
 6154            let mut lines = text.split('\n').collect_vec();
 6155
 6156            let lines_before = lines.len();
 6157            callback(&mut lines);
 6158            let lines_after = lines.len();
 6159
 6160            edits.push((start_point..end_point, lines.join("\n")));
 6161
 6162            // Selections must change based on added and removed line count
 6163            let start_row =
 6164                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6165            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6166            new_selections.push(Selection {
 6167                id: selection.id,
 6168                start: start_row,
 6169                end: end_row,
 6170                goal: SelectionGoal::None,
 6171                reversed: selection.reversed,
 6172            });
 6173
 6174            if lines_after > lines_before {
 6175                added_lines += lines_after - lines_before;
 6176            } else if lines_before > lines_after {
 6177                removed_lines += lines_before - lines_after;
 6178            }
 6179        }
 6180
 6181        self.transact(cx, |this, cx| {
 6182            let buffer = this.buffer.update(cx, |buffer, cx| {
 6183                buffer.edit(edits, None, cx);
 6184                buffer.snapshot(cx)
 6185            });
 6186
 6187            // Recalculate offsets on newly edited buffer
 6188            let new_selections = new_selections
 6189                .iter()
 6190                .map(|s| {
 6191                    let start_point = Point::new(s.start.0, 0);
 6192                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6193                    Selection {
 6194                        id: s.id,
 6195                        start: buffer.point_to_offset(start_point),
 6196                        end: buffer.point_to_offset(end_point),
 6197                        goal: s.goal,
 6198                        reversed: s.reversed,
 6199                    }
 6200                })
 6201                .collect();
 6202
 6203            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6204                s.select(new_selections);
 6205            });
 6206
 6207            this.request_autoscroll(Autoscroll::fit(), cx);
 6208        });
 6209    }
 6210
 6211    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6212        self.manipulate_text(cx, |text| text.to_uppercase())
 6213    }
 6214
 6215    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6216        self.manipulate_text(cx, |text| text.to_lowercase())
 6217    }
 6218
 6219    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6220        self.manipulate_text(cx, |text| {
 6221            text.split('\n')
 6222                .map(|line| line.to_case(Case::Title))
 6223                .join("\n")
 6224        })
 6225    }
 6226
 6227    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6228        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6229    }
 6230
 6231    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6232        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6233    }
 6234
 6235    pub fn convert_to_upper_camel_case(
 6236        &mut self,
 6237        _: &ConvertToUpperCamelCase,
 6238        cx: &mut ViewContext<Self>,
 6239    ) {
 6240        self.manipulate_text(cx, |text| {
 6241            text.split('\n')
 6242                .map(|line| line.to_case(Case::UpperCamel))
 6243                .join("\n")
 6244        })
 6245    }
 6246
 6247    pub fn convert_to_lower_camel_case(
 6248        &mut self,
 6249        _: &ConvertToLowerCamelCase,
 6250        cx: &mut ViewContext<Self>,
 6251    ) {
 6252        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6253    }
 6254
 6255    pub fn convert_to_opposite_case(
 6256        &mut self,
 6257        _: &ConvertToOppositeCase,
 6258        cx: &mut ViewContext<Self>,
 6259    ) {
 6260        self.manipulate_text(cx, |text| {
 6261            text.chars()
 6262                .fold(String::with_capacity(text.len()), |mut t, c| {
 6263                    if c.is_uppercase() {
 6264                        t.extend(c.to_lowercase());
 6265                    } else {
 6266                        t.extend(c.to_uppercase());
 6267                    }
 6268                    t
 6269                })
 6270        })
 6271    }
 6272
 6273    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6274    where
 6275        Fn: FnMut(&str) -> String,
 6276    {
 6277        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6278        let buffer = self.buffer.read(cx).snapshot(cx);
 6279
 6280        let mut new_selections = Vec::new();
 6281        let mut edits = Vec::new();
 6282        let mut selection_adjustment = 0i32;
 6283
 6284        for selection in self.selections.all::<usize>(cx) {
 6285            let selection_is_empty = selection.is_empty();
 6286
 6287            let (start, end) = if selection_is_empty {
 6288                let word_range = movement::surrounding_word(
 6289                    &display_map,
 6290                    selection.start.to_display_point(&display_map),
 6291                );
 6292                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6293                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6294                (start, end)
 6295            } else {
 6296                (selection.start, selection.end)
 6297            };
 6298
 6299            let text = buffer.text_for_range(start..end).collect::<String>();
 6300            let old_length = text.len() as i32;
 6301            let text = callback(&text);
 6302
 6303            new_selections.push(Selection {
 6304                start: (start as i32 - selection_adjustment) as usize,
 6305                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6306                goal: SelectionGoal::None,
 6307                ..selection
 6308            });
 6309
 6310            selection_adjustment += old_length - text.len() as i32;
 6311
 6312            edits.push((start..end, text));
 6313        }
 6314
 6315        self.transact(cx, |this, cx| {
 6316            this.buffer.update(cx, |buffer, cx| {
 6317                buffer.edit(edits, None, cx);
 6318            });
 6319
 6320            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6321                s.select(new_selections);
 6322            });
 6323
 6324            this.request_autoscroll(Autoscroll::fit(), cx);
 6325        });
 6326    }
 6327
 6328    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6329        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6330        let buffer = &display_map.buffer_snapshot;
 6331        let selections = self.selections.all::<Point>(cx);
 6332
 6333        let mut edits = Vec::new();
 6334        let mut selections_iter = selections.iter().peekable();
 6335        while let Some(selection) = selections_iter.next() {
 6336            let mut rows = selection.spanned_rows(false, &display_map);
 6337            // duplicate line-wise
 6338            if whole_lines || selection.start == selection.end {
 6339                // Avoid duplicating the same lines twice.
 6340                while let Some(next_selection) = selections_iter.peek() {
 6341                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6342                    if next_rows.start < rows.end {
 6343                        rows.end = next_rows.end;
 6344                        selections_iter.next().unwrap();
 6345                    } else {
 6346                        break;
 6347                    }
 6348                }
 6349
 6350                // Copy the text from the selected row region and splice it either at the start
 6351                // or end of the region.
 6352                let start = Point::new(rows.start.0, 0);
 6353                let end = Point::new(
 6354                    rows.end.previous_row().0,
 6355                    buffer.line_len(rows.end.previous_row()),
 6356                );
 6357                let text = buffer
 6358                    .text_for_range(start..end)
 6359                    .chain(Some("\n"))
 6360                    .collect::<String>();
 6361                let insert_location = if upwards {
 6362                    Point::new(rows.end.0, 0)
 6363                } else {
 6364                    start
 6365                };
 6366                edits.push((insert_location..insert_location, text));
 6367            } else {
 6368                // duplicate character-wise
 6369                let start = selection.start;
 6370                let end = selection.end;
 6371                let text = buffer.text_for_range(start..end).collect::<String>();
 6372                edits.push((selection.end..selection.end, text));
 6373            }
 6374        }
 6375
 6376        self.transact(cx, |this, cx| {
 6377            this.buffer.update(cx, |buffer, cx| {
 6378                buffer.edit(edits, None, cx);
 6379            });
 6380
 6381            this.request_autoscroll(Autoscroll::fit(), cx);
 6382        });
 6383    }
 6384
 6385    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6386        self.duplicate(true, true, cx);
 6387    }
 6388
 6389    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6390        self.duplicate(false, true, cx);
 6391    }
 6392
 6393    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6394        self.duplicate(false, false, cx);
 6395    }
 6396
 6397    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6398        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6399        let buffer = self.buffer.read(cx).snapshot(cx);
 6400
 6401        let mut edits = Vec::new();
 6402        let mut unfold_ranges = Vec::new();
 6403        let mut refold_creases = Vec::new();
 6404
 6405        let selections = self.selections.all::<Point>(cx);
 6406        let mut selections = selections.iter().peekable();
 6407        let mut contiguous_row_selections = Vec::new();
 6408        let mut new_selections = Vec::new();
 6409
 6410        while let Some(selection) = selections.next() {
 6411            // Find all the selections that span a contiguous row range
 6412            let (start_row, end_row) = consume_contiguous_rows(
 6413                &mut contiguous_row_selections,
 6414                selection,
 6415                &display_map,
 6416                &mut selections,
 6417            );
 6418
 6419            // Move the text spanned by the row range to be before the line preceding the row range
 6420            if start_row.0 > 0 {
 6421                let range_to_move = Point::new(
 6422                    start_row.previous_row().0,
 6423                    buffer.line_len(start_row.previous_row()),
 6424                )
 6425                    ..Point::new(
 6426                        end_row.previous_row().0,
 6427                        buffer.line_len(end_row.previous_row()),
 6428                    );
 6429                let insertion_point = display_map
 6430                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6431                    .0;
 6432
 6433                // Don't move lines across excerpts
 6434                if buffer
 6435                    .excerpt_boundaries_in_range((
 6436                        Bound::Excluded(insertion_point),
 6437                        Bound::Included(range_to_move.end),
 6438                    ))
 6439                    .next()
 6440                    .is_none()
 6441                {
 6442                    let text = buffer
 6443                        .text_for_range(range_to_move.clone())
 6444                        .flat_map(|s| s.chars())
 6445                        .skip(1)
 6446                        .chain(['\n'])
 6447                        .collect::<String>();
 6448
 6449                    edits.push((
 6450                        buffer.anchor_after(range_to_move.start)
 6451                            ..buffer.anchor_before(range_to_move.end),
 6452                        String::new(),
 6453                    ));
 6454                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6455                    edits.push((insertion_anchor..insertion_anchor, text));
 6456
 6457                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6458
 6459                    // Move selections up
 6460                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6461                        |mut selection| {
 6462                            selection.start.row -= row_delta;
 6463                            selection.end.row -= row_delta;
 6464                            selection
 6465                        },
 6466                    ));
 6467
 6468                    // Move folds up
 6469                    unfold_ranges.push(range_to_move.clone());
 6470                    for fold in display_map.folds_in_range(
 6471                        buffer.anchor_before(range_to_move.start)
 6472                            ..buffer.anchor_after(range_to_move.end),
 6473                    ) {
 6474                        let mut start = fold.range.start.to_point(&buffer);
 6475                        let mut end = fold.range.end.to_point(&buffer);
 6476                        start.row -= row_delta;
 6477                        end.row -= row_delta;
 6478                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6479                    }
 6480                }
 6481            }
 6482
 6483            // If we didn't move line(s), preserve the existing selections
 6484            new_selections.append(&mut contiguous_row_selections);
 6485        }
 6486
 6487        self.transact(cx, |this, cx| {
 6488            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6489            this.buffer.update(cx, |buffer, cx| {
 6490                for (range, text) in edits {
 6491                    buffer.edit([(range, text)], None, cx);
 6492                }
 6493            });
 6494            this.fold_creases(refold_creases, true, cx);
 6495            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6496                s.select(new_selections);
 6497            })
 6498        });
 6499    }
 6500
 6501    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6502        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6503        let buffer = self.buffer.read(cx).snapshot(cx);
 6504
 6505        let mut edits = Vec::new();
 6506        let mut unfold_ranges = Vec::new();
 6507        let mut refold_creases = Vec::new();
 6508
 6509        let selections = self.selections.all::<Point>(cx);
 6510        let mut selections = selections.iter().peekable();
 6511        let mut contiguous_row_selections = Vec::new();
 6512        let mut new_selections = Vec::new();
 6513
 6514        while let Some(selection) = selections.next() {
 6515            // Find all the selections that span a contiguous row range
 6516            let (start_row, end_row) = consume_contiguous_rows(
 6517                &mut contiguous_row_selections,
 6518                selection,
 6519                &display_map,
 6520                &mut selections,
 6521            );
 6522
 6523            // Move the text spanned by the row range to be after the last line of the row range
 6524            if end_row.0 <= buffer.max_point().row {
 6525                let range_to_move =
 6526                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6527                let insertion_point = display_map
 6528                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6529                    .0;
 6530
 6531                // Don't move lines across excerpt boundaries
 6532                if buffer
 6533                    .excerpt_boundaries_in_range((
 6534                        Bound::Excluded(range_to_move.start),
 6535                        Bound::Included(insertion_point),
 6536                    ))
 6537                    .next()
 6538                    .is_none()
 6539                {
 6540                    let mut text = String::from("\n");
 6541                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6542                    text.pop(); // Drop trailing newline
 6543                    edits.push((
 6544                        buffer.anchor_after(range_to_move.start)
 6545                            ..buffer.anchor_before(range_to_move.end),
 6546                        String::new(),
 6547                    ));
 6548                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6549                    edits.push((insertion_anchor..insertion_anchor, text));
 6550
 6551                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6552
 6553                    // Move selections down
 6554                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6555                        |mut selection| {
 6556                            selection.start.row += row_delta;
 6557                            selection.end.row += row_delta;
 6558                            selection
 6559                        },
 6560                    ));
 6561
 6562                    // Move folds down
 6563                    unfold_ranges.push(range_to_move.clone());
 6564                    for fold in display_map.folds_in_range(
 6565                        buffer.anchor_before(range_to_move.start)
 6566                            ..buffer.anchor_after(range_to_move.end),
 6567                    ) {
 6568                        let mut start = fold.range.start.to_point(&buffer);
 6569                        let mut end = fold.range.end.to_point(&buffer);
 6570                        start.row += row_delta;
 6571                        end.row += row_delta;
 6572                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6573                    }
 6574                }
 6575            }
 6576
 6577            // If we didn't move line(s), preserve the existing selections
 6578            new_selections.append(&mut contiguous_row_selections);
 6579        }
 6580
 6581        self.transact(cx, |this, cx| {
 6582            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6583            this.buffer.update(cx, |buffer, cx| {
 6584                for (range, text) in edits {
 6585                    buffer.edit([(range, text)], None, cx);
 6586                }
 6587            });
 6588            this.fold_creases(refold_creases, true, cx);
 6589            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6590        });
 6591    }
 6592
 6593    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6594        let text_layout_details = &self.text_layout_details(cx);
 6595        self.transact(cx, |this, cx| {
 6596            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6597                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6598                let line_mode = s.line_mode;
 6599                s.move_with(|display_map, selection| {
 6600                    if !selection.is_empty() || line_mode {
 6601                        return;
 6602                    }
 6603
 6604                    let mut head = selection.head();
 6605                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6606                    if head.column() == display_map.line_len(head.row()) {
 6607                        transpose_offset = display_map
 6608                            .buffer_snapshot
 6609                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6610                    }
 6611
 6612                    if transpose_offset == 0 {
 6613                        return;
 6614                    }
 6615
 6616                    *head.column_mut() += 1;
 6617                    head = display_map.clip_point(head, Bias::Right);
 6618                    let goal = SelectionGoal::HorizontalPosition(
 6619                        display_map
 6620                            .x_for_display_point(head, text_layout_details)
 6621                            .into(),
 6622                    );
 6623                    selection.collapse_to(head, goal);
 6624
 6625                    let transpose_start = display_map
 6626                        .buffer_snapshot
 6627                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6628                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6629                        let transpose_end = display_map
 6630                            .buffer_snapshot
 6631                            .clip_offset(transpose_offset + 1, Bias::Right);
 6632                        if let Some(ch) =
 6633                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6634                        {
 6635                            edits.push((transpose_start..transpose_offset, String::new()));
 6636                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6637                        }
 6638                    }
 6639                });
 6640                edits
 6641            });
 6642            this.buffer
 6643                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6644            let selections = this.selections.all::<usize>(cx);
 6645            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6646                s.select(selections);
 6647            });
 6648        });
 6649    }
 6650
 6651    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6652        self.rewrap_impl(IsVimMode::No, cx)
 6653    }
 6654
 6655    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6656        let buffer = self.buffer.read(cx).snapshot(cx);
 6657        let selections = self.selections.all::<Point>(cx);
 6658        let mut selections = selections.iter().peekable();
 6659
 6660        let mut edits = Vec::new();
 6661        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6662
 6663        while let Some(selection) = selections.next() {
 6664            let mut start_row = selection.start.row;
 6665            let mut end_row = selection.end.row;
 6666
 6667            // Skip selections that overlap with a range that has already been rewrapped.
 6668            let selection_range = start_row..end_row;
 6669            if rewrapped_row_ranges
 6670                .iter()
 6671                .any(|range| range.overlaps(&selection_range))
 6672            {
 6673                continue;
 6674            }
 6675
 6676            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6677
 6678            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6679                match language_scope.language_name().0.as_ref() {
 6680                    "Markdown" | "Plain Text" => {
 6681                        should_rewrap = true;
 6682                    }
 6683                    _ => {}
 6684                }
 6685            }
 6686
 6687            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6688
 6689            // Since not all lines in the selection may be at the same indent
 6690            // level, choose the indent size that is the most common between all
 6691            // of the lines.
 6692            //
 6693            // If there is a tie, we use the deepest indent.
 6694            let (indent_size, indent_end) = {
 6695                let mut indent_size_occurrences = HashMap::default();
 6696                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6697
 6698                for row in start_row..=end_row {
 6699                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6700                    rows_by_indent_size.entry(indent).or_default().push(row);
 6701                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6702                }
 6703
 6704                let indent_size = indent_size_occurrences
 6705                    .into_iter()
 6706                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6707                    .map(|(indent, _)| indent)
 6708                    .unwrap_or_default();
 6709                let row = rows_by_indent_size[&indent_size][0];
 6710                let indent_end = Point::new(row, indent_size.len);
 6711
 6712                (indent_size, indent_end)
 6713            };
 6714
 6715            let mut line_prefix = indent_size.chars().collect::<String>();
 6716
 6717            if let Some(comment_prefix) =
 6718                buffer
 6719                    .language_scope_at(selection.head())
 6720                    .and_then(|language| {
 6721                        language
 6722                            .line_comment_prefixes()
 6723                            .iter()
 6724                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6725                            .cloned()
 6726                    })
 6727            {
 6728                line_prefix.push_str(&comment_prefix);
 6729                should_rewrap = true;
 6730            }
 6731
 6732            if !should_rewrap {
 6733                continue;
 6734            }
 6735
 6736            if selection.is_empty() {
 6737                'expand_upwards: while start_row > 0 {
 6738                    let prev_row = start_row - 1;
 6739                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6740                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6741                    {
 6742                        start_row = prev_row;
 6743                    } else {
 6744                        break 'expand_upwards;
 6745                    }
 6746                }
 6747
 6748                'expand_downwards: while end_row < buffer.max_point().row {
 6749                    let next_row = end_row + 1;
 6750                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6751                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6752                    {
 6753                        end_row = next_row;
 6754                    } else {
 6755                        break 'expand_downwards;
 6756                    }
 6757                }
 6758            }
 6759
 6760            let start = Point::new(start_row, 0);
 6761            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6762            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6763            let Some(lines_without_prefixes) = selection_text
 6764                .lines()
 6765                .map(|line| {
 6766                    line.strip_prefix(&line_prefix)
 6767                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6768                        .ok_or_else(|| {
 6769                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6770                        })
 6771                })
 6772                .collect::<Result<Vec<_>, _>>()
 6773                .log_err()
 6774            else {
 6775                continue;
 6776            };
 6777
 6778            let wrap_column = buffer
 6779                .settings_at(Point::new(start_row, 0), cx)
 6780                .preferred_line_length as usize;
 6781            let wrapped_text = wrap_with_prefix(
 6782                line_prefix,
 6783                lines_without_prefixes.join(" "),
 6784                wrap_column,
 6785                tab_size,
 6786            );
 6787
 6788            // TODO: should always use char-based diff while still supporting cursor behavior that
 6789            // matches vim.
 6790            let diff = match is_vim_mode {
 6791                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6792                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6793            };
 6794            let mut offset = start.to_offset(&buffer);
 6795            let mut moved_since_edit = true;
 6796
 6797            for change in diff.iter_all_changes() {
 6798                let value = change.value();
 6799                match change.tag() {
 6800                    ChangeTag::Equal => {
 6801                        offset += value.len();
 6802                        moved_since_edit = true;
 6803                    }
 6804                    ChangeTag::Delete => {
 6805                        let start = buffer.anchor_after(offset);
 6806                        let end = buffer.anchor_before(offset + value.len());
 6807
 6808                        if moved_since_edit {
 6809                            edits.push((start..end, String::new()));
 6810                        } else {
 6811                            edits.last_mut().unwrap().0.end = end;
 6812                        }
 6813
 6814                        offset += value.len();
 6815                        moved_since_edit = false;
 6816                    }
 6817                    ChangeTag::Insert => {
 6818                        if moved_since_edit {
 6819                            let anchor = buffer.anchor_after(offset);
 6820                            edits.push((anchor..anchor, value.to_string()));
 6821                        } else {
 6822                            edits.last_mut().unwrap().1.push_str(value);
 6823                        }
 6824
 6825                        moved_since_edit = false;
 6826                    }
 6827                }
 6828            }
 6829
 6830            rewrapped_row_ranges.push(start_row..=end_row);
 6831        }
 6832
 6833        self.buffer
 6834            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6835    }
 6836
 6837    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6838        let mut text = String::new();
 6839        let buffer = self.buffer.read(cx).snapshot(cx);
 6840        let mut selections = self.selections.all::<Point>(cx);
 6841        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6842        {
 6843            let max_point = buffer.max_point();
 6844            let mut is_first = true;
 6845            for selection in &mut selections {
 6846                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6847                if is_entire_line {
 6848                    selection.start = Point::new(selection.start.row, 0);
 6849                    if !selection.is_empty() && selection.end.column == 0 {
 6850                        selection.end = cmp::min(max_point, selection.end);
 6851                    } else {
 6852                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6853                    }
 6854                    selection.goal = SelectionGoal::None;
 6855                }
 6856                if is_first {
 6857                    is_first = false;
 6858                } else {
 6859                    text += "\n";
 6860                }
 6861                let mut len = 0;
 6862                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6863                    text.push_str(chunk);
 6864                    len += chunk.len();
 6865                }
 6866                clipboard_selections.push(ClipboardSelection {
 6867                    len,
 6868                    is_entire_line,
 6869                    first_line_indent: buffer
 6870                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6871                        .len,
 6872                });
 6873            }
 6874        }
 6875
 6876        self.transact(cx, |this, cx| {
 6877            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6878                s.select(selections);
 6879            });
 6880            this.insert("", cx);
 6881        });
 6882        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6883    }
 6884
 6885    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6886        let item = self.cut_common(cx);
 6887        cx.write_to_clipboard(item);
 6888    }
 6889
 6890    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6891        self.change_selections(None, cx, |s| {
 6892            s.move_with(|snapshot, sel| {
 6893                if sel.is_empty() {
 6894                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6895                }
 6896            });
 6897        });
 6898        let item = self.cut_common(cx);
 6899        cx.set_global(KillRing(item))
 6900    }
 6901
 6902    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6903        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6904            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6905                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6906            } else {
 6907                return;
 6908            }
 6909        } else {
 6910            return;
 6911        };
 6912        self.do_paste(&text, metadata, false, cx);
 6913    }
 6914
 6915    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6916        let selections = self.selections.all::<Point>(cx);
 6917        let buffer = self.buffer.read(cx).read(cx);
 6918        let mut text = String::new();
 6919
 6920        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6921        {
 6922            let max_point = buffer.max_point();
 6923            let mut is_first = true;
 6924            for selection in selections.iter() {
 6925                let mut start = selection.start;
 6926                let mut end = selection.end;
 6927                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6928                if is_entire_line {
 6929                    start = Point::new(start.row, 0);
 6930                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6931                }
 6932                if is_first {
 6933                    is_first = false;
 6934                } else {
 6935                    text += "\n";
 6936                }
 6937                let mut len = 0;
 6938                for chunk in buffer.text_for_range(start..end) {
 6939                    text.push_str(chunk);
 6940                    len += chunk.len();
 6941                }
 6942                clipboard_selections.push(ClipboardSelection {
 6943                    len,
 6944                    is_entire_line,
 6945                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6946                });
 6947            }
 6948        }
 6949
 6950        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6951            text,
 6952            clipboard_selections,
 6953        ));
 6954    }
 6955
 6956    pub fn do_paste(
 6957        &mut self,
 6958        text: &String,
 6959        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6960        handle_entire_lines: bool,
 6961        cx: &mut ViewContext<Self>,
 6962    ) {
 6963        if self.read_only(cx) {
 6964            return;
 6965        }
 6966
 6967        let clipboard_text = Cow::Borrowed(text);
 6968
 6969        self.transact(cx, |this, cx| {
 6970            if let Some(mut clipboard_selections) = clipboard_selections {
 6971                let old_selections = this.selections.all::<usize>(cx);
 6972                let all_selections_were_entire_line =
 6973                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6974                let first_selection_indent_column =
 6975                    clipboard_selections.first().map(|s| s.first_line_indent);
 6976                if clipboard_selections.len() != old_selections.len() {
 6977                    clipboard_selections.drain(..);
 6978                }
 6979                let cursor_offset = this.selections.last::<usize>(cx).head();
 6980                let mut auto_indent_on_paste = true;
 6981
 6982                this.buffer.update(cx, |buffer, cx| {
 6983                    let snapshot = buffer.read(cx);
 6984                    auto_indent_on_paste =
 6985                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6986
 6987                    let mut start_offset = 0;
 6988                    let mut edits = Vec::new();
 6989                    let mut original_indent_columns = Vec::new();
 6990                    for (ix, selection) in old_selections.iter().enumerate() {
 6991                        let to_insert;
 6992                        let entire_line;
 6993                        let original_indent_column;
 6994                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6995                            let end_offset = start_offset + clipboard_selection.len;
 6996                            to_insert = &clipboard_text[start_offset..end_offset];
 6997                            entire_line = clipboard_selection.is_entire_line;
 6998                            start_offset = end_offset + 1;
 6999                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7000                        } else {
 7001                            to_insert = clipboard_text.as_str();
 7002                            entire_line = all_selections_were_entire_line;
 7003                            original_indent_column = first_selection_indent_column
 7004                        }
 7005
 7006                        // If the corresponding selection was empty when this slice of the
 7007                        // clipboard text was written, then the entire line containing the
 7008                        // selection was copied. If this selection is also currently empty,
 7009                        // then paste the line before the current line of the buffer.
 7010                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7011                            let column = selection.start.to_point(&snapshot).column as usize;
 7012                            let line_start = selection.start - column;
 7013                            line_start..line_start
 7014                        } else {
 7015                            selection.range()
 7016                        };
 7017
 7018                        edits.push((range, to_insert));
 7019                        original_indent_columns.extend(original_indent_column);
 7020                    }
 7021                    drop(snapshot);
 7022
 7023                    buffer.edit(
 7024                        edits,
 7025                        if auto_indent_on_paste {
 7026                            Some(AutoindentMode::Block {
 7027                                original_indent_columns,
 7028                            })
 7029                        } else {
 7030                            None
 7031                        },
 7032                        cx,
 7033                    );
 7034                });
 7035
 7036                let selections = this.selections.all::<usize>(cx);
 7037                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7038            } else {
 7039                this.insert(&clipboard_text, cx);
 7040            }
 7041        });
 7042    }
 7043
 7044    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7045        if let Some(item) = cx.read_from_clipboard() {
 7046            let entries = item.entries();
 7047
 7048            match entries.first() {
 7049                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7050                // of all the pasted entries.
 7051                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7052                    .do_paste(
 7053                        clipboard_string.text(),
 7054                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7055                        true,
 7056                        cx,
 7057                    ),
 7058                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7059            }
 7060        }
 7061    }
 7062
 7063    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7064        if self.read_only(cx) {
 7065            return;
 7066        }
 7067
 7068        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7069            if let Some((selections, _)) =
 7070                self.selection_history.transaction(transaction_id).cloned()
 7071            {
 7072                self.change_selections(None, cx, |s| {
 7073                    s.select_anchors(selections.to_vec());
 7074                });
 7075            }
 7076            self.request_autoscroll(Autoscroll::fit(), cx);
 7077            self.unmark_text(cx);
 7078            self.refresh_inline_completion(true, false, cx);
 7079            cx.emit(EditorEvent::Edited { transaction_id });
 7080            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7081        }
 7082    }
 7083
 7084    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7085        if self.read_only(cx) {
 7086            return;
 7087        }
 7088
 7089        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7090            if let Some((_, Some(selections))) =
 7091                self.selection_history.transaction(transaction_id).cloned()
 7092            {
 7093                self.change_selections(None, cx, |s| {
 7094                    s.select_anchors(selections.to_vec());
 7095                });
 7096            }
 7097            self.request_autoscroll(Autoscroll::fit(), cx);
 7098            self.unmark_text(cx);
 7099            self.refresh_inline_completion(true, false, cx);
 7100            cx.emit(EditorEvent::Edited { transaction_id });
 7101        }
 7102    }
 7103
 7104    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7105        self.buffer
 7106            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7107    }
 7108
 7109    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7110        self.buffer
 7111            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7112    }
 7113
 7114    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7115        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7116            let line_mode = s.line_mode;
 7117            s.move_with(|map, selection| {
 7118                let cursor = if selection.is_empty() && !line_mode {
 7119                    movement::left(map, selection.start)
 7120                } else {
 7121                    selection.start
 7122                };
 7123                selection.collapse_to(cursor, SelectionGoal::None);
 7124            });
 7125        })
 7126    }
 7127
 7128    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7129        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7130            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7131        })
 7132    }
 7133
 7134    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7135        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7136            let line_mode = s.line_mode;
 7137            s.move_with(|map, selection| {
 7138                let cursor = if selection.is_empty() && !line_mode {
 7139                    movement::right(map, selection.end)
 7140                } else {
 7141                    selection.end
 7142                };
 7143                selection.collapse_to(cursor, SelectionGoal::None)
 7144            });
 7145        })
 7146    }
 7147
 7148    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7149        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7150            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7151        })
 7152    }
 7153
 7154    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7155        if self.take_rename(true, cx).is_some() {
 7156            return;
 7157        }
 7158
 7159        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7160            cx.propagate();
 7161            return;
 7162        }
 7163
 7164        let text_layout_details = &self.text_layout_details(cx);
 7165        let selection_count = self.selections.count();
 7166        let first_selection = self.selections.first_anchor();
 7167
 7168        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7169            let line_mode = s.line_mode;
 7170            s.move_with(|map, selection| {
 7171                if !selection.is_empty() && !line_mode {
 7172                    selection.goal = SelectionGoal::None;
 7173                }
 7174                let (cursor, goal) = movement::up(
 7175                    map,
 7176                    selection.start,
 7177                    selection.goal,
 7178                    false,
 7179                    text_layout_details,
 7180                );
 7181                selection.collapse_to(cursor, goal);
 7182            });
 7183        });
 7184
 7185        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7186        {
 7187            cx.propagate();
 7188        }
 7189    }
 7190
 7191    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7192        if self.take_rename(true, cx).is_some() {
 7193            return;
 7194        }
 7195
 7196        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7197            cx.propagate();
 7198            return;
 7199        }
 7200
 7201        let text_layout_details = &self.text_layout_details(cx);
 7202
 7203        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7204            let line_mode = s.line_mode;
 7205            s.move_with(|map, selection| {
 7206                if !selection.is_empty() && !line_mode {
 7207                    selection.goal = SelectionGoal::None;
 7208                }
 7209                let (cursor, goal) = movement::up_by_rows(
 7210                    map,
 7211                    selection.start,
 7212                    action.lines,
 7213                    selection.goal,
 7214                    false,
 7215                    text_layout_details,
 7216                );
 7217                selection.collapse_to(cursor, goal);
 7218            });
 7219        })
 7220    }
 7221
 7222    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7223        if self.take_rename(true, cx).is_some() {
 7224            return;
 7225        }
 7226
 7227        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7228            cx.propagate();
 7229            return;
 7230        }
 7231
 7232        let text_layout_details = &self.text_layout_details(cx);
 7233
 7234        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7235            let line_mode = s.line_mode;
 7236            s.move_with(|map, selection| {
 7237                if !selection.is_empty() && !line_mode {
 7238                    selection.goal = SelectionGoal::None;
 7239                }
 7240                let (cursor, goal) = movement::down_by_rows(
 7241                    map,
 7242                    selection.start,
 7243                    action.lines,
 7244                    selection.goal,
 7245                    false,
 7246                    text_layout_details,
 7247                );
 7248                selection.collapse_to(cursor, goal);
 7249            });
 7250        })
 7251    }
 7252
 7253    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7254        let text_layout_details = &self.text_layout_details(cx);
 7255        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7256            s.move_heads_with(|map, head, goal| {
 7257                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7258            })
 7259        })
 7260    }
 7261
 7262    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7263        let text_layout_details = &self.text_layout_details(cx);
 7264        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7265            s.move_heads_with(|map, head, goal| {
 7266                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7267            })
 7268        })
 7269    }
 7270
 7271    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7272        let Some(row_count) = self.visible_row_count() else {
 7273            return;
 7274        };
 7275
 7276        let text_layout_details = &self.text_layout_details(cx);
 7277
 7278        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7279            s.move_heads_with(|map, head, goal| {
 7280                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7281            })
 7282        })
 7283    }
 7284
 7285    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7286        if self.take_rename(true, cx).is_some() {
 7287            return;
 7288        }
 7289
 7290        if self
 7291            .context_menu
 7292            .borrow_mut()
 7293            .as_mut()
 7294            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7295            .unwrap_or(false)
 7296        {
 7297            return;
 7298        }
 7299
 7300        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7301            cx.propagate();
 7302            return;
 7303        }
 7304
 7305        let Some(row_count) = self.visible_row_count() else {
 7306            return;
 7307        };
 7308
 7309        let autoscroll = if action.center_cursor {
 7310            Autoscroll::center()
 7311        } else {
 7312            Autoscroll::fit()
 7313        };
 7314
 7315        let text_layout_details = &self.text_layout_details(cx);
 7316
 7317        self.change_selections(Some(autoscroll), cx, |s| {
 7318            let line_mode = s.line_mode;
 7319            s.move_with(|map, selection| {
 7320                if !selection.is_empty() && !line_mode {
 7321                    selection.goal = SelectionGoal::None;
 7322                }
 7323                let (cursor, goal) = movement::up_by_rows(
 7324                    map,
 7325                    selection.end,
 7326                    row_count,
 7327                    selection.goal,
 7328                    false,
 7329                    text_layout_details,
 7330                );
 7331                selection.collapse_to(cursor, goal);
 7332            });
 7333        });
 7334    }
 7335
 7336    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7337        let text_layout_details = &self.text_layout_details(cx);
 7338        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7339            s.move_heads_with(|map, head, goal| {
 7340                movement::up(map, head, goal, false, text_layout_details)
 7341            })
 7342        })
 7343    }
 7344
 7345    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7346        self.take_rename(true, cx);
 7347
 7348        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7349            cx.propagate();
 7350            return;
 7351        }
 7352
 7353        let text_layout_details = &self.text_layout_details(cx);
 7354        let selection_count = self.selections.count();
 7355        let first_selection = self.selections.first_anchor();
 7356
 7357        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7358            let line_mode = s.line_mode;
 7359            s.move_with(|map, selection| {
 7360                if !selection.is_empty() && !line_mode {
 7361                    selection.goal = SelectionGoal::None;
 7362                }
 7363                let (cursor, goal) = movement::down(
 7364                    map,
 7365                    selection.end,
 7366                    selection.goal,
 7367                    false,
 7368                    text_layout_details,
 7369                );
 7370                selection.collapse_to(cursor, goal);
 7371            });
 7372        });
 7373
 7374        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7375        {
 7376            cx.propagate();
 7377        }
 7378    }
 7379
 7380    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7381        let Some(row_count) = self.visible_row_count() else {
 7382            return;
 7383        };
 7384
 7385        let text_layout_details = &self.text_layout_details(cx);
 7386
 7387        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7388            s.move_heads_with(|map, head, goal| {
 7389                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7390            })
 7391        })
 7392    }
 7393
 7394    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7395        if self.take_rename(true, cx).is_some() {
 7396            return;
 7397        }
 7398
 7399        if self
 7400            .context_menu
 7401            .borrow_mut()
 7402            .as_mut()
 7403            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7404            .unwrap_or(false)
 7405        {
 7406            return;
 7407        }
 7408
 7409        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7410            cx.propagate();
 7411            return;
 7412        }
 7413
 7414        let Some(row_count) = self.visible_row_count() else {
 7415            return;
 7416        };
 7417
 7418        let autoscroll = if action.center_cursor {
 7419            Autoscroll::center()
 7420        } else {
 7421            Autoscroll::fit()
 7422        };
 7423
 7424        let text_layout_details = &self.text_layout_details(cx);
 7425        self.change_selections(Some(autoscroll), cx, |s| {
 7426            let line_mode = s.line_mode;
 7427            s.move_with(|map, selection| {
 7428                if !selection.is_empty() && !line_mode {
 7429                    selection.goal = SelectionGoal::None;
 7430                }
 7431                let (cursor, goal) = movement::down_by_rows(
 7432                    map,
 7433                    selection.end,
 7434                    row_count,
 7435                    selection.goal,
 7436                    false,
 7437                    text_layout_details,
 7438                );
 7439                selection.collapse_to(cursor, goal);
 7440            });
 7441        });
 7442    }
 7443
 7444    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7445        let text_layout_details = &self.text_layout_details(cx);
 7446        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7447            s.move_heads_with(|map, head, goal| {
 7448                movement::down(map, head, goal, false, text_layout_details)
 7449            })
 7450        });
 7451    }
 7452
 7453    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7454        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7455            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7456        }
 7457    }
 7458
 7459    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7460        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7461            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7462        }
 7463    }
 7464
 7465    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7466        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7467            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7468        }
 7469    }
 7470
 7471    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7472        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7473            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7474        }
 7475    }
 7476
 7477    pub fn move_to_previous_word_start(
 7478        &mut self,
 7479        _: &MoveToPreviousWordStart,
 7480        cx: &mut ViewContext<Self>,
 7481    ) {
 7482        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7483            s.move_cursors_with(|map, head, _| {
 7484                (
 7485                    movement::previous_word_start(map, head),
 7486                    SelectionGoal::None,
 7487                )
 7488            });
 7489        })
 7490    }
 7491
 7492    pub fn move_to_previous_subword_start(
 7493        &mut self,
 7494        _: &MoveToPreviousSubwordStart,
 7495        cx: &mut ViewContext<Self>,
 7496    ) {
 7497        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7498            s.move_cursors_with(|map, head, _| {
 7499                (
 7500                    movement::previous_subword_start(map, head),
 7501                    SelectionGoal::None,
 7502                )
 7503            });
 7504        })
 7505    }
 7506
 7507    pub fn select_to_previous_word_start(
 7508        &mut self,
 7509        _: &SelectToPreviousWordStart,
 7510        cx: &mut ViewContext<Self>,
 7511    ) {
 7512        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7513            s.move_heads_with(|map, head, _| {
 7514                (
 7515                    movement::previous_word_start(map, head),
 7516                    SelectionGoal::None,
 7517                )
 7518            });
 7519        })
 7520    }
 7521
 7522    pub fn select_to_previous_subword_start(
 7523        &mut self,
 7524        _: &SelectToPreviousSubwordStart,
 7525        cx: &mut ViewContext<Self>,
 7526    ) {
 7527        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7528            s.move_heads_with(|map, head, _| {
 7529                (
 7530                    movement::previous_subword_start(map, head),
 7531                    SelectionGoal::None,
 7532                )
 7533            });
 7534        })
 7535    }
 7536
 7537    pub fn delete_to_previous_word_start(
 7538        &mut self,
 7539        action: &DeleteToPreviousWordStart,
 7540        cx: &mut ViewContext<Self>,
 7541    ) {
 7542        self.transact(cx, |this, cx| {
 7543            this.select_autoclose_pair(cx);
 7544            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7545                let line_mode = s.line_mode;
 7546                s.move_with(|map, selection| {
 7547                    if selection.is_empty() && !line_mode {
 7548                        let cursor = if action.ignore_newlines {
 7549                            movement::previous_word_start(map, selection.head())
 7550                        } else {
 7551                            movement::previous_word_start_or_newline(map, selection.head())
 7552                        };
 7553                        selection.set_head(cursor, SelectionGoal::None);
 7554                    }
 7555                });
 7556            });
 7557            this.insert("", cx);
 7558        });
 7559    }
 7560
 7561    pub fn delete_to_previous_subword_start(
 7562        &mut self,
 7563        _: &DeleteToPreviousSubwordStart,
 7564        cx: &mut ViewContext<Self>,
 7565    ) {
 7566        self.transact(cx, |this, cx| {
 7567            this.select_autoclose_pair(cx);
 7568            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7569                let line_mode = s.line_mode;
 7570                s.move_with(|map, selection| {
 7571                    if selection.is_empty() && !line_mode {
 7572                        let cursor = movement::previous_subword_start(map, selection.head());
 7573                        selection.set_head(cursor, SelectionGoal::None);
 7574                    }
 7575                });
 7576            });
 7577            this.insert("", cx);
 7578        });
 7579    }
 7580
 7581    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7582        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7583            s.move_cursors_with(|map, head, _| {
 7584                (movement::next_word_end(map, head), SelectionGoal::None)
 7585            });
 7586        })
 7587    }
 7588
 7589    pub fn move_to_next_subword_end(
 7590        &mut self,
 7591        _: &MoveToNextSubwordEnd,
 7592        cx: &mut ViewContext<Self>,
 7593    ) {
 7594        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7595            s.move_cursors_with(|map, head, _| {
 7596                (movement::next_subword_end(map, head), SelectionGoal::None)
 7597            });
 7598        })
 7599    }
 7600
 7601    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7602        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7603            s.move_heads_with(|map, head, _| {
 7604                (movement::next_word_end(map, head), SelectionGoal::None)
 7605            });
 7606        })
 7607    }
 7608
 7609    pub fn select_to_next_subword_end(
 7610        &mut self,
 7611        _: &SelectToNextSubwordEnd,
 7612        cx: &mut ViewContext<Self>,
 7613    ) {
 7614        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7615            s.move_heads_with(|map, head, _| {
 7616                (movement::next_subword_end(map, head), SelectionGoal::None)
 7617            });
 7618        })
 7619    }
 7620
 7621    pub fn delete_to_next_word_end(
 7622        &mut self,
 7623        action: &DeleteToNextWordEnd,
 7624        cx: &mut ViewContext<Self>,
 7625    ) {
 7626        self.transact(cx, |this, cx| {
 7627            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7628                let line_mode = s.line_mode;
 7629                s.move_with(|map, selection| {
 7630                    if selection.is_empty() && !line_mode {
 7631                        let cursor = if action.ignore_newlines {
 7632                            movement::next_word_end(map, selection.head())
 7633                        } else {
 7634                            movement::next_word_end_or_newline(map, selection.head())
 7635                        };
 7636                        selection.set_head(cursor, SelectionGoal::None);
 7637                    }
 7638                });
 7639            });
 7640            this.insert("", cx);
 7641        });
 7642    }
 7643
 7644    pub fn delete_to_next_subword_end(
 7645        &mut self,
 7646        _: &DeleteToNextSubwordEnd,
 7647        cx: &mut ViewContext<Self>,
 7648    ) {
 7649        self.transact(cx, |this, cx| {
 7650            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7651                s.move_with(|map, selection| {
 7652                    if selection.is_empty() {
 7653                        let cursor = movement::next_subword_end(map, selection.head());
 7654                        selection.set_head(cursor, SelectionGoal::None);
 7655                    }
 7656                });
 7657            });
 7658            this.insert("", cx);
 7659        });
 7660    }
 7661
 7662    pub fn move_to_beginning_of_line(
 7663        &mut self,
 7664        action: &MoveToBeginningOfLine,
 7665        cx: &mut ViewContext<Self>,
 7666    ) {
 7667        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7668            s.move_cursors_with(|map, head, _| {
 7669                (
 7670                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7671                    SelectionGoal::None,
 7672                )
 7673            });
 7674        })
 7675    }
 7676
 7677    pub fn select_to_beginning_of_line(
 7678        &mut self,
 7679        action: &SelectToBeginningOfLine,
 7680        cx: &mut ViewContext<Self>,
 7681    ) {
 7682        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7683            s.move_heads_with(|map, head, _| {
 7684                (
 7685                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7686                    SelectionGoal::None,
 7687                )
 7688            });
 7689        });
 7690    }
 7691
 7692    pub fn delete_to_beginning_of_line(
 7693        &mut self,
 7694        _: &DeleteToBeginningOfLine,
 7695        cx: &mut ViewContext<Self>,
 7696    ) {
 7697        self.transact(cx, |this, cx| {
 7698            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7699                s.move_with(|_, selection| {
 7700                    selection.reversed = true;
 7701                });
 7702            });
 7703
 7704            this.select_to_beginning_of_line(
 7705                &SelectToBeginningOfLine {
 7706                    stop_at_soft_wraps: false,
 7707                },
 7708                cx,
 7709            );
 7710            this.backspace(&Backspace, cx);
 7711        });
 7712    }
 7713
 7714    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7715        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7716            s.move_cursors_with(|map, head, _| {
 7717                (
 7718                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7719                    SelectionGoal::None,
 7720                )
 7721            });
 7722        })
 7723    }
 7724
 7725    pub fn select_to_end_of_line(
 7726        &mut self,
 7727        action: &SelectToEndOfLine,
 7728        cx: &mut ViewContext<Self>,
 7729    ) {
 7730        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7731            s.move_heads_with(|map, head, _| {
 7732                (
 7733                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7734                    SelectionGoal::None,
 7735                )
 7736            });
 7737        })
 7738    }
 7739
 7740    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7741        self.transact(cx, |this, cx| {
 7742            this.select_to_end_of_line(
 7743                &SelectToEndOfLine {
 7744                    stop_at_soft_wraps: false,
 7745                },
 7746                cx,
 7747            );
 7748            this.delete(&Delete, cx);
 7749        });
 7750    }
 7751
 7752    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7753        self.transact(cx, |this, cx| {
 7754            this.select_to_end_of_line(
 7755                &SelectToEndOfLine {
 7756                    stop_at_soft_wraps: false,
 7757                },
 7758                cx,
 7759            );
 7760            this.cut(&Cut, cx);
 7761        });
 7762    }
 7763
 7764    pub fn move_to_start_of_paragraph(
 7765        &mut self,
 7766        _: &MoveToStartOfParagraph,
 7767        cx: &mut ViewContext<Self>,
 7768    ) {
 7769        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7770            cx.propagate();
 7771            return;
 7772        }
 7773
 7774        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7775            s.move_with(|map, selection| {
 7776                selection.collapse_to(
 7777                    movement::start_of_paragraph(map, selection.head(), 1),
 7778                    SelectionGoal::None,
 7779                )
 7780            });
 7781        })
 7782    }
 7783
 7784    pub fn move_to_end_of_paragraph(
 7785        &mut self,
 7786        _: &MoveToEndOfParagraph,
 7787        cx: &mut ViewContext<Self>,
 7788    ) {
 7789        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7790            cx.propagate();
 7791            return;
 7792        }
 7793
 7794        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7795            s.move_with(|map, selection| {
 7796                selection.collapse_to(
 7797                    movement::end_of_paragraph(map, selection.head(), 1),
 7798                    SelectionGoal::None,
 7799                )
 7800            });
 7801        })
 7802    }
 7803
 7804    pub fn select_to_start_of_paragraph(
 7805        &mut self,
 7806        _: &SelectToStartOfParagraph,
 7807        cx: &mut ViewContext<Self>,
 7808    ) {
 7809        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7810            cx.propagate();
 7811            return;
 7812        }
 7813
 7814        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7815            s.move_heads_with(|map, head, _| {
 7816                (
 7817                    movement::start_of_paragraph(map, head, 1),
 7818                    SelectionGoal::None,
 7819                )
 7820            });
 7821        })
 7822    }
 7823
 7824    pub fn select_to_end_of_paragraph(
 7825        &mut self,
 7826        _: &SelectToEndOfParagraph,
 7827        cx: &mut ViewContext<Self>,
 7828    ) {
 7829        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7830            cx.propagate();
 7831            return;
 7832        }
 7833
 7834        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7835            s.move_heads_with(|map, head, _| {
 7836                (
 7837                    movement::end_of_paragraph(map, head, 1),
 7838                    SelectionGoal::None,
 7839                )
 7840            });
 7841        })
 7842    }
 7843
 7844    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7845        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7846            cx.propagate();
 7847            return;
 7848        }
 7849
 7850        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7851            s.select_ranges(vec![0..0]);
 7852        });
 7853    }
 7854
 7855    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7856        let mut selection = self.selections.last::<Point>(cx);
 7857        selection.set_head(Point::zero(), SelectionGoal::None);
 7858
 7859        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7860            s.select(vec![selection]);
 7861        });
 7862    }
 7863
 7864    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7865        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7866            cx.propagate();
 7867            return;
 7868        }
 7869
 7870        let cursor = self.buffer.read(cx).read(cx).len();
 7871        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7872            s.select_ranges(vec![cursor..cursor])
 7873        });
 7874    }
 7875
 7876    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7877        self.nav_history = nav_history;
 7878    }
 7879
 7880    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7881        self.nav_history.as_ref()
 7882    }
 7883
 7884    fn push_to_nav_history(
 7885        &mut self,
 7886        cursor_anchor: Anchor,
 7887        new_position: Option<Point>,
 7888        cx: &mut ViewContext<Self>,
 7889    ) {
 7890        if let Some(nav_history) = self.nav_history.as_mut() {
 7891            let buffer = self.buffer.read(cx).read(cx);
 7892            let cursor_position = cursor_anchor.to_point(&buffer);
 7893            let scroll_state = self.scroll_manager.anchor();
 7894            let scroll_top_row = scroll_state.top_row(&buffer);
 7895            drop(buffer);
 7896
 7897            if let Some(new_position) = new_position {
 7898                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7899                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7900                    return;
 7901                }
 7902            }
 7903
 7904            nav_history.push(
 7905                Some(NavigationData {
 7906                    cursor_anchor,
 7907                    cursor_position,
 7908                    scroll_anchor: scroll_state,
 7909                    scroll_top_row,
 7910                }),
 7911                cx,
 7912            );
 7913        }
 7914    }
 7915
 7916    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7917        let buffer = self.buffer.read(cx).snapshot(cx);
 7918        let mut selection = self.selections.first::<usize>(cx);
 7919        selection.set_head(buffer.len(), SelectionGoal::None);
 7920        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7921            s.select(vec![selection]);
 7922        });
 7923    }
 7924
 7925    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7926        let end = self.buffer.read(cx).read(cx).len();
 7927        self.change_selections(None, cx, |s| {
 7928            s.select_ranges(vec![0..end]);
 7929        });
 7930    }
 7931
 7932    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7933        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7934        let mut selections = self.selections.all::<Point>(cx);
 7935        let max_point = display_map.buffer_snapshot.max_point();
 7936        for selection in &mut selections {
 7937            let rows = selection.spanned_rows(true, &display_map);
 7938            selection.start = Point::new(rows.start.0, 0);
 7939            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7940            selection.reversed = false;
 7941        }
 7942        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7943            s.select(selections);
 7944        });
 7945    }
 7946
 7947    pub fn split_selection_into_lines(
 7948        &mut self,
 7949        _: &SplitSelectionIntoLines,
 7950        cx: &mut ViewContext<Self>,
 7951    ) {
 7952        let mut to_unfold = Vec::new();
 7953        let mut new_selection_ranges = Vec::new();
 7954        {
 7955            let selections = self.selections.all::<Point>(cx);
 7956            let buffer = self.buffer.read(cx).read(cx);
 7957            for selection in selections {
 7958                for row in selection.start.row..selection.end.row {
 7959                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7960                    new_selection_ranges.push(cursor..cursor);
 7961                }
 7962                new_selection_ranges.push(selection.end..selection.end);
 7963                to_unfold.push(selection.start..selection.end);
 7964            }
 7965        }
 7966        self.unfold_ranges(&to_unfold, true, true, cx);
 7967        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7968            s.select_ranges(new_selection_ranges);
 7969        });
 7970    }
 7971
 7972    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7973        self.add_selection(true, cx);
 7974    }
 7975
 7976    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7977        self.add_selection(false, cx);
 7978    }
 7979
 7980    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7981        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7982        let mut selections = self.selections.all::<Point>(cx);
 7983        let text_layout_details = self.text_layout_details(cx);
 7984        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7985            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7986            let range = oldest_selection.display_range(&display_map).sorted();
 7987
 7988            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7989            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7990            let positions = start_x.min(end_x)..start_x.max(end_x);
 7991
 7992            selections.clear();
 7993            let mut stack = Vec::new();
 7994            for row in range.start.row().0..=range.end.row().0 {
 7995                if let Some(selection) = self.selections.build_columnar_selection(
 7996                    &display_map,
 7997                    DisplayRow(row),
 7998                    &positions,
 7999                    oldest_selection.reversed,
 8000                    &text_layout_details,
 8001                ) {
 8002                    stack.push(selection.id);
 8003                    selections.push(selection);
 8004                }
 8005            }
 8006
 8007            if above {
 8008                stack.reverse();
 8009            }
 8010
 8011            AddSelectionsState { above, stack }
 8012        });
 8013
 8014        let last_added_selection = *state.stack.last().unwrap();
 8015        let mut new_selections = Vec::new();
 8016        if above == state.above {
 8017            let end_row = if above {
 8018                DisplayRow(0)
 8019            } else {
 8020                display_map.max_point().row()
 8021            };
 8022
 8023            'outer: for selection in selections {
 8024                if selection.id == last_added_selection {
 8025                    let range = selection.display_range(&display_map).sorted();
 8026                    debug_assert_eq!(range.start.row(), range.end.row());
 8027                    let mut row = range.start.row();
 8028                    let positions =
 8029                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8030                            px(start)..px(end)
 8031                        } else {
 8032                            let start_x =
 8033                                display_map.x_for_display_point(range.start, &text_layout_details);
 8034                            let end_x =
 8035                                display_map.x_for_display_point(range.end, &text_layout_details);
 8036                            start_x.min(end_x)..start_x.max(end_x)
 8037                        };
 8038
 8039                    while row != end_row {
 8040                        if above {
 8041                            row.0 -= 1;
 8042                        } else {
 8043                            row.0 += 1;
 8044                        }
 8045
 8046                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8047                            &display_map,
 8048                            row,
 8049                            &positions,
 8050                            selection.reversed,
 8051                            &text_layout_details,
 8052                        ) {
 8053                            state.stack.push(new_selection.id);
 8054                            if above {
 8055                                new_selections.push(new_selection);
 8056                                new_selections.push(selection);
 8057                            } else {
 8058                                new_selections.push(selection);
 8059                                new_selections.push(new_selection);
 8060                            }
 8061
 8062                            continue 'outer;
 8063                        }
 8064                    }
 8065                }
 8066
 8067                new_selections.push(selection);
 8068            }
 8069        } else {
 8070            new_selections = selections;
 8071            new_selections.retain(|s| s.id != last_added_selection);
 8072            state.stack.pop();
 8073        }
 8074
 8075        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8076            s.select(new_selections);
 8077        });
 8078        if state.stack.len() > 1 {
 8079            self.add_selections_state = Some(state);
 8080        }
 8081    }
 8082
 8083    pub fn select_next_match_internal(
 8084        &mut self,
 8085        display_map: &DisplaySnapshot,
 8086        replace_newest: bool,
 8087        autoscroll: Option<Autoscroll>,
 8088        cx: &mut ViewContext<Self>,
 8089    ) -> Result<()> {
 8090        fn select_next_match_ranges(
 8091            this: &mut Editor,
 8092            range: Range<usize>,
 8093            replace_newest: bool,
 8094            auto_scroll: Option<Autoscroll>,
 8095            cx: &mut ViewContext<Editor>,
 8096        ) {
 8097            this.unfold_ranges(&[range.clone()], false, true, cx);
 8098            this.change_selections(auto_scroll, cx, |s| {
 8099                if replace_newest {
 8100                    s.delete(s.newest_anchor().id);
 8101                }
 8102                s.insert_range(range.clone());
 8103            });
 8104        }
 8105
 8106        let buffer = &display_map.buffer_snapshot;
 8107        let mut selections = self.selections.all::<usize>(cx);
 8108        if let Some(mut select_next_state) = self.select_next_state.take() {
 8109            let query = &select_next_state.query;
 8110            if !select_next_state.done {
 8111                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8112                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8113                let mut next_selected_range = None;
 8114
 8115                let bytes_after_last_selection =
 8116                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8117                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8118                let query_matches = query
 8119                    .stream_find_iter(bytes_after_last_selection)
 8120                    .map(|result| (last_selection.end, result))
 8121                    .chain(
 8122                        query
 8123                            .stream_find_iter(bytes_before_first_selection)
 8124                            .map(|result| (0, result)),
 8125                    );
 8126
 8127                for (start_offset, query_match) in query_matches {
 8128                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8129                    let offset_range =
 8130                        start_offset + query_match.start()..start_offset + query_match.end();
 8131                    let display_range = offset_range.start.to_display_point(display_map)
 8132                        ..offset_range.end.to_display_point(display_map);
 8133
 8134                    if !select_next_state.wordwise
 8135                        || (!movement::is_inside_word(display_map, display_range.start)
 8136                            && !movement::is_inside_word(display_map, display_range.end))
 8137                    {
 8138                        // TODO: This is n^2, because we might check all the selections
 8139                        if !selections
 8140                            .iter()
 8141                            .any(|selection| selection.range().overlaps(&offset_range))
 8142                        {
 8143                            next_selected_range = Some(offset_range);
 8144                            break;
 8145                        }
 8146                    }
 8147                }
 8148
 8149                if let Some(next_selected_range) = next_selected_range {
 8150                    select_next_match_ranges(
 8151                        self,
 8152                        next_selected_range,
 8153                        replace_newest,
 8154                        autoscroll,
 8155                        cx,
 8156                    );
 8157                } else {
 8158                    select_next_state.done = true;
 8159                }
 8160            }
 8161
 8162            self.select_next_state = Some(select_next_state);
 8163        } else {
 8164            let mut only_carets = true;
 8165            let mut same_text_selected = true;
 8166            let mut selected_text = None;
 8167
 8168            let mut selections_iter = selections.iter().peekable();
 8169            while let Some(selection) = selections_iter.next() {
 8170                if selection.start != selection.end {
 8171                    only_carets = false;
 8172                }
 8173
 8174                if same_text_selected {
 8175                    if selected_text.is_none() {
 8176                        selected_text =
 8177                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8178                    }
 8179
 8180                    if let Some(next_selection) = selections_iter.peek() {
 8181                        if next_selection.range().len() == selection.range().len() {
 8182                            let next_selected_text = buffer
 8183                                .text_for_range(next_selection.range())
 8184                                .collect::<String>();
 8185                            if Some(next_selected_text) != selected_text {
 8186                                same_text_selected = false;
 8187                                selected_text = None;
 8188                            }
 8189                        } else {
 8190                            same_text_selected = false;
 8191                            selected_text = None;
 8192                        }
 8193                    }
 8194                }
 8195            }
 8196
 8197            if only_carets {
 8198                for selection in &mut selections {
 8199                    let word_range = movement::surrounding_word(
 8200                        display_map,
 8201                        selection.start.to_display_point(display_map),
 8202                    );
 8203                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8204                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8205                    selection.goal = SelectionGoal::None;
 8206                    selection.reversed = false;
 8207                    select_next_match_ranges(
 8208                        self,
 8209                        selection.start..selection.end,
 8210                        replace_newest,
 8211                        autoscroll,
 8212                        cx,
 8213                    );
 8214                }
 8215
 8216                if selections.len() == 1 {
 8217                    let selection = selections
 8218                        .last()
 8219                        .expect("ensured that there's only one selection");
 8220                    let query = buffer
 8221                        .text_for_range(selection.start..selection.end)
 8222                        .collect::<String>();
 8223                    let is_empty = query.is_empty();
 8224                    let select_state = SelectNextState {
 8225                        query: AhoCorasick::new(&[query])?,
 8226                        wordwise: true,
 8227                        done: is_empty,
 8228                    };
 8229                    self.select_next_state = Some(select_state);
 8230                } else {
 8231                    self.select_next_state = None;
 8232                }
 8233            } else if let Some(selected_text) = selected_text {
 8234                self.select_next_state = Some(SelectNextState {
 8235                    query: AhoCorasick::new(&[selected_text])?,
 8236                    wordwise: false,
 8237                    done: false,
 8238                });
 8239                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8240            }
 8241        }
 8242        Ok(())
 8243    }
 8244
 8245    pub fn select_all_matches(
 8246        &mut self,
 8247        _action: &SelectAllMatches,
 8248        cx: &mut ViewContext<Self>,
 8249    ) -> Result<()> {
 8250        self.push_to_selection_history();
 8251        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8252
 8253        self.select_next_match_internal(&display_map, false, None, cx)?;
 8254        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8255            return Ok(());
 8256        };
 8257        if select_next_state.done {
 8258            return Ok(());
 8259        }
 8260
 8261        let mut new_selections = self.selections.all::<usize>(cx);
 8262
 8263        let buffer = &display_map.buffer_snapshot;
 8264        let query_matches = select_next_state
 8265            .query
 8266            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8267
 8268        for query_match in query_matches {
 8269            let query_match = query_match.unwrap(); // can only fail due to I/O
 8270            let offset_range = query_match.start()..query_match.end();
 8271            let display_range = offset_range.start.to_display_point(&display_map)
 8272                ..offset_range.end.to_display_point(&display_map);
 8273
 8274            if !select_next_state.wordwise
 8275                || (!movement::is_inside_word(&display_map, display_range.start)
 8276                    && !movement::is_inside_word(&display_map, display_range.end))
 8277            {
 8278                self.selections.change_with(cx, |selections| {
 8279                    new_selections.push(Selection {
 8280                        id: selections.new_selection_id(),
 8281                        start: offset_range.start,
 8282                        end: offset_range.end,
 8283                        reversed: false,
 8284                        goal: SelectionGoal::None,
 8285                    });
 8286                });
 8287            }
 8288        }
 8289
 8290        new_selections.sort_by_key(|selection| selection.start);
 8291        let mut ix = 0;
 8292        while ix + 1 < new_selections.len() {
 8293            let current_selection = &new_selections[ix];
 8294            let next_selection = &new_selections[ix + 1];
 8295            if current_selection.range().overlaps(&next_selection.range()) {
 8296                if current_selection.id < next_selection.id {
 8297                    new_selections.remove(ix + 1);
 8298                } else {
 8299                    new_selections.remove(ix);
 8300                }
 8301            } else {
 8302                ix += 1;
 8303            }
 8304        }
 8305
 8306        select_next_state.done = true;
 8307        self.unfold_ranges(
 8308            &new_selections
 8309                .iter()
 8310                .map(|selection| selection.range())
 8311                .collect::<Vec<_>>(),
 8312            false,
 8313            false,
 8314            cx,
 8315        );
 8316        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8317            selections.select(new_selections)
 8318        });
 8319
 8320        Ok(())
 8321    }
 8322
 8323    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8324        self.push_to_selection_history();
 8325        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8326        self.select_next_match_internal(
 8327            &display_map,
 8328            action.replace_newest,
 8329            Some(Autoscroll::newest()),
 8330            cx,
 8331        )?;
 8332        Ok(())
 8333    }
 8334
 8335    pub fn select_previous(
 8336        &mut self,
 8337        action: &SelectPrevious,
 8338        cx: &mut ViewContext<Self>,
 8339    ) -> Result<()> {
 8340        self.push_to_selection_history();
 8341        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8342        let buffer = &display_map.buffer_snapshot;
 8343        let mut selections = self.selections.all::<usize>(cx);
 8344        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8345            let query = &select_prev_state.query;
 8346            if !select_prev_state.done {
 8347                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8348                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8349                let mut next_selected_range = None;
 8350                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8351                let bytes_before_last_selection =
 8352                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8353                let bytes_after_first_selection =
 8354                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8355                let query_matches = query
 8356                    .stream_find_iter(bytes_before_last_selection)
 8357                    .map(|result| (last_selection.start, result))
 8358                    .chain(
 8359                        query
 8360                            .stream_find_iter(bytes_after_first_selection)
 8361                            .map(|result| (buffer.len(), result)),
 8362                    );
 8363                for (end_offset, query_match) in query_matches {
 8364                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8365                    let offset_range =
 8366                        end_offset - query_match.end()..end_offset - query_match.start();
 8367                    let display_range = offset_range.start.to_display_point(&display_map)
 8368                        ..offset_range.end.to_display_point(&display_map);
 8369
 8370                    if !select_prev_state.wordwise
 8371                        || (!movement::is_inside_word(&display_map, display_range.start)
 8372                            && !movement::is_inside_word(&display_map, display_range.end))
 8373                    {
 8374                        next_selected_range = Some(offset_range);
 8375                        break;
 8376                    }
 8377                }
 8378
 8379                if let Some(next_selected_range) = next_selected_range {
 8380                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8381                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8382                        if action.replace_newest {
 8383                            s.delete(s.newest_anchor().id);
 8384                        }
 8385                        s.insert_range(next_selected_range);
 8386                    });
 8387                } else {
 8388                    select_prev_state.done = true;
 8389                }
 8390            }
 8391
 8392            self.select_prev_state = Some(select_prev_state);
 8393        } else {
 8394            let mut only_carets = true;
 8395            let mut same_text_selected = true;
 8396            let mut selected_text = None;
 8397
 8398            let mut selections_iter = selections.iter().peekable();
 8399            while let Some(selection) = selections_iter.next() {
 8400                if selection.start != selection.end {
 8401                    only_carets = false;
 8402                }
 8403
 8404                if same_text_selected {
 8405                    if selected_text.is_none() {
 8406                        selected_text =
 8407                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8408                    }
 8409
 8410                    if let Some(next_selection) = selections_iter.peek() {
 8411                        if next_selection.range().len() == selection.range().len() {
 8412                            let next_selected_text = buffer
 8413                                .text_for_range(next_selection.range())
 8414                                .collect::<String>();
 8415                            if Some(next_selected_text) != selected_text {
 8416                                same_text_selected = false;
 8417                                selected_text = None;
 8418                            }
 8419                        } else {
 8420                            same_text_selected = false;
 8421                            selected_text = None;
 8422                        }
 8423                    }
 8424                }
 8425            }
 8426
 8427            if only_carets {
 8428                for selection in &mut selections {
 8429                    let word_range = movement::surrounding_word(
 8430                        &display_map,
 8431                        selection.start.to_display_point(&display_map),
 8432                    );
 8433                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8434                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8435                    selection.goal = SelectionGoal::None;
 8436                    selection.reversed = false;
 8437                }
 8438                if selections.len() == 1 {
 8439                    let selection = selections
 8440                        .last()
 8441                        .expect("ensured that there's only one selection");
 8442                    let query = buffer
 8443                        .text_for_range(selection.start..selection.end)
 8444                        .collect::<String>();
 8445                    let is_empty = query.is_empty();
 8446                    let select_state = SelectNextState {
 8447                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8448                        wordwise: true,
 8449                        done: is_empty,
 8450                    };
 8451                    self.select_prev_state = Some(select_state);
 8452                } else {
 8453                    self.select_prev_state = None;
 8454                }
 8455
 8456                self.unfold_ranges(
 8457                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8458                    false,
 8459                    true,
 8460                    cx,
 8461                );
 8462                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8463                    s.select(selections);
 8464                });
 8465            } else if let Some(selected_text) = selected_text {
 8466                self.select_prev_state = Some(SelectNextState {
 8467                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8468                    wordwise: false,
 8469                    done: false,
 8470                });
 8471                self.select_previous(action, cx)?;
 8472            }
 8473        }
 8474        Ok(())
 8475    }
 8476
 8477    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8478        if self.read_only(cx) {
 8479            return;
 8480        }
 8481        let text_layout_details = &self.text_layout_details(cx);
 8482        self.transact(cx, |this, cx| {
 8483            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8484            let mut edits = Vec::new();
 8485            let mut selection_edit_ranges = Vec::new();
 8486            let mut last_toggled_row = None;
 8487            let snapshot = this.buffer.read(cx).read(cx);
 8488            let empty_str: Arc<str> = Arc::default();
 8489            let mut suffixes_inserted = Vec::new();
 8490            let ignore_indent = action.ignore_indent;
 8491
 8492            fn comment_prefix_range(
 8493                snapshot: &MultiBufferSnapshot,
 8494                row: MultiBufferRow,
 8495                comment_prefix: &str,
 8496                comment_prefix_whitespace: &str,
 8497                ignore_indent: bool,
 8498            ) -> Range<Point> {
 8499                let indent_size = if ignore_indent {
 8500                    0
 8501                } else {
 8502                    snapshot.indent_size_for_line(row).len
 8503                };
 8504
 8505                let start = Point::new(row.0, indent_size);
 8506
 8507                let mut line_bytes = snapshot
 8508                    .bytes_in_range(start..snapshot.max_point())
 8509                    .flatten()
 8510                    .copied();
 8511
 8512                // If this line currently begins with the line comment prefix, then record
 8513                // the range containing the prefix.
 8514                if line_bytes
 8515                    .by_ref()
 8516                    .take(comment_prefix.len())
 8517                    .eq(comment_prefix.bytes())
 8518                {
 8519                    // Include any whitespace that matches the comment prefix.
 8520                    let matching_whitespace_len = line_bytes
 8521                        .zip(comment_prefix_whitespace.bytes())
 8522                        .take_while(|(a, b)| a == b)
 8523                        .count() as u32;
 8524                    let end = Point::new(
 8525                        start.row,
 8526                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8527                    );
 8528                    start..end
 8529                } else {
 8530                    start..start
 8531                }
 8532            }
 8533
 8534            fn comment_suffix_range(
 8535                snapshot: &MultiBufferSnapshot,
 8536                row: MultiBufferRow,
 8537                comment_suffix: &str,
 8538                comment_suffix_has_leading_space: bool,
 8539            ) -> Range<Point> {
 8540                let end = Point::new(row.0, snapshot.line_len(row));
 8541                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8542
 8543                let mut line_end_bytes = snapshot
 8544                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8545                    .flatten()
 8546                    .copied();
 8547
 8548                let leading_space_len = if suffix_start_column > 0
 8549                    && line_end_bytes.next() == Some(b' ')
 8550                    && comment_suffix_has_leading_space
 8551                {
 8552                    1
 8553                } else {
 8554                    0
 8555                };
 8556
 8557                // If this line currently begins with the line comment prefix, then record
 8558                // the range containing the prefix.
 8559                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8560                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8561                    start..end
 8562                } else {
 8563                    end..end
 8564                }
 8565            }
 8566
 8567            // TODO: Handle selections that cross excerpts
 8568            for selection in &mut selections {
 8569                let start_column = snapshot
 8570                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8571                    .len;
 8572                let language = if let Some(language) =
 8573                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8574                {
 8575                    language
 8576                } else {
 8577                    continue;
 8578                };
 8579
 8580                selection_edit_ranges.clear();
 8581
 8582                // If multiple selections contain a given row, avoid processing that
 8583                // row more than once.
 8584                let mut start_row = MultiBufferRow(selection.start.row);
 8585                if last_toggled_row == Some(start_row) {
 8586                    start_row = start_row.next_row();
 8587                }
 8588                let end_row =
 8589                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8590                        MultiBufferRow(selection.end.row - 1)
 8591                    } else {
 8592                        MultiBufferRow(selection.end.row)
 8593                    };
 8594                last_toggled_row = Some(end_row);
 8595
 8596                if start_row > end_row {
 8597                    continue;
 8598                }
 8599
 8600                // If the language has line comments, toggle those.
 8601                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8602
 8603                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8604                if ignore_indent {
 8605                    full_comment_prefixes = full_comment_prefixes
 8606                        .into_iter()
 8607                        .map(|s| Arc::from(s.trim_end()))
 8608                        .collect();
 8609                }
 8610
 8611                if !full_comment_prefixes.is_empty() {
 8612                    let first_prefix = full_comment_prefixes
 8613                        .first()
 8614                        .expect("prefixes is non-empty");
 8615                    let prefix_trimmed_lengths = full_comment_prefixes
 8616                        .iter()
 8617                        .map(|p| p.trim_end_matches(' ').len())
 8618                        .collect::<SmallVec<[usize; 4]>>();
 8619
 8620                    let mut all_selection_lines_are_comments = true;
 8621
 8622                    for row in start_row.0..=end_row.0 {
 8623                        let row = MultiBufferRow(row);
 8624                        if start_row < end_row && snapshot.is_line_blank(row) {
 8625                            continue;
 8626                        }
 8627
 8628                        let prefix_range = full_comment_prefixes
 8629                            .iter()
 8630                            .zip(prefix_trimmed_lengths.iter().copied())
 8631                            .map(|(prefix, trimmed_prefix_len)| {
 8632                                comment_prefix_range(
 8633                                    snapshot.deref(),
 8634                                    row,
 8635                                    &prefix[..trimmed_prefix_len],
 8636                                    &prefix[trimmed_prefix_len..],
 8637                                    ignore_indent,
 8638                                )
 8639                            })
 8640                            .max_by_key(|range| range.end.column - range.start.column)
 8641                            .expect("prefixes is non-empty");
 8642
 8643                        if prefix_range.is_empty() {
 8644                            all_selection_lines_are_comments = false;
 8645                        }
 8646
 8647                        selection_edit_ranges.push(prefix_range);
 8648                    }
 8649
 8650                    if all_selection_lines_are_comments {
 8651                        edits.extend(
 8652                            selection_edit_ranges
 8653                                .iter()
 8654                                .cloned()
 8655                                .map(|range| (range, empty_str.clone())),
 8656                        );
 8657                    } else {
 8658                        let min_column = selection_edit_ranges
 8659                            .iter()
 8660                            .map(|range| range.start.column)
 8661                            .min()
 8662                            .unwrap_or(0);
 8663                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8664                            let position = Point::new(range.start.row, min_column);
 8665                            (position..position, first_prefix.clone())
 8666                        }));
 8667                    }
 8668                } else if let Some((full_comment_prefix, comment_suffix)) =
 8669                    language.block_comment_delimiters()
 8670                {
 8671                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8672                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8673                    let prefix_range = comment_prefix_range(
 8674                        snapshot.deref(),
 8675                        start_row,
 8676                        comment_prefix,
 8677                        comment_prefix_whitespace,
 8678                        ignore_indent,
 8679                    );
 8680                    let suffix_range = comment_suffix_range(
 8681                        snapshot.deref(),
 8682                        end_row,
 8683                        comment_suffix.trim_start_matches(' '),
 8684                        comment_suffix.starts_with(' '),
 8685                    );
 8686
 8687                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8688                        edits.push((
 8689                            prefix_range.start..prefix_range.start,
 8690                            full_comment_prefix.clone(),
 8691                        ));
 8692                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8693                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8694                    } else {
 8695                        edits.push((prefix_range, empty_str.clone()));
 8696                        edits.push((suffix_range, empty_str.clone()));
 8697                    }
 8698                } else {
 8699                    continue;
 8700                }
 8701            }
 8702
 8703            drop(snapshot);
 8704            this.buffer.update(cx, |buffer, cx| {
 8705                buffer.edit(edits, None, cx);
 8706            });
 8707
 8708            // Adjust selections so that they end before any comment suffixes that
 8709            // were inserted.
 8710            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8711            let mut selections = this.selections.all::<Point>(cx);
 8712            let snapshot = this.buffer.read(cx).read(cx);
 8713            for selection in &mut selections {
 8714                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8715                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8716                        Ordering::Less => {
 8717                            suffixes_inserted.next();
 8718                            continue;
 8719                        }
 8720                        Ordering::Greater => break,
 8721                        Ordering::Equal => {
 8722                            if selection.end.column == snapshot.line_len(row) {
 8723                                if selection.is_empty() {
 8724                                    selection.start.column -= suffix_len as u32;
 8725                                }
 8726                                selection.end.column -= suffix_len as u32;
 8727                            }
 8728                            break;
 8729                        }
 8730                    }
 8731                }
 8732            }
 8733
 8734            drop(snapshot);
 8735            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8736
 8737            let selections = this.selections.all::<Point>(cx);
 8738            let selections_on_single_row = selections.windows(2).all(|selections| {
 8739                selections[0].start.row == selections[1].start.row
 8740                    && selections[0].end.row == selections[1].end.row
 8741                    && selections[0].start.row == selections[0].end.row
 8742            });
 8743            let selections_selecting = selections
 8744                .iter()
 8745                .any(|selection| selection.start != selection.end);
 8746            let advance_downwards = action.advance_downwards
 8747                && selections_on_single_row
 8748                && !selections_selecting
 8749                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8750
 8751            if advance_downwards {
 8752                let snapshot = this.buffer.read(cx).snapshot(cx);
 8753
 8754                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8755                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8756                        let mut point = display_point.to_point(display_snapshot);
 8757                        point.row += 1;
 8758                        point = snapshot.clip_point(point, Bias::Left);
 8759                        let display_point = point.to_display_point(display_snapshot);
 8760                        let goal = SelectionGoal::HorizontalPosition(
 8761                            display_snapshot
 8762                                .x_for_display_point(display_point, text_layout_details)
 8763                                .into(),
 8764                        );
 8765                        (display_point, goal)
 8766                    })
 8767                });
 8768            }
 8769        });
 8770    }
 8771
 8772    pub fn select_enclosing_symbol(
 8773        &mut self,
 8774        _: &SelectEnclosingSymbol,
 8775        cx: &mut ViewContext<Self>,
 8776    ) {
 8777        let buffer = self.buffer.read(cx).snapshot(cx);
 8778        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8779
 8780        fn update_selection(
 8781            selection: &Selection<usize>,
 8782            buffer_snap: &MultiBufferSnapshot,
 8783        ) -> Option<Selection<usize>> {
 8784            let cursor = selection.head();
 8785            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8786            for symbol in symbols.iter().rev() {
 8787                let start = symbol.range.start.to_offset(buffer_snap);
 8788                let end = symbol.range.end.to_offset(buffer_snap);
 8789                let new_range = start..end;
 8790                if start < selection.start || end > selection.end {
 8791                    return Some(Selection {
 8792                        id: selection.id,
 8793                        start: new_range.start,
 8794                        end: new_range.end,
 8795                        goal: SelectionGoal::None,
 8796                        reversed: selection.reversed,
 8797                    });
 8798                }
 8799            }
 8800            None
 8801        }
 8802
 8803        let mut selected_larger_symbol = false;
 8804        let new_selections = old_selections
 8805            .iter()
 8806            .map(|selection| match update_selection(selection, &buffer) {
 8807                Some(new_selection) => {
 8808                    if new_selection.range() != selection.range() {
 8809                        selected_larger_symbol = true;
 8810                    }
 8811                    new_selection
 8812                }
 8813                None => selection.clone(),
 8814            })
 8815            .collect::<Vec<_>>();
 8816
 8817        if selected_larger_symbol {
 8818            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8819                s.select(new_selections);
 8820            });
 8821        }
 8822    }
 8823
 8824    pub fn select_larger_syntax_node(
 8825        &mut self,
 8826        _: &SelectLargerSyntaxNode,
 8827        cx: &mut ViewContext<Self>,
 8828    ) {
 8829        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8830        let buffer = self.buffer.read(cx).snapshot(cx);
 8831        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8832
 8833        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8834        let mut selected_larger_node = false;
 8835        let new_selections = old_selections
 8836            .iter()
 8837            .map(|selection| {
 8838                let old_range = selection.start..selection.end;
 8839                let mut new_range = old_range.clone();
 8840                let mut new_node = None;
 8841                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 8842                {
 8843                    new_node = Some(node);
 8844                    new_range = containing_range;
 8845                    if !display_map.intersects_fold(new_range.start)
 8846                        && !display_map.intersects_fold(new_range.end)
 8847                    {
 8848                        break;
 8849                    }
 8850                }
 8851
 8852                if let Some(node) = new_node {
 8853                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 8854                    // nodes. Parent and grandparent are also logged because this operation will not
 8855                    // visit nodes that have the same range as their parent.
 8856                    log::info!("Node: {node:?}");
 8857                    let parent = node.parent();
 8858                    log::info!("Parent: {parent:?}");
 8859                    let grandparent = parent.and_then(|x| x.parent());
 8860                    log::info!("Grandparent: {grandparent:?}");
 8861                }
 8862
 8863                selected_larger_node |= new_range != old_range;
 8864                Selection {
 8865                    id: selection.id,
 8866                    start: new_range.start,
 8867                    end: new_range.end,
 8868                    goal: SelectionGoal::None,
 8869                    reversed: selection.reversed,
 8870                }
 8871            })
 8872            .collect::<Vec<_>>();
 8873
 8874        if selected_larger_node {
 8875            stack.push(old_selections);
 8876            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8877                s.select(new_selections);
 8878            });
 8879        }
 8880        self.select_larger_syntax_node_stack = stack;
 8881    }
 8882
 8883    pub fn select_smaller_syntax_node(
 8884        &mut self,
 8885        _: &SelectSmallerSyntaxNode,
 8886        cx: &mut ViewContext<Self>,
 8887    ) {
 8888        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8889        if let Some(selections) = stack.pop() {
 8890            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8891                s.select(selections.to_vec());
 8892            });
 8893        }
 8894        self.select_larger_syntax_node_stack = stack;
 8895    }
 8896
 8897    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8898        if !EditorSettings::get_global(cx).gutter.runnables {
 8899            self.clear_tasks();
 8900            return Task::ready(());
 8901        }
 8902        let project = self.project.as_ref().map(Model::downgrade);
 8903        cx.spawn(|this, mut cx| async move {
 8904            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8905            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8906                return;
 8907            };
 8908            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8909                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8910            }) else {
 8911                return;
 8912            };
 8913
 8914            let hide_runnables = project
 8915                .update(&mut cx, |project, cx| {
 8916                    // Do not display any test indicators in non-dev server remote projects.
 8917                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8918                })
 8919                .unwrap_or(true);
 8920            if hide_runnables {
 8921                return;
 8922            }
 8923            let new_rows =
 8924                cx.background_executor()
 8925                    .spawn({
 8926                        let snapshot = display_snapshot.clone();
 8927                        async move {
 8928                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8929                        }
 8930                    })
 8931                    .await;
 8932            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8933
 8934            this.update(&mut cx, |this, _| {
 8935                this.clear_tasks();
 8936                for (key, value) in rows {
 8937                    this.insert_tasks(key, value);
 8938                }
 8939            })
 8940            .ok();
 8941        })
 8942    }
 8943    fn fetch_runnable_ranges(
 8944        snapshot: &DisplaySnapshot,
 8945        range: Range<Anchor>,
 8946    ) -> Vec<language::RunnableRange> {
 8947        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8948    }
 8949
 8950    fn runnable_rows(
 8951        project: Model<Project>,
 8952        snapshot: DisplaySnapshot,
 8953        runnable_ranges: Vec<RunnableRange>,
 8954        mut cx: AsyncWindowContext,
 8955    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8956        runnable_ranges
 8957            .into_iter()
 8958            .filter_map(|mut runnable| {
 8959                let tasks = cx
 8960                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8961                    .ok()?;
 8962                if tasks.is_empty() {
 8963                    return None;
 8964                }
 8965
 8966                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8967
 8968                let row = snapshot
 8969                    .buffer_snapshot
 8970                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8971                    .1
 8972                    .start
 8973                    .row;
 8974
 8975                let context_range =
 8976                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8977                Some((
 8978                    (runnable.buffer_id, row),
 8979                    RunnableTasks {
 8980                        templates: tasks,
 8981                        offset: MultiBufferOffset(runnable.run_range.start),
 8982                        context_range,
 8983                        column: point.column,
 8984                        extra_variables: runnable.extra_captures,
 8985                    },
 8986                ))
 8987            })
 8988            .collect()
 8989    }
 8990
 8991    fn templates_with_tags(
 8992        project: &Model<Project>,
 8993        runnable: &mut Runnable,
 8994        cx: &WindowContext,
 8995    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8996        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8997            let (worktree_id, file) = project
 8998                .buffer_for_id(runnable.buffer, cx)
 8999                .and_then(|buffer| buffer.read(cx).file())
 9000                .map(|file| (file.worktree_id(cx), file.clone()))
 9001                .unzip();
 9002
 9003            (
 9004                project.task_store().read(cx).task_inventory().cloned(),
 9005                worktree_id,
 9006                file,
 9007            )
 9008        });
 9009
 9010        let tags = mem::take(&mut runnable.tags);
 9011        let mut tags: Vec<_> = tags
 9012            .into_iter()
 9013            .flat_map(|tag| {
 9014                let tag = tag.0.clone();
 9015                inventory
 9016                    .as_ref()
 9017                    .into_iter()
 9018                    .flat_map(|inventory| {
 9019                        inventory.read(cx).list_tasks(
 9020                            file.clone(),
 9021                            Some(runnable.language.clone()),
 9022                            worktree_id,
 9023                            cx,
 9024                        )
 9025                    })
 9026                    .filter(move |(_, template)| {
 9027                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9028                    })
 9029            })
 9030            .sorted_by_key(|(kind, _)| kind.to_owned())
 9031            .collect();
 9032        if let Some((leading_tag_source, _)) = tags.first() {
 9033            // Strongest source wins; if we have worktree tag binding, prefer that to
 9034            // global and language bindings;
 9035            // if we have a global binding, prefer that to language binding.
 9036            let first_mismatch = tags
 9037                .iter()
 9038                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9039            if let Some(index) = first_mismatch {
 9040                tags.truncate(index);
 9041            }
 9042        }
 9043
 9044        tags
 9045    }
 9046
 9047    pub fn move_to_enclosing_bracket(
 9048        &mut self,
 9049        _: &MoveToEnclosingBracket,
 9050        cx: &mut ViewContext<Self>,
 9051    ) {
 9052        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9053            s.move_offsets_with(|snapshot, selection| {
 9054                let Some(enclosing_bracket_ranges) =
 9055                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9056                else {
 9057                    return;
 9058                };
 9059
 9060                let mut best_length = usize::MAX;
 9061                let mut best_inside = false;
 9062                let mut best_in_bracket_range = false;
 9063                let mut best_destination = None;
 9064                for (open, close) in enclosing_bracket_ranges {
 9065                    let close = close.to_inclusive();
 9066                    let length = close.end() - open.start;
 9067                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9068                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9069                        || close.contains(&selection.head());
 9070
 9071                    // If best is next to a bracket and current isn't, skip
 9072                    if !in_bracket_range && best_in_bracket_range {
 9073                        continue;
 9074                    }
 9075
 9076                    // Prefer smaller lengths unless best is inside and current isn't
 9077                    if length > best_length && (best_inside || !inside) {
 9078                        continue;
 9079                    }
 9080
 9081                    best_length = length;
 9082                    best_inside = inside;
 9083                    best_in_bracket_range = in_bracket_range;
 9084                    best_destination = Some(
 9085                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9086                            if inside {
 9087                                open.end
 9088                            } else {
 9089                                open.start
 9090                            }
 9091                        } else if inside {
 9092                            *close.start()
 9093                        } else {
 9094                            *close.end()
 9095                        },
 9096                    );
 9097                }
 9098
 9099                if let Some(destination) = best_destination {
 9100                    selection.collapse_to(destination, SelectionGoal::None);
 9101                }
 9102            })
 9103        });
 9104    }
 9105
 9106    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9107        self.end_selection(cx);
 9108        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9109        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9110            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9111            self.select_next_state = entry.select_next_state;
 9112            self.select_prev_state = entry.select_prev_state;
 9113            self.add_selections_state = entry.add_selections_state;
 9114            self.request_autoscroll(Autoscroll::newest(), cx);
 9115        }
 9116        self.selection_history.mode = SelectionHistoryMode::Normal;
 9117    }
 9118
 9119    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9120        self.end_selection(cx);
 9121        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9122        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9123            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9124            self.select_next_state = entry.select_next_state;
 9125            self.select_prev_state = entry.select_prev_state;
 9126            self.add_selections_state = entry.add_selections_state;
 9127            self.request_autoscroll(Autoscroll::newest(), cx);
 9128        }
 9129        self.selection_history.mode = SelectionHistoryMode::Normal;
 9130    }
 9131
 9132    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9133        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9134    }
 9135
 9136    pub fn expand_excerpts_down(
 9137        &mut self,
 9138        action: &ExpandExcerptsDown,
 9139        cx: &mut ViewContext<Self>,
 9140    ) {
 9141        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9142    }
 9143
 9144    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9145        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9146    }
 9147
 9148    pub fn expand_excerpts_for_direction(
 9149        &mut self,
 9150        lines: u32,
 9151        direction: ExpandExcerptDirection,
 9152        cx: &mut ViewContext<Self>,
 9153    ) {
 9154        let selections = self.selections.disjoint_anchors();
 9155
 9156        let lines = if lines == 0 {
 9157            EditorSettings::get_global(cx).expand_excerpt_lines
 9158        } else {
 9159            lines
 9160        };
 9161
 9162        self.buffer.update(cx, |buffer, cx| {
 9163            let snapshot = buffer.snapshot(cx);
 9164            let mut excerpt_ids = selections
 9165                .iter()
 9166                .flat_map(|selection| {
 9167                    snapshot
 9168                        .excerpts_for_range(selection.range())
 9169                        .map(|excerpt| excerpt.id())
 9170                })
 9171                .collect::<Vec<_>>();
 9172            excerpt_ids.sort();
 9173            excerpt_ids.dedup();
 9174            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9175        })
 9176    }
 9177
 9178    pub fn expand_excerpt(
 9179        &mut self,
 9180        excerpt: ExcerptId,
 9181        direction: ExpandExcerptDirection,
 9182        cx: &mut ViewContext<Self>,
 9183    ) {
 9184        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9185        self.buffer.update(cx, |buffer, cx| {
 9186            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9187        })
 9188    }
 9189
 9190    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9191        self.go_to_diagnostic_impl(Direction::Next, cx)
 9192    }
 9193
 9194    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9195        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9196    }
 9197
 9198    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9199        let buffer = self.buffer.read(cx).snapshot(cx);
 9200        let selection = self.selections.newest::<usize>(cx);
 9201
 9202        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9203        if direction == Direction::Next {
 9204            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9205                self.activate_diagnostics(popover.group_id(), cx);
 9206                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9207                    let primary_range_start = active_diagnostics.primary_range.start;
 9208                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9209                        let mut new_selection = s.newest_anchor().clone();
 9210                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9211                        s.select_anchors(vec![new_selection.clone()]);
 9212                    });
 9213                }
 9214                return;
 9215            }
 9216        }
 9217
 9218        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9219            active_diagnostics
 9220                .primary_range
 9221                .to_offset(&buffer)
 9222                .to_inclusive()
 9223        });
 9224        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9225            if active_primary_range.contains(&selection.head()) {
 9226                *active_primary_range.start()
 9227            } else {
 9228                selection.head()
 9229            }
 9230        } else {
 9231            selection.head()
 9232        };
 9233        let snapshot = self.snapshot(cx);
 9234        loop {
 9235            let diagnostics = if direction == Direction::Prev {
 9236                buffer
 9237                    .diagnostics_in_range(0..search_start, true)
 9238                    .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
 9239                        diagnostic,
 9240                        range: range.to_offset(&buffer),
 9241                    })
 9242                    .collect::<Vec<_>>()
 9243            } else {
 9244                buffer
 9245                    .diagnostics_in_range(search_start..buffer.len(), false)
 9246                    .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
 9247                        diagnostic,
 9248                        range: range.to_offset(&buffer),
 9249                    })
 9250                    .collect::<Vec<_>>()
 9251            }
 9252            .into_iter()
 9253            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9254            let group = diagnostics
 9255                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9256                // be sorted in a stable way
 9257                // skip until we are at current active diagnostic, if it exists
 9258                .skip_while(|entry| {
 9259                    (match direction {
 9260                        Direction::Prev => entry.range.start >= search_start,
 9261                        Direction::Next => entry.range.start <= search_start,
 9262                    }) && self
 9263                        .active_diagnostics
 9264                        .as_ref()
 9265                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9266                })
 9267                .find_map(|entry| {
 9268                    if entry.diagnostic.is_primary
 9269                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9270                        && !entry.range.is_empty()
 9271                        // if we match with the active diagnostic, skip it
 9272                        && Some(entry.diagnostic.group_id)
 9273                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9274                    {
 9275                        Some((entry.range, entry.diagnostic.group_id))
 9276                    } else {
 9277                        None
 9278                    }
 9279                });
 9280
 9281            if let Some((primary_range, group_id)) = group {
 9282                self.activate_diagnostics(group_id, cx);
 9283                if self.active_diagnostics.is_some() {
 9284                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9285                        s.select(vec![Selection {
 9286                            id: selection.id,
 9287                            start: primary_range.start,
 9288                            end: primary_range.start,
 9289                            reversed: false,
 9290                            goal: SelectionGoal::None,
 9291                        }]);
 9292                    });
 9293                }
 9294                break;
 9295            } else {
 9296                // Cycle around to the start of the buffer, potentially moving back to the start of
 9297                // the currently active diagnostic.
 9298                active_primary_range.take();
 9299                if direction == Direction::Prev {
 9300                    if search_start == buffer.len() {
 9301                        break;
 9302                    } else {
 9303                        search_start = buffer.len();
 9304                    }
 9305                } else if search_start == 0 {
 9306                    break;
 9307                } else {
 9308                    search_start = 0;
 9309                }
 9310            }
 9311        }
 9312    }
 9313
 9314    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9315        let snapshot = self.snapshot(cx);
 9316        let selection = self.selections.newest::<Point>(cx);
 9317        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9318    }
 9319
 9320    fn go_to_hunk_after_position(
 9321        &mut self,
 9322        snapshot: &EditorSnapshot,
 9323        position: Point,
 9324        cx: &mut ViewContext<Editor>,
 9325    ) -> Option<MultiBufferDiffHunk> {
 9326        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9327            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9328                snapshot,
 9329                position,
 9330                ix > 0,
 9331                snapshot.diff_map.diff_hunks_in_range(
 9332                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9333                    &snapshot.buffer_snapshot,
 9334                ),
 9335                cx,
 9336            ) {
 9337                return Some(hunk);
 9338            }
 9339        }
 9340        None
 9341    }
 9342
 9343    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9344        let snapshot = self.snapshot(cx);
 9345        let selection = self.selections.newest::<Point>(cx);
 9346        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9347    }
 9348
 9349    fn go_to_hunk_before_position(
 9350        &mut self,
 9351        snapshot: &EditorSnapshot,
 9352        position: Point,
 9353        cx: &mut ViewContext<Editor>,
 9354    ) -> Option<MultiBufferDiffHunk> {
 9355        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9356            .into_iter()
 9357            .enumerate()
 9358        {
 9359            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9360                snapshot,
 9361                position,
 9362                ix > 0,
 9363                snapshot
 9364                    .diff_map
 9365                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9366                cx,
 9367            ) {
 9368                return Some(hunk);
 9369            }
 9370        }
 9371        None
 9372    }
 9373
 9374    fn go_to_next_hunk_in_direction(
 9375        &mut self,
 9376        snapshot: &DisplaySnapshot,
 9377        initial_point: Point,
 9378        is_wrapped: bool,
 9379        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9380        cx: &mut ViewContext<Editor>,
 9381    ) -> Option<MultiBufferDiffHunk> {
 9382        let display_point = initial_point.to_display_point(snapshot);
 9383        let mut hunks = hunks
 9384            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9385            .filter(|(display_hunk, _)| {
 9386                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9387            })
 9388            .dedup();
 9389
 9390        if let Some((display_hunk, hunk)) = hunks.next() {
 9391            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9392                let row = display_hunk.start_display_row();
 9393                let point = DisplayPoint::new(row, 0);
 9394                s.select_display_ranges([point..point]);
 9395            });
 9396
 9397            Some(hunk)
 9398        } else {
 9399            None
 9400        }
 9401    }
 9402
 9403    pub fn go_to_definition(
 9404        &mut self,
 9405        _: &GoToDefinition,
 9406        cx: &mut ViewContext<Self>,
 9407    ) -> Task<Result<Navigated>> {
 9408        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9409        cx.spawn(|editor, mut cx| async move {
 9410            if definition.await? == Navigated::Yes {
 9411                return Ok(Navigated::Yes);
 9412            }
 9413            match editor.update(&mut cx, |editor, cx| {
 9414                editor.find_all_references(&FindAllReferences, cx)
 9415            })? {
 9416                Some(references) => references.await,
 9417                None => Ok(Navigated::No),
 9418            }
 9419        })
 9420    }
 9421
 9422    pub fn go_to_declaration(
 9423        &mut self,
 9424        _: &GoToDeclaration,
 9425        cx: &mut ViewContext<Self>,
 9426    ) -> Task<Result<Navigated>> {
 9427        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9428    }
 9429
 9430    pub fn go_to_declaration_split(
 9431        &mut self,
 9432        _: &GoToDeclaration,
 9433        cx: &mut ViewContext<Self>,
 9434    ) -> Task<Result<Navigated>> {
 9435        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9436    }
 9437
 9438    pub fn go_to_implementation(
 9439        &mut self,
 9440        _: &GoToImplementation,
 9441        cx: &mut ViewContext<Self>,
 9442    ) -> Task<Result<Navigated>> {
 9443        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9444    }
 9445
 9446    pub fn go_to_implementation_split(
 9447        &mut self,
 9448        _: &GoToImplementationSplit,
 9449        cx: &mut ViewContext<Self>,
 9450    ) -> Task<Result<Navigated>> {
 9451        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9452    }
 9453
 9454    pub fn go_to_type_definition(
 9455        &mut self,
 9456        _: &GoToTypeDefinition,
 9457        cx: &mut ViewContext<Self>,
 9458    ) -> Task<Result<Navigated>> {
 9459        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9460    }
 9461
 9462    pub fn go_to_definition_split(
 9463        &mut self,
 9464        _: &GoToDefinitionSplit,
 9465        cx: &mut ViewContext<Self>,
 9466    ) -> Task<Result<Navigated>> {
 9467        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9468    }
 9469
 9470    pub fn go_to_type_definition_split(
 9471        &mut self,
 9472        _: &GoToTypeDefinitionSplit,
 9473        cx: &mut ViewContext<Self>,
 9474    ) -> Task<Result<Navigated>> {
 9475        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9476    }
 9477
 9478    fn go_to_definition_of_kind(
 9479        &mut self,
 9480        kind: GotoDefinitionKind,
 9481        split: bool,
 9482        cx: &mut ViewContext<Self>,
 9483    ) -> Task<Result<Navigated>> {
 9484        let Some(provider) = self.semantics_provider.clone() else {
 9485            return Task::ready(Ok(Navigated::No));
 9486        };
 9487        let head = self.selections.newest::<usize>(cx).head();
 9488        let buffer = self.buffer.read(cx);
 9489        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9490            text_anchor
 9491        } else {
 9492            return Task::ready(Ok(Navigated::No));
 9493        };
 9494
 9495        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9496            return Task::ready(Ok(Navigated::No));
 9497        };
 9498
 9499        cx.spawn(|editor, mut cx| async move {
 9500            let definitions = definitions.await?;
 9501            let navigated = editor
 9502                .update(&mut cx, |editor, cx| {
 9503                    editor.navigate_to_hover_links(
 9504                        Some(kind),
 9505                        definitions
 9506                            .into_iter()
 9507                            .filter(|location| {
 9508                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9509                            })
 9510                            .map(HoverLink::Text)
 9511                            .collect::<Vec<_>>(),
 9512                        split,
 9513                        cx,
 9514                    )
 9515                })?
 9516                .await?;
 9517            anyhow::Ok(navigated)
 9518        })
 9519    }
 9520
 9521    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9522        let selection = self.selections.newest_anchor();
 9523        let head = selection.head();
 9524        let tail = selection.tail();
 9525
 9526        let Some((buffer, start_position)) =
 9527            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9528        else {
 9529            return;
 9530        };
 9531
 9532        let end_position = if head != tail {
 9533            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9534                return;
 9535            };
 9536            Some(pos)
 9537        } else {
 9538            None
 9539        };
 9540
 9541        let url_finder = cx.spawn(|editor, mut cx| async move {
 9542            let url = if let Some(end_pos) = end_position {
 9543                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9544            } else {
 9545                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9546            };
 9547
 9548            if let Some(url) = url {
 9549                editor.update(&mut cx, |_, cx| {
 9550                    cx.open_url(&url);
 9551                })
 9552            } else {
 9553                Ok(())
 9554            }
 9555        });
 9556
 9557        url_finder.detach();
 9558    }
 9559
 9560    pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
 9561        let Some(workspace) = self.workspace() else {
 9562            return;
 9563        };
 9564
 9565        let position = self.selections.newest_anchor().head();
 9566
 9567        let Some((buffer, buffer_position)) =
 9568            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9569        else {
 9570            return;
 9571        };
 9572
 9573        let project = self.project.clone();
 9574
 9575        cx.spawn(|_, mut cx| async move {
 9576            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9577
 9578            if let Some((_, path)) = result {
 9579                workspace
 9580                    .update(&mut cx, |workspace, cx| {
 9581                        workspace.open_resolved_path(path, cx)
 9582                    })?
 9583                    .await?;
 9584            }
 9585            anyhow::Ok(())
 9586        })
 9587        .detach();
 9588    }
 9589
 9590    pub(crate) fn navigate_to_hover_links(
 9591        &mut self,
 9592        kind: Option<GotoDefinitionKind>,
 9593        mut definitions: Vec<HoverLink>,
 9594        split: bool,
 9595        cx: &mut ViewContext<Editor>,
 9596    ) -> Task<Result<Navigated>> {
 9597        // If there is one definition, just open it directly
 9598        if definitions.len() == 1 {
 9599            let definition = definitions.pop().unwrap();
 9600
 9601            enum TargetTaskResult {
 9602                Location(Option<Location>),
 9603                AlreadyNavigated,
 9604            }
 9605
 9606            let target_task = match definition {
 9607                HoverLink::Text(link) => {
 9608                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9609                }
 9610                HoverLink::InlayHint(lsp_location, server_id) => {
 9611                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9612                    cx.background_executor().spawn(async move {
 9613                        let location = computation.await?;
 9614                        Ok(TargetTaskResult::Location(location))
 9615                    })
 9616                }
 9617                HoverLink::Url(url) => {
 9618                    cx.open_url(&url);
 9619                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9620                }
 9621                HoverLink::File(path) => {
 9622                    if let Some(workspace) = self.workspace() {
 9623                        cx.spawn(|_, mut cx| async move {
 9624                            workspace
 9625                                .update(&mut cx, |workspace, cx| {
 9626                                    workspace.open_resolved_path(path, cx)
 9627                                })?
 9628                                .await
 9629                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9630                        })
 9631                    } else {
 9632                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9633                    }
 9634                }
 9635            };
 9636            cx.spawn(|editor, mut cx| async move {
 9637                let target = match target_task.await.context("target resolution task")? {
 9638                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9639                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9640                    TargetTaskResult::Location(Some(target)) => target,
 9641                };
 9642
 9643                editor.update(&mut cx, |editor, cx| {
 9644                    let Some(workspace) = editor.workspace() else {
 9645                        return Navigated::No;
 9646                    };
 9647                    let pane = workspace.read(cx).active_pane().clone();
 9648
 9649                    let range = target.range.to_offset(target.buffer.read(cx));
 9650                    let range = editor.range_for_match(&range);
 9651
 9652                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9653                        let buffer = target.buffer.read(cx);
 9654                        let range = check_multiline_range(buffer, range);
 9655                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9656                            s.select_ranges([range]);
 9657                        });
 9658                    } else {
 9659                        cx.window_context().defer(move |cx| {
 9660                            let target_editor: View<Self> =
 9661                                workspace.update(cx, |workspace, cx| {
 9662                                    let pane = if split {
 9663                                        workspace.adjacent_pane(cx)
 9664                                    } else {
 9665                                        workspace.active_pane().clone()
 9666                                    };
 9667
 9668                                    workspace.open_project_item(
 9669                                        pane,
 9670                                        target.buffer.clone(),
 9671                                        true,
 9672                                        true,
 9673                                        cx,
 9674                                    )
 9675                                });
 9676                            target_editor.update(cx, |target_editor, cx| {
 9677                                // When selecting a definition in a different buffer, disable the nav history
 9678                                // to avoid creating a history entry at the previous cursor location.
 9679                                pane.update(cx, |pane, _| pane.disable_history());
 9680                                let buffer = target.buffer.read(cx);
 9681                                let range = check_multiline_range(buffer, range);
 9682                                target_editor.change_selections(
 9683                                    Some(Autoscroll::focused()),
 9684                                    cx,
 9685                                    |s| {
 9686                                        s.select_ranges([range]);
 9687                                    },
 9688                                );
 9689                                pane.update(cx, |pane, _| pane.enable_history());
 9690                            });
 9691                        });
 9692                    }
 9693                    Navigated::Yes
 9694                })
 9695            })
 9696        } else if !definitions.is_empty() {
 9697            cx.spawn(|editor, mut cx| async move {
 9698                let (title, location_tasks, workspace) = editor
 9699                    .update(&mut cx, |editor, cx| {
 9700                        let tab_kind = match kind {
 9701                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9702                            _ => "Definitions",
 9703                        };
 9704                        let title = definitions
 9705                            .iter()
 9706                            .find_map(|definition| match definition {
 9707                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9708                                    let buffer = origin.buffer.read(cx);
 9709                                    format!(
 9710                                        "{} for {}",
 9711                                        tab_kind,
 9712                                        buffer
 9713                                            .text_for_range(origin.range.clone())
 9714                                            .collect::<String>()
 9715                                    )
 9716                                }),
 9717                                HoverLink::InlayHint(_, _) => None,
 9718                                HoverLink::Url(_) => None,
 9719                                HoverLink::File(_) => None,
 9720                            })
 9721                            .unwrap_or(tab_kind.to_string());
 9722                        let location_tasks = definitions
 9723                            .into_iter()
 9724                            .map(|definition| match definition {
 9725                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9726                                HoverLink::InlayHint(lsp_location, server_id) => {
 9727                                    editor.compute_target_location(lsp_location, server_id, cx)
 9728                                }
 9729                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9730                                HoverLink::File(_) => Task::ready(Ok(None)),
 9731                            })
 9732                            .collect::<Vec<_>>();
 9733                        (title, location_tasks, editor.workspace().clone())
 9734                    })
 9735                    .context("location tasks preparation")?;
 9736
 9737                let locations = future::join_all(location_tasks)
 9738                    .await
 9739                    .into_iter()
 9740                    .filter_map(|location| location.transpose())
 9741                    .collect::<Result<_>>()
 9742                    .context("location tasks")?;
 9743
 9744                let Some(workspace) = workspace else {
 9745                    return Ok(Navigated::No);
 9746                };
 9747                let opened = workspace
 9748                    .update(&mut cx, |workspace, cx| {
 9749                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9750                    })
 9751                    .ok();
 9752
 9753                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9754            })
 9755        } else {
 9756            Task::ready(Ok(Navigated::No))
 9757        }
 9758    }
 9759
 9760    fn compute_target_location(
 9761        &self,
 9762        lsp_location: lsp::Location,
 9763        server_id: LanguageServerId,
 9764        cx: &mut ViewContext<Self>,
 9765    ) -> Task<anyhow::Result<Option<Location>>> {
 9766        let Some(project) = self.project.clone() else {
 9767            return Task::ready(Ok(None));
 9768        };
 9769
 9770        cx.spawn(move |editor, mut cx| async move {
 9771            let location_task = editor.update(&mut cx, |_, cx| {
 9772                project.update(cx, |project, cx| {
 9773                    let language_server_name = project
 9774                        .language_server_statuses(cx)
 9775                        .find(|(id, _)| server_id == *id)
 9776                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9777                    language_server_name.map(|language_server_name| {
 9778                        project.open_local_buffer_via_lsp(
 9779                            lsp_location.uri.clone(),
 9780                            server_id,
 9781                            language_server_name,
 9782                            cx,
 9783                        )
 9784                    })
 9785                })
 9786            })?;
 9787            let location = match location_task {
 9788                Some(task) => Some({
 9789                    let target_buffer_handle = task.await.context("open local buffer")?;
 9790                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9791                        let target_start = target_buffer
 9792                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9793                        let target_end = target_buffer
 9794                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9795                        target_buffer.anchor_after(target_start)
 9796                            ..target_buffer.anchor_before(target_end)
 9797                    })?;
 9798                    Location {
 9799                        buffer: target_buffer_handle,
 9800                        range,
 9801                    }
 9802                }),
 9803                None => None,
 9804            };
 9805            Ok(location)
 9806        })
 9807    }
 9808
 9809    pub fn find_all_references(
 9810        &mut self,
 9811        _: &FindAllReferences,
 9812        cx: &mut ViewContext<Self>,
 9813    ) -> Option<Task<Result<Navigated>>> {
 9814        let selection = self.selections.newest::<usize>(cx);
 9815        let multi_buffer = self.buffer.read(cx);
 9816        let head = selection.head();
 9817
 9818        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9819        let head_anchor = multi_buffer_snapshot.anchor_at(
 9820            head,
 9821            if head < selection.tail() {
 9822                Bias::Right
 9823            } else {
 9824                Bias::Left
 9825            },
 9826        );
 9827
 9828        match self
 9829            .find_all_references_task_sources
 9830            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9831        {
 9832            Ok(_) => {
 9833                log::info!(
 9834                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9835                );
 9836                return None;
 9837            }
 9838            Err(i) => {
 9839                self.find_all_references_task_sources.insert(i, head_anchor);
 9840            }
 9841        }
 9842
 9843        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9844        let workspace = self.workspace()?;
 9845        let project = workspace.read(cx).project().clone();
 9846        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9847        Some(cx.spawn(|editor, mut cx| async move {
 9848            let _cleanup = defer({
 9849                let mut cx = cx.clone();
 9850                move || {
 9851                    let _ = editor.update(&mut cx, |editor, _| {
 9852                        if let Ok(i) =
 9853                            editor
 9854                                .find_all_references_task_sources
 9855                                .binary_search_by(|anchor| {
 9856                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9857                                })
 9858                        {
 9859                            editor.find_all_references_task_sources.remove(i);
 9860                        }
 9861                    });
 9862                }
 9863            });
 9864
 9865            let locations = references.await?;
 9866            if locations.is_empty() {
 9867                return anyhow::Ok(Navigated::No);
 9868            }
 9869
 9870            workspace.update(&mut cx, |workspace, cx| {
 9871                let title = locations
 9872                    .first()
 9873                    .as_ref()
 9874                    .map(|location| {
 9875                        let buffer = location.buffer.read(cx);
 9876                        format!(
 9877                            "References to `{}`",
 9878                            buffer
 9879                                .text_for_range(location.range.clone())
 9880                                .collect::<String>()
 9881                        )
 9882                    })
 9883                    .unwrap();
 9884                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9885                Navigated::Yes
 9886            })
 9887        }))
 9888    }
 9889
 9890    /// Opens a multibuffer with the given project locations in it
 9891    pub fn open_locations_in_multibuffer(
 9892        workspace: &mut Workspace,
 9893        mut locations: Vec<Location>,
 9894        title: String,
 9895        split: bool,
 9896        cx: &mut ViewContext<Workspace>,
 9897    ) {
 9898        // If there are multiple definitions, open them in a multibuffer
 9899        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9900        let mut locations = locations.into_iter().peekable();
 9901        let mut ranges_to_highlight = Vec::new();
 9902        let capability = workspace.project().read(cx).capability();
 9903
 9904        let excerpt_buffer = cx.new_model(|cx| {
 9905            let mut multibuffer = MultiBuffer::new(capability);
 9906            while let Some(location) = locations.next() {
 9907                let buffer = location.buffer.read(cx);
 9908                let mut ranges_for_buffer = Vec::new();
 9909                let range = location.range.to_offset(buffer);
 9910                ranges_for_buffer.push(range.clone());
 9911
 9912                while let Some(next_location) = locations.peek() {
 9913                    if next_location.buffer == location.buffer {
 9914                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9915                        locations.next();
 9916                    } else {
 9917                        break;
 9918                    }
 9919                }
 9920
 9921                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9922                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9923                    location.buffer.clone(),
 9924                    ranges_for_buffer,
 9925                    DEFAULT_MULTIBUFFER_CONTEXT,
 9926                    cx,
 9927                ))
 9928            }
 9929
 9930            multibuffer.with_title(title)
 9931        });
 9932
 9933        let editor = cx.new_view(|cx| {
 9934            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9935        });
 9936        editor.update(cx, |editor, cx| {
 9937            if let Some(first_range) = ranges_to_highlight.first() {
 9938                editor.change_selections(None, cx, |selections| {
 9939                    selections.clear_disjoint();
 9940                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9941                });
 9942            }
 9943            editor.highlight_background::<Self>(
 9944                &ranges_to_highlight,
 9945                |theme| theme.editor_highlighted_line_background,
 9946                cx,
 9947            );
 9948            editor.register_buffers_with_language_servers(cx);
 9949        });
 9950
 9951        let item = Box::new(editor);
 9952        let item_id = item.item_id();
 9953
 9954        if split {
 9955            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9956        } else {
 9957            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9958                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9959                    pane.close_current_preview_item(cx)
 9960                } else {
 9961                    None
 9962                }
 9963            });
 9964            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9965        }
 9966        workspace.active_pane().update(cx, |pane, cx| {
 9967            pane.set_preview_item_id(Some(item_id), cx);
 9968        });
 9969    }
 9970
 9971    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9972        use language::ToOffset as _;
 9973
 9974        let provider = self.semantics_provider.clone()?;
 9975        let selection = self.selections.newest_anchor().clone();
 9976        let (cursor_buffer, cursor_buffer_position) = self
 9977            .buffer
 9978            .read(cx)
 9979            .text_anchor_for_position(selection.head(), cx)?;
 9980        let (tail_buffer, cursor_buffer_position_end) = self
 9981            .buffer
 9982            .read(cx)
 9983            .text_anchor_for_position(selection.tail(), cx)?;
 9984        if tail_buffer != cursor_buffer {
 9985            return None;
 9986        }
 9987
 9988        let snapshot = cursor_buffer.read(cx).snapshot();
 9989        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9990        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9991        let prepare_rename = provider
 9992            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9993            .unwrap_or_else(|| Task::ready(Ok(None)));
 9994        drop(snapshot);
 9995
 9996        Some(cx.spawn(|this, mut cx| async move {
 9997            let rename_range = if let Some(range) = prepare_rename.await? {
 9998                Some(range)
 9999            } else {
10000                this.update(&mut cx, |this, cx| {
10001                    let buffer = this.buffer.read(cx).snapshot(cx);
10002                    let mut buffer_highlights = this
10003                        .document_highlights_for_position(selection.head(), &buffer)
10004                        .filter(|highlight| {
10005                            highlight.start.excerpt_id == selection.head().excerpt_id
10006                                && highlight.end.excerpt_id == selection.head().excerpt_id
10007                        });
10008                    buffer_highlights
10009                        .next()
10010                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10011                })?
10012            };
10013            if let Some(rename_range) = rename_range {
10014                this.update(&mut cx, |this, cx| {
10015                    let snapshot = cursor_buffer.read(cx).snapshot();
10016                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10017                    let cursor_offset_in_rename_range =
10018                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10019                    let cursor_offset_in_rename_range_end =
10020                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10021
10022                    this.take_rename(false, cx);
10023                    let buffer = this.buffer.read(cx).read(cx);
10024                    let cursor_offset = selection.head().to_offset(&buffer);
10025                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10026                    let rename_end = rename_start + rename_buffer_range.len();
10027                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10028                    let mut old_highlight_id = None;
10029                    let old_name: Arc<str> = buffer
10030                        .chunks(rename_start..rename_end, true)
10031                        .map(|chunk| {
10032                            if old_highlight_id.is_none() {
10033                                old_highlight_id = chunk.syntax_highlight_id;
10034                            }
10035                            chunk.text
10036                        })
10037                        .collect::<String>()
10038                        .into();
10039
10040                    drop(buffer);
10041
10042                    // Position the selection in the rename editor so that it matches the current selection.
10043                    this.show_local_selections = false;
10044                    let rename_editor = cx.new_view(|cx| {
10045                        let mut editor = Editor::single_line(cx);
10046                        editor.buffer.update(cx, |buffer, cx| {
10047                            buffer.edit([(0..0, old_name.clone())], None, cx)
10048                        });
10049                        let rename_selection_range = match cursor_offset_in_rename_range
10050                            .cmp(&cursor_offset_in_rename_range_end)
10051                        {
10052                            Ordering::Equal => {
10053                                editor.select_all(&SelectAll, cx);
10054                                return editor;
10055                            }
10056                            Ordering::Less => {
10057                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10058                            }
10059                            Ordering::Greater => {
10060                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10061                            }
10062                        };
10063                        if rename_selection_range.end > old_name.len() {
10064                            editor.select_all(&SelectAll, cx);
10065                        } else {
10066                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10067                                s.select_ranges([rename_selection_range]);
10068                            });
10069                        }
10070                        editor
10071                    });
10072                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10073                        if e == &EditorEvent::Focused {
10074                            cx.emit(EditorEvent::FocusedIn)
10075                        }
10076                    })
10077                    .detach();
10078
10079                    let write_highlights =
10080                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10081                    let read_highlights =
10082                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10083                    let ranges = write_highlights
10084                        .iter()
10085                        .flat_map(|(_, ranges)| ranges.iter())
10086                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10087                        .cloned()
10088                        .collect();
10089
10090                    this.highlight_text::<Rename>(
10091                        ranges,
10092                        HighlightStyle {
10093                            fade_out: Some(0.6),
10094                            ..Default::default()
10095                        },
10096                        cx,
10097                    );
10098                    let rename_focus_handle = rename_editor.focus_handle(cx);
10099                    cx.focus(&rename_focus_handle);
10100                    let block_id = this.insert_blocks(
10101                        [BlockProperties {
10102                            style: BlockStyle::Flex,
10103                            placement: BlockPlacement::Below(range.start),
10104                            height: 1,
10105                            render: Arc::new({
10106                                let rename_editor = rename_editor.clone();
10107                                move |cx: &mut BlockContext| {
10108                                    let mut text_style = cx.editor_style.text.clone();
10109                                    if let Some(highlight_style) = old_highlight_id
10110                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10111                                    {
10112                                        text_style = text_style.highlight(highlight_style);
10113                                    }
10114                                    div()
10115                                        .block_mouse_down()
10116                                        .pl(cx.anchor_x)
10117                                        .child(EditorElement::new(
10118                                            &rename_editor,
10119                                            EditorStyle {
10120                                                background: cx.theme().system().transparent,
10121                                                local_player: cx.editor_style.local_player,
10122                                                text: text_style,
10123                                                scrollbar_width: cx.editor_style.scrollbar_width,
10124                                                syntax: cx.editor_style.syntax.clone(),
10125                                                status: cx.editor_style.status.clone(),
10126                                                inlay_hints_style: HighlightStyle {
10127                                                    font_weight: Some(FontWeight::BOLD),
10128                                                    ..make_inlay_hints_style(cx)
10129                                                },
10130                                                inline_completion_styles: make_suggestion_styles(
10131                                                    cx,
10132                                                ),
10133                                                ..EditorStyle::default()
10134                                            },
10135                                        ))
10136                                        .into_any_element()
10137                                }
10138                            }),
10139                            priority: 0,
10140                        }],
10141                        Some(Autoscroll::fit()),
10142                        cx,
10143                    )[0];
10144                    this.pending_rename = Some(RenameState {
10145                        range,
10146                        old_name,
10147                        editor: rename_editor,
10148                        block_id,
10149                    });
10150                })?;
10151            }
10152
10153            Ok(())
10154        }))
10155    }
10156
10157    pub fn confirm_rename(
10158        &mut self,
10159        _: &ConfirmRename,
10160        cx: &mut ViewContext<Self>,
10161    ) -> Option<Task<Result<()>>> {
10162        let rename = self.take_rename(false, cx)?;
10163        let workspace = self.workspace()?.downgrade();
10164        let (buffer, start) = self
10165            .buffer
10166            .read(cx)
10167            .text_anchor_for_position(rename.range.start, cx)?;
10168        let (end_buffer, _) = self
10169            .buffer
10170            .read(cx)
10171            .text_anchor_for_position(rename.range.end, cx)?;
10172        if buffer != end_buffer {
10173            return None;
10174        }
10175
10176        let old_name = rename.old_name;
10177        let new_name = rename.editor.read(cx).text(cx);
10178
10179        let rename = self.semantics_provider.as_ref()?.perform_rename(
10180            &buffer,
10181            start,
10182            new_name.clone(),
10183            cx,
10184        )?;
10185
10186        Some(cx.spawn(|editor, mut cx| async move {
10187            let project_transaction = rename.await?;
10188            Self::open_project_transaction(
10189                &editor,
10190                workspace,
10191                project_transaction,
10192                format!("Rename: {}{}", old_name, new_name),
10193                cx.clone(),
10194            )
10195            .await?;
10196
10197            editor.update(&mut cx, |editor, cx| {
10198                editor.refresh_document_highlights(cx);
10199            })?;
10200            Ok(())
10201        }))
10202    }
10203
10204    fn take_rename(
10205        &mut self,
10206        moving_cursor: bool,
10207        cx: &mut ViewContext<Self>,
10208    ) -> Option<RenameState> {
10209        let rename = self.pending_rename.take()?;
10210        if rename.editor.focus_handle(cx).is_focused(cx) {
10211            cx.focus(&self.focus_handle);
10212        }
10213
10214        self.remove_blocks(
10215            [rename.block_id].into_iter().collect(),
10216            Some(Autoscroll::fit()),
10217            cx,
10218        );
10219        self.clear_highlights::<Rename>(cx);
10220        self.show_local_selections = true;
10221
10222        if moving_cursor {
10223            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10224                editor.selections.newest::<usize>(cx).head()
10225            });
10226
10227            // Update the selection to match the position of the selection inside
10228            // the rename editor.
10229            let snapshot = self.buffer.read(cx).read(cx);
10230            let rename_range = rename.range.to_offset(&snapshot);
10231            let cursor_in_editor = snapshot
10232                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10233                .min(rename_range.end);
10234            drop(snapshot);
10235
10236            self.change_selections(None, cx, |s| {
10237                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10238            });
10239        } else {
10240            self.refresh_document_highlights(cx);
10241        }
10242
10243        Some(rename)
10244    }
10245
10246    pub fn pending_rename(&self) -> Option<&RenameState> {
10247        self.pending_rename.as_ref()
10248    }
10249
10250    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10251        let project = match &self.project {
10252            Some(project) => project.clone(),
10253            None => return None,
10254        };
10255
10256        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10257    }
10258
10259    fn format_selections(
10260        &mut self,
10261        _: &FormatSelections,
10262        cx: &mut ViewContext<Self>,
10263    ) -> Option<Task<Result<()>>> {
10264        let project = match &self.project {
10265            Some(project) => project.clone(),
10266            None => return None,
10267        };
10268
10269        let ranges = self
10270            .selections
10271            .all_adjusted(cx)
10272            .into_iter()
10273            .map(|selection| selection.range())
10274            .collect_vec();
10275
10276        Some(self.perform_format(
10277            project,
10278            FormatTrigger::Manual,
10279            FormatTarget::Ranges(ranges),
10280            cx,
10281        ))
10282    }
10283
10284    fn perform_format(
10285        &mut self,
10286        project: Model<Project>,
10287        trigger: FormatTrigger,
10288        target: FormatTarget,
10289        cx: &mut ViewContext<Self>,
10290    ) -> Task<Result<()>> {
10291        let buffer = self.buffer.clone();
10292        let (buffers, target) = match target {
10293            FormatTarget::Buffers => {
10294                let mut buffers = buffer.read(cx).all_buffers();
10295                if trigger == FormatTrigger::Save {
10296                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
10297                }
10298                (buffers, LspFormatTarget::Buffers)
10299            }
10300            FormatTarget::Ranges(selection_ranges) => {
10301                let multi_buffer = buffer.read(cx);
10302                let snapshot = multi_buffer.read(cx);
10303                let mut buffers = HashSet::default();
10304                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10305                    BTreeMap::new();
10306                for selection_range in selection_ranges {
10307                    for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10308                    {
10309                        let buffer_id = excerpt.buffer_id();
10310                        let start = excerpt.buffer().anchor_before(buffer_range.start);
10311                        let end = excerpt.buffer().anchor_after(buffer_range.end);
10312                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10313                        buffer_id_to_ranges
10314                            .entry(buffer_id)
10315                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10316                            .or_insert_with(|| vec![start..end]);
10317                    }
10318                }
10319                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10320            }
10321        };
10322
10323        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10324        let format = project.update(cx, |project, cx| {
10325            project.format(buffers, target, true, trigger, cx)
10326        });
10327
10328        cx.spawn(|_, mut cx| async move {
10329            let transaction = futures::select_biased! {
10330                () = timeout => {
10331                    log::warn!("timed out waiting for formatting");
10332                    None
10333                }
10334                transaction = format.log_err().fuse() => transaction,
10335            };
10336
10337            buffer
10338                .update(&mut cx, |buffer, cx| {
10339                    if let Some(transaction) = transaction {
10340                        if !buffer.is_singleton() {
10341                            buffer.push_transaction(&transaction.0, cx);
10342                        }
10343                    }
10344
10345                    cx.notify();
10346                })
10347                .ok();
10348
10349            Ok(())
10350        })
10351    }
10352
10353    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10354        if let Some(project) = self.project.clone() {
10355            self.buffer.update(cx, |multi_buffer, cx| {
10356                project.update(cx, |project, cx| {
10357                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10358                });
10359            })
10360        }
10361    }
10362
10363    fn cancel_language_server_work(
10364        &mut self,
10365        _: &actions::CancelLanguageServerWork,
10366        cx: &mut ViewContext<Self>,
10367    ) {
10368        if let Some(project) = self.project.clone() {
10369            self.buffer.update(cx, |multi_buffer, cx| {
10370                project.update(cx, |project, cx| {
10371                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10372                });
10373            })
10374        }
10375    }
10376
10377    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10378        cx.show_character_palette();
10379    }
10380
10381    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10382        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10383            let buffer = self.buffer.read(cx).snapshot(cx);
10384            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10385            let is_valid = buffer
10386                .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10387                .any(|entry| {
10388                    let range = entry.range.to_offset(&buffer);
10389                    entry.diagnostic.is_primary
10390                        && !range.is_empty()
10391                        && range.start == primary_range_start
10392                        && entry.diagnostic.message == active_diagnostics.primary_message
10393                });
10394
10395            if is_valid != active_diagnostics.is_valid {
10396                active_diagnostics.is_valid = is_valid;
10397                let mut new_styles = HashMap::default();
10398                for (block_id, diagnostic) in &active_diagnostics.blocks {
10399                    new_styles.insert(
10400                        *block_id,
10401                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10402                    );
10403                }
10404                self.display_map.update(cx, |display_map, _cx| {
10405                    display_map.replace_blocks(new_styles)
10406                });
10407            }
10408        }
10409    }
10410
10411    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10412        self.dismiss_diagnostics(cx);
10413        let snapshot = self.snapshot(cx);
10414        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10415            let buffer = self.buffer.read(cx).snapshot(cx);
10416
10417            let mut primary_range = None;
10418            let mut primary_message = None;
10419            let mut group_end = Point::zero();
10420            let diagnostic_group = buffer
10421                .diagnostic_group(group_id)
10422                .filter_map(|entry| {
10423                    let start = entry.range.start.to_point(&buffer);
10424                    let end = entry.range.end.to_point(&buffer);
10425                    if snapshot.is_line_folded(MultiBufferRow(start.row))
10426                        && (start.row == end.row
10427                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
10428                    {
10429                        return None;
10430                    }
10431                    if end > group_end {
10432                        group_end = end;
10433                    }
10434                    if entry.diagnostic.is_primary {
10435                        primary_range = Some(entry.range.clone());
10436                        primary_message = Some(entry.diagnostic.message.clone());
10437                    }
10438                    Some(entry)
10439                })
10440                .collect::<Vec<_>>();
10441            let primary_range = primary_range?;
10442            let primary_message = primary_message?;
10443
10444            let blocks = display_map
10445                .insert_blocks(
10446                    diagnostic_group.iter().map(|entry| {
10447                        let diagnostic = entry.diagnostic.clone();
10448                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10449                        BlockProperties {
10450                            style: BlockStyle::Fixed,
10451                            placement: BlockPlacement::Below(
10452                                buffer.anchor_after(entry.range.start),
10453                            ),
10454                            height: message_height,
10455                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10456                            priority: 0,
10457                        }
10458                    }),
10459                    cx,
10460                )
10461                .into_iter()
10462                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10463                .collect();
10464
10465            Some(ActiveDiagnosticGroup {
10466                primary_range,
10467                primary_message,
10468                group_id,
10469                blocks,
10470                is_valid: true,
10471            })
10472        });
10473    }
10474
10475    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10476        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10477            self.display_map.update(cx, |display_map, cx| {
10478                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10479            });
10480            cx.notify();
10481        }
10482    }
10483
10484    pub fn set_selections_from_remote(
10485        &mut self,
10486        selections: Vec<Selection<Anchor>>,
10487        pending_selection: Option<Selection<Anchor>>,
10488        cx: &mut ViewContext<Self>,
10489    ) {
10490        let old_cursor_position = self.selections.newest_anchor().head();
10491        self.selections.change_with(cx, |s| {
10492            s.select_anchors(selections);
10493            if let Some(pending_selection) = pending_selection {
10494                s.set_pending(pending_selection, SelectMode::Character);
10495            } else {
10496                s.clear_pending();
10497            }
10498        });
10499        self.selections_did_change(false, &old_cursor_position, true, cx);
10500    }
10501
10502    fn push_to_selection_history(&mut self) {
10503        self.selection_history.push(SelectionHistoryEntry {
10504            selections: self.selections.disjoint_anchors(),
10505            select_next_state: self.select_next_state.clone(),
10506            select_prev_state: self.select_prev_state.clone(),
10507            add_selections_state: self.add_selections_state.clone(),
10508        });
10509    }
10510
10511    pub fn transact(
10512        &mut self,
10513        cx: &mut ViewContext<Self>,
10514        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10515    ) -> Option<TransactionId> {
10516        self.start_transaction_at(Instant::now(), cx);
10517        update(self, cx);
10518        self.end_transaction_at(Instant::now(), cx)
10519    }
10520
10521    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10522        self.end_selection(cx);
10523        if let Some(tx_id) = self
10524            .buffer
10525            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10526        {
10527            self.selection_history
10528                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10529            cx.emit(EditorEvent::TransactionBegun {
10530                transaction_id: tx_id,
10531            })
10532        }
10533    }
10534
10535    pub fn end_transaction_at(
10536        &mut self,
10537        now: Instant,
10538        cx: &mut ViewContext<Self>,
10539    ) -> Option<TransactionId> {
10540        if let Some(transaction_id) = self
10541            .buffer
10542            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10543        {
10544            if let Some((_, end_selections)) =
10545                self.selection_history.transaction_mut(transaction_id)
10546            {
10547                *end_selections = Some(self.selections.disjoint_anchors());
10548            } else {
10549                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10550            }
10551
10552            cx.emit(EditorEvent::Edited { transaction_id });
10553            Some(transaction_id)
10554        } else {
10555            None
10556        }
10557    }
10558
10559    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10560        if self.is_singleton(cx) {
10561            let selection = self.selections.newest::<Point>(cx);
10562
10563            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10564            let range = if selection.is_empty() {
10565                let point = selection.head().to_display_point(&display_map);
10566                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10567                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10568                    .to_point(&display_map);
10569                start..end
10570            } else {
10571                selection.range()
10572            };
10573            if display_map.folds_in_range(range).next().is_some() {
10574                self.unfold_lines(&Default::default(), cx)
10575            } else {
10576                self.fold(&Default::default(), cx)
10577            }
10578        } else {
10579            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10580            let mut toggled_buffers = HashSet::default();
10581            for (_, buffer_snapshot, _) in
10582                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10583            {
10584                let buffer_id = buffer_snapshot.remote_id();
10585                if toggled_buffers.insert(buffer_id) {
10586                    if self.buffer_folded(buffer_id, cx) {
10587                        self.unfold_buffer(buffer_id, cx);
10588                    } else {
10589                        self.fold_buffer(buffer_id, cx);
10590                    }
10591                }
10592            }
10593        }
10594    }
10595
10596    pub fn toggle_fold_recursive(
10597        &mut self,
10598        _: &actions::ToggleFoldRecursive,
10599        cx: &mut ViewContext<Self>,
10600    ) {
10601        let selection = self.selections.newest::<Point>(cx);
10602
10603        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10604        let range = if selection.is_empty() {
10605            let point = selection.head().to_display_point(&display_map);
10606            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10607            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10608                .to_point(&display_map);
10609            start..end
10610        } else {
10611            selection.range()
10612        };
10613        if display_map.folds_in_range(range).next().is_some() {
10614            self.unfold_recursive(&Default::default(), cx)
10615        } else {
10616            self.fold_recursive(&Default::default(), cx)
10617        }
10618    }
10619
10620    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10621        if self.is_singleton(cx) {
10622            let mut to_fold = Vec::new();
10623            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10624            let selections = self.selections.all_adjusted(cx);
10625
10626            for selection in selections {
10627                let range = selection.range().sorted();
10628                let buffer_start_row = range.start.row;
10629
10630                if range.start.row != range.end.row {
10631                    let mut found = false;
10632                    let mut row = range.start.row;
10633                    while row <= range.end.row {
10634                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10635                        {
10636                            found = true;
10637                            row = crease.range().end.row + 1;
10638                            to_fold.push(crease);
10639                        } else {
10640                            row += 1
10641                        }
10642                    }
10643                    if found {
10644                        continue;
10645                    }
10646                }
10647
10648                for row in (0..=range.start.row).rev() {
10649                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10650                        if crease.range().end.row >= buffer_start_row {
10651                            to_fold.push(crease);
10652                            if row <= range.start.row {
10653                                break;
10654                            }
10655                        }
10656                    }
10657                }
10658            }
10659
10660            self.fold_creases(to_fold, true, cx);
10661        } else {
10662            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10663            let mut folded_buffers = HashSet::default();
10664            for (_, buffer_snapshot, _) in
10665                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10666            {
10667                let buffer_id = buffer_snapshot.remote_id();
10668                if folded_buffers.insert(buffer_id) {
10669                    self.fold_buffer(buffer_id, cx);
10670                }
10671            }
10672        }
10673    }
10674
10675    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10676        if !self.buffer.read(cx).is_singleton() {
10677            return;
10678        }
10679
10680        let fold_at_level = fold_at.level;
10681        let snapshot = self.buffer.read(cx).snapshot(cx);
10682        let mut to_fold = Vec::new();
10683        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10684
10685        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10686            while start_row < end_row {
10687                match self
10688                    .snapshot(cx)
10689                    .crease_for_buffer_row(MultiBufferRow(start_row))
10690                {
10691                    Some(crease) => {
10692                        let nested_start_row = crease.range().start.row + 1;
10693                        let nested_end_row = crease.range().end.row;
10694
10695                        if current_level < fold_at_level {
10696                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10697                        } else if current_level == fold_at_level {
10698                            to_fold.push(crease);
10699                        }
10700
10701                        start_row = nested_end_row + 1;
10702                    }
10703                    None => start_row += 1,
10704                }
10705            }
10706        }
10707
10708        self.fold_creases(to_fold, true, cx);
10709    }
10710
10711    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10712        if self.buffer.read(cx).is_singleton() {
10713            let mut fold_ranges = Vec::new();
10714            let snapshot = self.buffer.read(cx).snapshot(cx);
10715
10716            for row in 0..snapshot.max_row().0 {
10717                if let Some(foldable_range) =
10718                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10719                {
10720                    fold_ranges.push(foldable_range);
10721                }
10722            }
10723
10724            self.fold_creases(fold_ranges, true, cx);
10725        } else {
10726            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10727                editor
10728                    .update(&mut cx, |editor, cx| {
10729                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10730                            editor.fold_buffer(buffer_id, cx);
10731                        }
10732                    })
10733                    .ok();
10734            });
10735        }
10736    }
10737
10738    pub fn fold_function_bodies(
10739        &mut self,
10740        _: &actions::FoldFunctionBodies,
10741        cx: &mut ViewContext<Self>,
10742    ) {
10743        let snapshot = self.buffer.read(cx).snapshot(cx);
10744        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10745            return;
10746        };
10747        let creases = buffer
10748            .function_body_fold_ranges(0..buffer.len())
10749            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10750            .collect();
10751
10752        self.fold_creases(creases, true, cx);
10753    }
10754
10755    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10756        let mut to_fold = Vec::new();
10757        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10758        let selections = self.selections.all_adjusted(cx);
10759
10760        for selection in selections {
10761            let range = selection.range().sorted();
10762            let buffer_start_row = range.start.row;
10763
10764            if range.start.row != range.end.row {
10765                let mut found = false;
10766                for row in range.start.row..=range.end.row {
10767                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10768                        found = true;
10769                        to_fold.push(crease);
10770                    }
10771                }
10772                if found {
10773                    continue;
10774                }
10775            }
10776
10777            for row in (0..=range.start.row).rev() {
10778                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10779                    if crease.range().end.row >= buffer_start_row {
10780                        to_fold.push(crease);
10781                    } else {
10782                        break;
10783                    }
10784                }
10785            }
10786        }
10787
10788        self.fold_creases(to_fold, true, cx);
10789    }
10790
10791    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10792        let buffer_row = fold_at.buffer_row;
10793        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10794
10795        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10796            let autoscroll = self
10797                .selections
10798                .all::<Point>(cx)
10799                .iter()
10800                .any(|selection| crease.range().overlaps(&selection.range()));
10801
10802            self.fold_creases(vec![crease], autoscroll, cx);
10803        }
10804    }
10805
10806    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10807        if self.is_singleton(cx) {
10808            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10809            let buffer = &display_map.buffer_snapshot;
10810            let selections = self.selections.all::<Point>(cx);
10811            let ranges = selections
10812                .iter()
10813                .map(|s| {
10814                    let range = s.display_range(&display_map).sorted();
10815                    let mut start = range.start.to_point(&display_map);
10816                    let mut end = range.end.to_point(&display_map);
10817                    start.column = 0;
10818                    end.column = buffer.line_len(MultiBufferRow(end.row));
10819                    start..end
10820                })
10821                .collect::<Vec<_>>();
10822
10823            self.unfold_ranges(&ranges, true, true, cx);
10824        } else {
10825            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10826            let mut unfolded_buffers = HashSet::default();
10827            for (_, buffer_snapshot, _) in
10828                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10829            {
10830                let buffer_id = buffer_snapshot.remote_id();
10831                if unfolded_buffers.insert(buffer_id) {
10832                    self.unfold_buffer(buffer_id, cx);
10833                }
10834            }
10835        }
10836    }
10837
10838    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10839        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10840        let selections = self.selections.all::<Point>(cx);
10841        let ranges = selections
10842            .iter()
10843            .map(|s| {
10844                let mut range = s.display_range(&display_map).sorted();
10845                *range.start.column_mut() = 0;
10846                *range.end.column_mut() = display_map.line_len(range.end.row());
10847                let start = range.start.to_point(&display_map);
10848                let end = range.end.to_point(&display_map);
10849                start..end
10850            })
10851            .collect::<Vec<_>>();
10852
10853        self.unfold_ranges(&ranges, true, true, cx);
10854    }
10855
10856    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10857        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10858
10859        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10860            ..Point::new(
10861                unfold_at.buffer_row.0,
10862                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10863            );
10864
10865        let autoscroll = self
10866            .selections
10867            .all::<Point>(cx)
10868            .iter()
10869            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10870
10871        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10872    }
10873
10874    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10875        if self.buffer.read(cx).is_singleton() {
10876            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10877            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10878        } else {
10879            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10880                editor
10881                    .update(&mut cx, |editor, cx| {
10882                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10883                            editor.unfold_buffer(buffer_id, cx);
10884                        }
10885                    })
10886                    .ok();
10887            });
10888        }
10889    }
10890
10891    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10892        let selections = self.selections.all::<Point>(cx);
10893        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10894        let line_mode = self.selections.line_mode;
10895        let ranges = selections
10896            .into_iter()
10897            .map(|s| {
10898                if line_mode {
10899                    let start = Point::new(s.start.row, 0);
10900                    let end = Point::new(
10901                        s.end.row,
10902                        display_map
10903                            .buffer_snapshot
10904                            .line_len(MultiBufferRow(s.end.row)),
10905                    );
10906                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10907                } else {
10908                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10909                }
10910            })
10911            .collect::<Vec<_>>();
10912        self.fold_creases(ranges, true, cx);
10913    }
10914
10915    pub fn fold_ranges<T: ToOffset + Clone>(
10916        &mut self,
10917        ranges: Vec<Range<T>>,
10918        auto_scroll: bool,
10919        cx: &mut ViewContext<Self>,
10920    ) {
10921        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10922        let ranges = ranges
10923            .into_iter()
10924            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
10925            .collect::<Vec<_>>();
10926        self.fold_creases(ranges, auto_scroll, cx);
10927    }
10928
10929    pub fn fold_creases<T: ToOffset + Clone>(
10930        &mut self,
10931        creases: Vec<Crease<T>>,
10932        auto_scroll: bool,
10933        cx: &mut ViewContext<Self>,
10934    ) {
10935        if creases.is_empty() {
10936            return;
10937        }
10938
10939        let mut buffers_affected = HashSet::default();
10940        let multi_buffer = self.buffer().read(cx);
10941        for crease in &creases {
10942            if let Some((_, buffer, _)) =
10943                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10944            {
10945                buffers_affected.insert(buffer.read(cx).remote_id());
10946            };
10947        }
10948
10949        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10950
10951        if auto_scroll {
10952            self.request_autoscroll(Autoscroll::fit(), cx);
10953        }
10954
10955        for buffer_id in buffers_affected {
10956            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10957        }
10958
10959        cx.notify();
10960
10961        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10962            // Clear diagnostics block when folding a range that contains it.
10963            let snapshot = self.snapshot(cx);
10964            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10965                drop(snapshot);
10966                self.active_diagnostics = Some(active_diagnostics);
10967                self.dismiss_diagnostics(cx);
10968            } else {
10969                self.active_diagnostics = Some(active_diagnostics);
10970            }
10971        }
10972
10973        self.scrollbar_marker_state.dirty = true;
10974    }
10975
10976    /// Removes any folds whose ranges intersect any of the given ranges.
10977    pub fn unfold_ranges<T: ToOffset + Clone>(
10978        &mut self,
10979        ranges: &[Range<T>],
10980        inclusive: bool,
10981        auto_scroll: bool,
10982        cx: &mut ViewContext<Self>,
10983    ) {
10984        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10985            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10986        });
10987    }
10988
10989    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10990        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10991            return;
10992        }
10993        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10994            return;
10995        };
10996        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10997        self.display_map
10998            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10999        cx.emit(EditorEvent::BufferFoldToggled {
11000            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11001            folded: true,
11002        });
11003        cx.notify();
11004    }
11005
11006    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11007        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11008            return;
11009        }
11010        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11011            return;
11012        };
11013        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11014        self.display_map.update(cx, |display_map, cx| {
11015            display_map.unfold_buffer(buffer_id, cx);
11016        });
11017        cx.emit(EditorEvent::BufferFoldToggled {
11018            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11019            folded: false,
11020        });
11021        cx.notify();
11022    }
11023
11024    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11025        self.display_map.read(cx).buffer_folded(buffer)
11026    }
11027
11028    /// Removes any folds with the given ranges.
11029    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11030        &mut self,
11031        ranges: &[Range<T>],
11032        type_id: TypeId,
11033        auto_scroll: bool,
11034        cx: &mut ViewContext<Self>,
11035    ) {
11036        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11037            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11038        });
11039    }
11040
11041    fn remove_folds_with<T: ToOffset + Clone>(
11042        &mut self,
11043        ranges: &[Range<T>],
11044        auto_scroll: bool,
11045        cx: &mut ViewContext<Self>,
11046        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11047    ) {
11048        if ranges.is_empty() {
11049            return;
11050        }
11051
11052        let mut buffers_affected = HashSet::default();
11053        let multi_buffer = self.buffer().read(cx);
11054        for range in ranges {
11055            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11056                buffers_affected.insert(buffer.read(cx).remote_id());
11057            };
11058        }
11059
11060        self.display_map.update(cx, update);
11061
11062        if auto_scroll {
11063            self.request_autoscroll(Autoscroll::fit(), cx);
11064        }
11065
11066        for buffer_id in buffers_affected {
11067            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11068        }
11069
11070        cx.notify();
11071        self.scrollbar_marker_state.dirty = true;
11072        self.active_indent_guides_state.dirty = true;
11073    }
11074
11075    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11076        self.display_map.read(cx).fold_placeholder.clone()
11077    }
11078
11079    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11080        if hovered != self.gutter_hovered {
11081            self.gutter_hovered = hovered;
11082            cx.notify();
11083        }
11084    }
11085
11086    pub fn insert_blocks(
11087        &mut self,
11088        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11089        autoscroll: Option<Autoscroll>,
11090        cx: &mut ViewContext<Self>,
11091    ) -> Vec<CustomBlockId> {
11092        let blocks = self
11093            .display_map
11094            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11095        if let Some(autoscroll) = autoscroll {
11096            self.request_autoscroll(autoscroll, cx);
11097        }
11098        cx.notify();
11099        blocks
11100    }
11101
11102    pub fn resize_blocks(
11103        &mut self,
11104        heights: HashMap<CustomBlockId, u32>,
11105        autoscroll: Option<Autoscroll>,
11106        cx: &mut ViewContext<Self>,
11107    ) {
11108        self.display_map
11109            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11110        if let Some(autoscroll) = autoscroll {
11111            self.request_autoscroll(autoscroll, cx);
11112        }
11113        cx.notify();
11114    }
11115
11116    pub fn replace_blocks(
11117        &mut self,
11118        renderers: HashMap<CustomBlockId, RenderBlock>,
11119        autoscroll: Option<Autoscroll>,
11120        cx: &mut ViewContext<Self>,
11121    ) {
11122        self.display_map
11123            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11124        if let Some(autoscroll) = autoscroll {
11125            self.request_autoscroll(autoscroll, cx);
11126        }
11127        cx.notify();
11128    }
11129
11130    pub fn remove_blocks(
11131        &mut self,
11132        block_ids: HashSet<CustomBlockId>,
11133        autoscroll: Option<Autoscroll>,
11134        cx: &mut ViewContext<Self>,
11135    ) {
11136        self.display_map.update(cx, |display_map, cx| {
11137            display_map.remove_blocks(block_ids, cx)
11138        });
11139        if let Some(autoscroll) = autoscroll {
11140            self.request_autoscroll(autoscroll, cx);
11141        }
11142        cx.notify();
11143    }
11144
11145    pub fn row_for_block(
11146        &self,
11147        block_id: CustomBlockId,
11148        cx: &mut ViewContext<Self>,
11149    ) -> Option<DisplayRow> {
11150        self.display_map
11151            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11152    }
11153
11154    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11155        self.focused_block = Some(focused_block);
11156    }
11157
11158    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11159        self.focused_block.take()
11160    }
11161
11162    pub fn insert_creases(
11163        &mut self,
11164        creases: impl IntoIterator<Item = Crease<Anchor>>,
11165        cx: &mut ViewContext<Self>,
11166    ) -> Vec<CreaseId> {
11167        self.display_map
11168            .update(cx, |map, cx| map.insert_creases(creases, cx))
11169    }
11170
11171    pub fn remove_creases(
11172        &mut self,
11173        ids: impl IntoIterator<Item = CreaseId>,
11174        cx: &mut ViewContext<Self>,
11175    ) {
11176        self.display_map
11177            .update(cx, |map, cx| map.remove_creases(ids, cx));
11178    }
11179
11180    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11181        self.display_map
11182            .update(cx, |map, cx| map.snapshot(cx))
11183            .longest_row()
11184    }
11185
11186    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11187        self.display_map
11188            .update(cx, |map, cx| map.snapshot(cx))
11189            .max_point()
11190    }
11191
11192    pub fn text(&self, cx: &AppContext) -> String {
11193        self.buffer.read(cx).read(cx).text()
11194    }
11195
11196    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11197        let text = self.text(cx);
11198        let text = text.trim();
11199
11200        if text.is_empty() {
11201            return None;
11202        }
11203
11204        Some(text.to_string())
11205    }
11206
11207    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11208        self.transact(cx, |this, cx| {
11209            this.buffer
11210                .read(cx)
11211                .as_singleton()
11212                .expect("you can only call set_text on editors for singleton buffers")
11213                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11214        });
11215    }
11216
11217    pub fn display_text(&self, cx: &mut AppContext) -> String {
11218        self.display_map
11219            .update(cx, |map, cx| map.snapshot(cx))
11220            .text()
11221    }
11222
11223    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11224        let mut wrap_guides = smallvec::smallvec![];
11225
11226        if self.show_wrap_guides == Some(false) {
11227            return wrap_guides;
11228        }
11229
11230        let settings = self.buffer.read(cx).settings_at(0, cx);
11231        if settings.show_wrap_guides {
11232            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11233                wrap_guides.push((soft_wrap as usize, true));
11234            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11235                wrap_guides.push((soft_wrap as usize, true));
11236            }
11237            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11238        }
11239
11240        wrap_guides
11241    }
11242
11243    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11244        let settings = self.buffer.read(cx).settings_at(0, cx);
11245        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11246        match mode {
11247            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11248                SoftWrap::None
11249            }
11250            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11251            language_settings::SoftWrap::PreferredLineLength => {
11252                SoftWrap::Column(settings.preferred_line_length)
11253            }
11254            language_settings::SoftWrap::Bounded => {
11255                SoftWrap::Bounded(settings.preferred_line_length)
11256            }
11257        }
11258    }
11259
11260    pub fn set_soft_wrap_mode(
11261        &mut self,
11262        mode: language_settings::SoftWrap,
11263        cx: &mut ViewContext<Self>,
11264    ) {
11265        self.soft_wrap_mode_override = Some(mode);
11266        cx.notify();
11267    }
11268
11269    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11270        self.text_style_refinement = Some(style);
11271    }
11272
11273    /// called by the Element so we know what style we were most recently rendered with.
11274    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11275        let rem_size = cx.rem_size();
11276        self.display_map.update(cx, |map, cx| {
11277            map.set_font(
11278                style.text.font(),
11279                style.text.font_size.to_pixels(rem_size),
11280                cx,
11281            )
11282        });
11283        self.style = Some(style);
11284    }
11285
11286    pub fn style(&self) -> Option<&EditorStyle> {
11287        self.style.as_ref()
11288    }
11289
11290    // Called by the element. This method is not designed to be called outside of the editor
11291    // element's layout code because it does not notify when rewrapping is computed synchronously.
11292    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11293        self.display_map
11294            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11295    }
11296
11297    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11298        if self.soft_wrap_mode_override.is_some() {
11299            self.soft_wrap_mode_override.take();
11300        } else {
11301            let soft_wrap = match self.soft_wrap_mode(cx) {
11302                SoftWrap::GitDiff => return,
11303                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11304                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11305                    language_settings::SoftWrap::None
11306                }
11307            };
11308            self.soft_wrap_mode_override = Some(soft_wrap);
11309        }
11310        cx.notify();
11311    }
11312
11313    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11314        let Some(workspace) = self.workspace() else {
11315            return;
11316        };
11317        let fs = workspace.read(cx).app_state().fs.clone();
11318        let current_show = TabBarSettings::get_global(cx).show;
11319        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11320            setting.show = Some(!current_show);
11321        });
11322    }
11323
11324    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11325        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11326            self.buffer
11327                .read(cx)
11328                .settings_at(0, cx)
11329                .indent_guides
11330                .enabled
11331        });
11332        self.show_indent_guides = Some(!currently_enabled);
11333        cx.notify();
11334    }
11335
11336    fn should_show_indent_guides(&self) -> Option<bool> {
11337        self.show_indent_guides
11338    }
11339
11340    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11341        let mut editor_settings = EditorSettings::get_global(cx).clone();
11342        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11343        EditorSettings::override_global(editor_settings, cx);
11344    }
11345
11346    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11347        self.use_relative_line_numbers
11348            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11349    }
11350
11351    pub fn toggle_relative_line_numbers(
11352        &mut self,
11353        _: &ToggleRelativeLineNumbers,
11354        cx: &mut ViewContext<Self>,
11355    ) {
11356        let is_relative = self.should_use_relative_line_numbers(cx);
11357        self.set_relative_line_number(Some(!is_relative), cx)
11358    }
11359
11360    pub fn set_relative_line_number(
11361        &mut self,
11362        is_relative: Option<bool>,
11363        cx: &mut ViewContext<Self>,
11364    ) {
11365        self.use_relative_line_numbers = is_relative;
11366        cx.notify();
11367    }
11368
11369    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11370        self.show_gutter = show_gutter;
11371        cx.notify();
11372    }
11373
11374    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11375        self.show_scrollbars = show_scrollbars;
11376        cx.notify();
11377    }
11378
11379    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11380        self.show_line_numbers = Some(show_line_numbers);
11381        cx.notify();
11382    }
11383
11384    pub fn set_show_git_diff_gutter(
11385        &mut self,
11386        show_git_diff_gutter: bool,
11387        cx: &mut ViewContext<Self>,
11388    ) {
11389        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11390        cx.notify();
11391    }
11392
11393    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11394        self.show_code_actions = Some(show_code_actions);
11395        cx.notify();
11396    }
11397
11398    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11399        self.show_runnables = Some(show_runnables);
11400        cx.notify();
11401    }
11402
11403    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11404        if self.display_map.read(cx).masked != masked {
11405            self.display_map.update(cx, |map, _| map.masked = masked);
11406        }
11407        cx.notify()
11408    }
11409
11410    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11411        self.show_wrap_guides = Some(show_wrap_guides);
11412        cx.notify();
11413    }
11414
11415    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11416        self.show_indent_guides = Some(show_indent_guides);
11417        cx.notify();
11418    }
11419
11420    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11421        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11422            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11423                if let Some(dir) = file.abs_path(cx).parent() {
11424                    return Some(dir.to_owned());
11425                }
11426            }
11427
11428            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11429                return Some(project_path.path.to_path_buf());
11430            }
11431        }
11432
11433        None
11434    }
11435
11436    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11437        self.active_excerpt(cx)?
11438            .1
11439            .read(cx)
11440            .file()
11441            .and_then(|f| f.as_local())
11442    }
11443
11444    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11445        if let Some(target) = self.target_file(cx) {
11446            cx.reveal_path(&target.abs_path(cx));
11447        }
11448    }
11449
11450    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11451        if let Some(file) = self.target_file(cx) {
11452            if let Some(path) = file.abs_path(cx).to_str() {
11453                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11454            }
11455        }
11456    }
11457
11458    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11459        if let Some(file) = self.target_file(cx) {
11460            if let Some(path) = file.path().to_str() {
11461                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11462            }
11463        }
11464    }
11465
11466    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11467        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11468
11469        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11470            self.start_git_blame(true, cx);
11471        }
11472
11473        cx.notify();
11474    }
11475
11476    pub fn toggle_git_blame_inline(
11477        &mut self,
11478        _: &ToggleGitBlameInline,
11479        cx: &mut ViewContext<Self>,
11480    ) {
11481        self.toggle_git_blame_inline_internal(true, cx);
11482        cx.notify();
11483    }
11484
11485    pub fn git_blame_inline_enabled(&self) -> bool {
11486        self.git_blame_inline_enabled
11487    }
11488
11489    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11490        self.show_selection_menu = self
11491            .show_selection_menu
11492            .map(|show_selections_menu| !show_selections_menu)
11493            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11494
11495        cx.notify();
11496    }
11497
11498    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11499        self.show_selection_menu
11500            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11501    }
11502
11503    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11504        if let Some(project) = self.project.as_ref() {
11505            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11506                return;
11507            };
11508
11509            if buffer.read(cx).file().is_none() {
11510                return;
11511            }
11512
11513            let focused = self.focus_handle(cx).contains_focused(cx);
11514
11515            let project = project.clone();
11516            let blame =
11517                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11518            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11519            self.blame = Some(blame);
11520        }
11521    }
11522
11523    fn toggle_git_blame_inline_internal(
11524        &mut self,
11525        user_triggered: bool,
11526        cx: &mut ViewContext<Self>,
11527    ) {
11528        if self.git_blame_inline_enabled {
11529            self.git_blame_inline_enabled = false;
11530            self.show_git_blame_inline = false;
11531            self.show_git_blame_inline_delay_task.take();
11532        } else {
11533            self.git_blame_inline_enabled = true;
11534            self.start_git_blame_inline(user_triggered, cx);
11535        }
11536
11537        cx.notify();
11538    }
11539
11540    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11541        self.start_git_blame(user_triggered, cx);
11542
11543        if ProjectSettings::get_global(cx)
11544            .git
11545            .inline_blame_delay()
11546            .is_some()
11547        {
11548            self.start_inline_blame_timer(cx);
11549        } else {
11550            self.show_git_blame_inline = true
11551        }
11552    }
11553
11554    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11555        self.blame.as_ref()
11556    }
11557
11558    pub fn show_git_blame_gutter(&self) -> bool {
11559        self.show_git_blame_gutter
11560    }
11561
11562    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11563        self.show_git_blame_gutter && self.has_blame_entries(cx)
11564    }
11565
11566    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11567        self.show_git_blame_inline
11568            && self.focus_handle.is_focused(cx)
11569            && !self.newest_selection_head_on_empty_line(cx)
11570            && self.has_blame_entries(cx)
11571    }
11572
11573    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11574        self.blame()
11575            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11576    }
11577
11578    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11579        let cursor_anchor = self.selections.newest_anchor().head();
11580
11581        let snapshot = self.buffer.read(cx).snapshot(cx);
11582        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11583
11584        snapshot.line_len(buffer_row) == 0
11585    }
11586
11587    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11588        let buffer_and_selection = maybe!({
11589            let selection = self.selections.newest::<Point>(cx);
11590            let selection_range = selection.range();
11591
11592            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11593                (buffer, selection_range.start.row..selection_range.end.row)
11594            } else {
11595                let multi_buffer = self.buffer().read(cx);
11596                let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11597                let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11598
11599                let (excerpt, range) = if selection.reversed {
11600                    buffer_ranges.first()
11601                } else {
11602                    buffer_ranges.last()
11603                }?;
11604
11605                let snapshot = excerpt.buffer();
11606                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11607                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11608                (
11609                    multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11610                    selection,
11611                )
11612            };
11613
11614            Some((buffer, selection))
11615        });
11616
11617        let Some((buffer, selection)) = buffer_and_selection else {
11618            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11619        };
11620
11621        let Some(project) = self.project.as_ref() else {
11622            return Task::ready(Err(anyhow!("editor does not have project")));
11623        };
11624
11625        project.update(cx, |project, cx| {
11626            project.get_permalink_to_line(&buffer, selection, cx)
11627        })
11628    }
11629
11630    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11631        let permalink_task = self.get_permalink_to_line(cx);
11632        let workspace = self.workspace();
11633
11634        cx.spawn(|_, mut cx| async move {
11635            match permalink_task.await {
11636                Ok(permalink) => {
11637                    cx.update(|cx| {
11638                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11639                    })
11640                    .ok();
11641                }
11642                Err(err) => {
11643                    let message = format!("Failed to copy permalink: {err}");
11644
11645                    Err::<(), anyhow::Error>(err).log_err();
11646
11647                    if let Some(workspace) = workspace {
11648                        workspace
11649                            .update(&mut cx, |workspace, cx| {
11650                                struct CopyPermalinkToLine;
11651
11652                                workspace.show_toast(
11653                                    Toast::new(
11654                                        NotificationId::unique::<CopyPermalinkToLine>(),
11655                                        message,
11656                                    ),
11657                                    cx,
11658                                )
11659                            })
11660                            .ok();
11661                    }
11662                }
11663            }
11664        })
11665        .detach();
11666    }
11667
11668    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11669        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11670        if let Some(file) = self.target_file(cx) {
11671            if let Some(path) = file.path().to_str() {
11672                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11673            }
11674        }
11675    }
11676
11677    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11678        let permalink_task = self.get_permalink_to_line(cx);
11679        let workspace = self.workspace();
11680
11681        cx.spawn(|_, mut cx| async move {
11682            match permalink_task.await {
11683                Ok(permalink) => {
11684                    cx.update(|cx| {
11685                        cx.open_url(permalink.as_ref());
11686                    })
11687                    .ok();
11688                }
11689                Err(err) => {
11690                    let message = format!("Failed to open permalink: {err}");
11691
11692                    Err::<(), anyhow::Error>(err).log_err();
11693
11694                    if let Some(workspace) = workspace {
11695                        workspace
11696                            .update(&mut cx, |workspace, cx| {
11697                                struct OpenPermalinkToLine;
11698
11699                                workspace.show_toast(
11700                                    Toast::new(
11701                                        NotificationId::unique::<OpenPermalinkToLine>(),
11702                                        message,
11703                                    ),
11704                                    cx,
11705                                )
11706                            })
11707                            .ok();
11708                    }
11709                }
11710            }
11711        })
11712        .detach();
11713    }
11714
11715    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11716        self.insert_uuid(UuidVersion::V4, cx);
11717    }
11718
11719    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11720        self.insert_uuid(UuidVersion::V7, cx);
11721    }
11722
11723    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11724        self.transact(cx, |this, cx| {
11725            let edits = this
11726                .selections
11727                .all::<Point>(cx)
11728                .into_iter()
11729                .map(|selection| {
11730                    let uuid = match version {
11731                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11732                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11733                    };
11734
11735                    (selection.range(), uuid.to_string())
11736                });
11737            this.edit(edits, cx);
11738            this.refresh_inline_completion(true, false, cx);
11739        });
11740    }
11741
11742    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11743    /// last highlight added will be used.
11744    ///
11745    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11746    pub fn highlight_rows<T: 'static>(
11747        &mut self,
11748        range: Range<Anchor>,
11749        color: Hsla,
11750        should_autoscroll: bool,
11751        cx: &mut ViewContext<Self>,
11752    ) {
11753        let snapshot = self.buffer().read(cx).snapshot(cx);
11754        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11755        let ix = row_highlights.binary_search_by(|highlight| {
11756            Ordering::Equal
11757                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11758                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11759        });
11760
11761        if let Err(mut ix) = ix {
11762            let index = post_inc(&mut self.highlight_order);
11763
11764            // If this range intersects with the preceding highlight, then merge it with
11765            // the preceding highlight. Otherwise insert a new highlight.
11766            let mut merged = false;
11767            if ix > 0 {
11768                let prev_highlight = &mut row_highlights[ix - 1];
11769                if prev_highlight
11770                    .range
11771                    .end
11772                    .cmp(&range.start, &snapshot)
11773                    .is_ge()
11774                {
11775                    ix -= 1;
11776                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11777                        prev_highlight.range.end = range.end;
11778                    }
11779                    merged = true;
11780                    prev_highlight.index = index;
11781                    prev_highlight.color = color;
11782                    prev_highlight.should_autoscroll = should_autoscroll;
11783                }
11784            }
11785
11786            if !merged {
11787                row_highlights.insert(
11788                    ix,
11789                    RowHighlight {
11790                        range: range.clone(),
11791                        index,
11792                        color,
11793                        should_autoscroll,
11794                    },
11795                );
11796            }
11797
11798            // If any of the following highlights intersect with this one, merge them.
11799            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11800                let highlight = &row_highlights[ix];
11801                if next_highlight
11802                    .range
11803                    .start
11804                    .cmp(&highlight.range.end, &snapshot)
11805                    .is_le()
11806                {
11807                    if next_highlight
11808                        .range
11809                        .end
11810                        .cmp(&highlight.range.end, &snapshot)
11811                        .is_gt()
11812                    {
11813                        row_highlights[ix].range.end = next_highlight.range.end;
11814                    }
11815                    row_highlights.remove(ix + 1);
11816                } else {
11817                    break;
11818                }
11819            }
11820        }
11821    }
11822
11823    /// Remove any highlighted row ranges of the given type that intersect the
11824    /// given ranges.
11825    pub fn remove_highlighted_rows<T: 'static>(
11826        &mut self,
11827        ranges_to_remove: Vec<Range<Anchor>>,
11828        cx: &mut ViewContext<Self>,
11829    ) {
11830        let snapshot = self.buffer().read(cx).snapshot(cx);
11831        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11832        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11833        row_highlights.retain(|highlight| {
11834            while let Some(range_to_remove) = ranges_to_remove.peek() {
11835                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11836                    Ordering::Less | Ordering::Equal => {
11837                        ranges_to_remove.next();
11838                    }
11839                    Ordering::Greater => {
11840                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11841                            Ordering::Less | Ordering::Equal => {
11842                                return false;
11843                            }
11844                            Ordering::Greater => break,
11845                        }
11846                    }
11847                }
11848            }
11849
11850            true
11851        })
11852    }
11853
11854    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11855    pub fn clear_row_highlights<T: 'static>(&mut self) {
11856        self.highlighted_rows.remove(&TypeId::of::<T>());
11857    }
11858
11859    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11860    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11861        self.highlighted_rows
11862            .get(&TypeId::of::<T>())
11863            .map_or(&[] as &[_], |vec| vec.as_slice())
11864            .iter()
11865            .map(|highlight| (highlight.range.clone(), highlight.color))
11866    }
11867
11868    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11869    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11870    /// Allows to ignore certain kinds of highlights.
11871    pub fn highlighted_display_rows(
11872        &mut self,
11873        cx: &mut WindowContext,
11874    ) -> BTreeMap<DisplayRow, Hsla> {
11875        let snapshot = self.snapshot(cx);
11876        let mut used_highlight_orders = HashMap::default();
11877        self.highlighted_rows
11878            .iter()
11879            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11880            .fold(
11881                BTreeMap::<DisplayRow, Hsla>::new(),
11882                |mut unique_rows, highlight| {
11883                    let start = highlight.range.start.to_display_point(&snapshot);
11884                    let end = highlight.range.end.to_display_point(&snapshot);
11885                    let start_row = start.row().0;
11886                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11887                        && end.column() == 0
11888                    {
11889                        end.row().0.saturating_sub(1)
11890                    } else {
11891                        end.row().0
11892                    };
11893                    for row in start_row..=end_row {
11894                        let used_index =
11895                            used_highlight_orders.entry(row).or_insert(highlight.index);
11896                        if highlight.index >= *used_index {
11897                            *used_index = highlight.index;
11898                            unique_rows.insert(DisplayRow(row), highlight.color);
11899                        }
11900                    }
11901                    unique_rows
11902                },
11903            )
11904    }
11905
11906    pub fn highlighted_display_row_for_autoscroll(
11907        &self,
11908        snapshot: &DisplaySnapshot,
11909    ) -> Option<DisplayRow> {
11910        self.highlighted_rows
11911            .values()
11912            .flat_map(|highlighted_rows| highlighted_rows.iter())
11913            .filter_map(|highlight| {
11914                if highlight.should_autoscroll {
11915                    Some(highlight.range.start.to_display_point(snapshot).row())
11916                } else {
11917                    None
11918                }
11919            })
11920            .min()
11921    }
11922
11923    pub fn set_search_within_ranges(
11924        &mut self,
11925        ranges: &[Range<Anchor>],
11926        cx: &mut ViewContext<Self>,
11927    ) {
11928        self.highlight_background::<SearchWithinRange>(
11929            ranges,
11930            |colors| colors.editor_document_highlight_read_background,
11931            cx,
11932        )
11933    }
11934
11935    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11936        self.breadcrumb_header = Some(new_header);
11937    }
11938
11939    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11940        self.clear_background_highlights::<SearchWithinRange>(cx);
11941    }
11942
11943    pub fn highlight_background<T: 'static>(
11944        &mut self,
11945        ranges: &[Range<Anchor>],
11946        color_fetcher: fn(&ThemeColors) -> Hsla,
11947        cx: &mut ViewContext<Self>,
11948    ) {
11949        self.background_highlights
11950            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11951        self.scrollbar_marker_state.dirty = true;
11952        cx.notify();
11953    }
11954
11955    pub fn clear_background_highlights<T: 'static>(
11956        &mut self,
11957        cx: &mut ViewContext<Self>,
11958    ) -> Option<BackgroundHighlight> {
11959        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11960        if !text_highlights.1.is_empty() {
11961            self.scrollbar_marker_state.dirty = true;
11962            cx.notify();
11963        }
11964        Some(text_highlights)
11965    }
11966
11967    pub fn highlight_gutter<T: 'static>(
11968        &mut self,
11969        ranges: &[Range<Anchor>],
11970        color_fetcher: fn(&AppContext) -> Hsla,
11971        cx: &mut ViewContext<Self>,
11972    ) {
11973        self.gutter_highlights
11974            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11975        cx.notify();
11976    }
11977
11978    pub fn clear_gutter_highlights<T: 'static>(
11979        &mut self,
11980        cx: &mut ViewContext<Self>,
11981    ) -> Option<GutterHighlight> {
11982        cx.notify();
11983        self.gutter_highlights.remove(&TypeId::of::<T>())
11984    }
11985
11986    #[cfg(feature = "test-support")]
11987    pub fn all_text_background_highlights(
11988        &mut self,
11989        cx: &mut ViewContext<Self>,
11990    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11991        let snapshot = self.snapshot(cx);
11992        let buffer = &snapshot.buffer_snapshot;
11993        let start = buffer.anchor_before(0);
11994        let end = buffer.anchor_after(buffer.len());
11995        let theme = cx.theme().colors();
11996        self.background_highlights_in_range(start..end, &snapshot, theme)
11997    }
11998
11999    #[cfg(feature = "test-support")]
12000    pub fn search_background_highlights(
12001        &mut self,
12002        cx: &mut ViewContext<Self>,
12003    ) -> Vec<Range<Point>> {
12004        let snapshot = self.buffer().read(cx).snapshot(cx);
12005
12006        let highlights = self
12007            .background_highlights
12008            .get(&TypeId::of::<items::BufferSearchHighlights>());
12009
12010        if let Some((_color, ranges)) = highlights {
12011            ranges
12012                .iter()
12013                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12014                .collect_vec()
12015        } else {
12016            vec![]
12017        }
12018    }
12019
12020    fn document_highlights_for_position<'a>(
12021        &'a self,
12022        position: Anchor,
12023        buffer: &'a MultiBufferSnapshot,
12024    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12025        let read_highlights = self
12026            .background_highlights
12027            .get(&TypeId::of::<DocumentHighlightRead>())
12028            .map(|h| &h.1);
12029        let write_highlights = self
12030            .background_highlights
12031            .get(&TypeId::of::<DocumentHighlightWrite>())
12032            .map(|h| &h.1);
12033        let left_position = position.bias_left(buffer);
12034        let right_position = position.bias_right(buffer);
12035        read_highlights
12036            .into_iter()
12037            .chain(write_highlights)
12038            .flat_map(move |ranges| {
12039                let start_ix = match ranges.binary_search_by(|probe| {
12040                    let cmp = probe.end.cmp(&left_position, buffer);
12041                    if cmp.is_ge() {
12042                        Ordering::Greater
12043                    } else {
12044                        Ordering::Less
12045                    }
12046                }) {
12047                    Ok(i) | Err(i) => i,
12048                };
12049
12050                ranges[start_ix..]
12051                    .iter()
12052                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12053            })
12054    }
12055
12056    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12057        self.background_highlights
12058            .get(&TypeId::of::<T>())
12059            .map_or(false, |(_, highlights)| !highlights.is_empty())
12060    }
12061
12062    pub fn background_highlights_in_range(
12063        &self,
12064        search_range: Range<Anchor>,
12065        display_snapshot: &DisplaySnapshot,
12066        theme: &ThemeColors,
12067    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12068        let mut results = Vec::new();
12069        for (color_fetcher, ranges) in self.background_highlights.values() {
12070            let color = color_fetcher(theme);
12071            let start_ix = match ranges.binary_search_by(|probe| {
12072                let cmp = probe
12073                    .end
12074                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12075                if cmp.is_gt() {
12076                    Ordering::Greater
12077                } else {
12078                    Ordering::Less
12079                }
12080            }) {
12081                Ok(i) | Err(i) => i,
12082            };
12083            for range in &ranges[start_ix..] {
12084                if range
12085                    .start
12086                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12087                    .is_ge()
12088                {
12089                    break;
12090                }
12091
12092                let start = range.start.to_display_point(display_snapshot);
12093                let end = range.end.to_display_point(display_snapshot);
12094                results.push((start..end, color))
12095            }
12096        }
12097        results
12098    }
12099
12100    pub fn background_highlight_row_ranges<T: 'static>(
12101        &self,
12102        search_range: Range<Anchor>,
12103        display_snapshot: &DisplaySnapshot,
12104        count: usize,
12105    ) -> Vec<RangeInclusive<DisplayPoint>> {
12106        let mut results = Vec::new();
12107        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12108            return vec![];
12109        };
12110
12111        let start_ix = match ranges.binary_search_by(|probe| {
12112            let cmp = probe
12113                .end
12114                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12115            if cmp.is_gt() {
12116                Ordering::Greater
12117            } else {
12118                Ordering::Less
12119            }
12120        }) {
12121            Ok(i) | Err(i) => i,
12122        };
12123        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12124            if let (Some(start_display), Some(end_display)) = (start, end) {
12125                results.push(
12126                    start_display.to_display_point(display_snapshot)
12127                        ..=end_display.to_display_point(display_snapshot),
12128                );
12129            }
12130        };
12131        let mut start_row: Option<Point> = None;
12132        let mut end_row: Option<Point> = None;
12133        if ranges.len() > count {
12134            return Vec::new();
12135        }
12136        for range in &ranges[start_ix..] {
12137            if range
12138                .start
12139                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12140                .is_ge()
12141            {
12142                break;
12143            }
12144            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12145            if let Some(current_row) = &end_row {
12146                if end.row == current_row.row {
12147                    continue;
12148                }
12149            }
12150            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12151            if start_row.is_none() {
12152                assert_eq!(end_row, None);
12153                start_row = Some(start);
12154                end_row = Some(end);
12155                continue;
12156            }
12157            if let Some(current_end) = end_row.as_mut() {
12158                if start.row > current_end.row + 1 {
12159                    push_region(start_row, end_row);
12160                    start_row = Some(start);
12161                    end_row = Some(end);
12162                } else {
12163                    // Merge two hunks.
12164                    *current_end = end;
12165                }
12166            } else {
12167                unreachable!();
12168            }
12169        }
12170        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12171        push_region(start_row, end_row);
12172        results
12173    }
12174
12175    pub fn gutter_highlights_in_range(
12176        &self,
12177        search_range: Range<Anchor>,
12178        display_snapshot: &DisplaySnapshot,
12179        cx: &AppContext,
12180    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12181        let mut results = Vec::new();
12182        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12183            let color = color_fetcher(cx);
12184            let start_ix = match ranges.binary_search_by(|probe| {
12185                let cmp = probe
12186                    .end
12187                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12188                if cmp.is_gt() {
12189                    Ordering::Greater
12190                } else {
12191                    Ordering::Less
12192                }
12193            }) {
12194                Ok(i) | Err(i) => i,
12195            };
12196            for range in &ranges[start_ix..] {
12197                if range
12198                    .start
12199                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12200                    .is_ge()
12201                {
12202                    break;
12203                }
12204
12205                let start = range.start.to_display_point(display_snapshot);
12206                let end = range.end.to_display_point(display_snapshot);
12207                results.push((start..end, color))
12208            }
12209        }
12210        results
12211    }
12212
12213    /// Get the text ranges corresponding to the redaction query
12214    pub fn redacted_ranges(
12215        &self,
12216        search_range: Range<Anchor>,
12217        display_snapshot: &DisplaySnapshot,
12218        cx: &WindowContext,
12219    ) -> Vec<Range<DisplayPoint>> {
12220        display_snapshot
12221            .buffer_snapshot
12222            .redacted_ranges(search_range, |file| {
12223                if let Some(file) = file {
12224                    file.is_private()
12225                        && EditorSettings::get(
12226                            Some(SettingsLocation {
12227                                worktree_id: file.worktree_id(cx),
12228                                path: file.path().as_ref(),
12229                            }),
12230                            cx,
12231                        )
12232                        .redact_private_values
12233                } else {
12234                    false
12235                }
12236            })
12237            .map(|range| {
12238                range.start.to_display_point(display_snapshot)
12239                    ..range.end.to_display_point(display_snapshot)
12240            })
12241            .collect()
12242    }
12243
12244    pub fn highlight_text<T: 'static>(
12245        &mut self,
12246        ranges: Vec<Range<Anchor>>,
12247        style: HighlightStyle,
12248        cx: &mut ViewContext<Self>,
12249    ) {
12250        self.display_map.update(cx, |map, _| {
12251            map.highlight_text(TypeId::of::<T>(), ranges, style)
12252        });
12253        cx.notify();
12254    }
12255
12256    pub(crate) fn highlight_inlays<T: 'static>(
12257        &mut self,
12258        highlights: Vec<InlayHighlight>,
12259        style: HighlightStyle,
12260        cx: &mut ViewContext<Self>,
12261    ) {
12262        self.display_map.update(cx, |map, _| {
12263            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12264        });
12265        cx.notify();
12266    }
12267
12268    pub fn text_highlights<'a, T: 'static>(
12269        &'a self,
12270        cx: &'a AppContext,
12271    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12272        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12273    }
12274
12275    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12276        let cleared = self
12277            .display_map
12278            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12279        if cleared {
12280            cx.notify();
12281        }
12282    }
12283
12284    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12285        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12286            && self.focus_handle.is_focused(cx)
12287    }
12288
12289    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12290        self.show_cursor_when_unfocused = is_enabled;
12291        cx.notify();
12292    }
12293
12294    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12295        self.project
12296            .as_ref()
12297            .map(|project| project.read(cx).lsp_store())
12298    }
12299
12300    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12301        cx.notify();
12302    }
12303
12304    fn on_buffer_event(
12305        &mut self,
12306        multibuffer: Model<MultiBuffer>,
12307        event: &multi_buffer::Event,
12308        cx: &mut ViewContext<Self>,
12309    ) {
12310        match event {
12311            multi_buffer::Event::Edited {
12312                singleton_buffer_edited,
12313                edited_buffer: buffer_edited,
12314            } => {
12315                self.scrollbar_marker_state.dirty = true;
12316                self.active_indent_guides_state.dirty = true;
12317                self.refresh_active_diagnostics(cx);
12318                self.refresh_code_actions(cx);
12319                if self.has_active_inline_completion() {
12320                    self.update_visible_inline_completion(cx);
12321                }
12322                if let Some(buffer) = buffer_edited {
12323                    let buffer_id = buffer.read(cx).remote_id();
12324                    if !self.registered_buffers.contains_key(&buffer_id) {
12325                        if let Some(lsp_store) = self.lsp_store(cx) {
12326                            lsp_store.update(cx, |lsp_store, cx| {
12327                                self.registered_buffers.insert(
12328                                    buffer_id,
12329                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12330                                );
12331                            })
12332                        }
12333                    }
12334                }
12335                cx.emit(EditorEvent::BufferEdited);
12336                cx.emit(SearchEvent::MatchesInvalidated);
12337                if *singleton_buffer_edited {
12338                    if let Some(project) = &self.project {
12339                        let project = project.read(cx);
12340                        #[allow(clippy::mutable_key_type)]
12341                        let languages_affected = multibuffer
12342                            .read(cx)
12343                            .all_buffers()
12344                            .into_iter()
12345                            .filter_map(|buffer| {
12346                                let buffer = buffer.read(cx);
12347                                let language = buffer.language()?;
12348                                if project.is_local()
12349                                    && project
12350                                        .language_servers_for_local_buffer(buffer, cx)
12351                                        .count()
12352                                        == 0
12353                                {
12354                                    None
12355                                } else {
12356                                    Some(language)
12357                                }
12358                            })
12359                            .cloned()
12360                            .collect::<HashSet<_>>();
12361                        if !languages_affected.is_empty() {
12362                            self.refresh_inlay_hints(
12363                                InlayHintRefreshReason::BufferEdited(languages_affected),
12364                                cx,
12365                            );
12366                        }
12367                    }
12368                }
12369
12370                let Some(project) = &self.project else { return };
12371                let (telemetry, is_via_ssh) = {
12372                    let project = project.read(cx);
12373                    let telemetry = project.client().telemetry().clone();
12374                    let is_via_ssh = project.is_via_ssh();
12375                    (telemetry, is_via_ssh)
12376                };
12377                refresh_linked_ranges(self, cx);
12378                telemetry.log_edit_event("editor", is_via_ssh);
12379            }
12380            multi_buffer::Event::ExcerptsAdded {
12381                buffer,
12382                predecessor,
12383                excerpts,
12384            } => {
12385                self.tasks_update_task = Some(self.refresh_runnables(cx));
12386                let buffer_id = buffer.read(cx).remote_id();
12387                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12388                    if let Some(project) = &self.project {
12389                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12390                    }
12391                }
12392                cx.emit(EditorEvent::ExcerptsAdded {
12393                    buffer: buffer.clone(),
12394                    predecessor: *predecessor,
12395                    excerpts: excerpts.clone(),
12396                });
12397                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12398            }
12399            multi_buffer::Event::ExcerptsRemoved { ids } => {
12400                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12401                let buffer = self.buffer.read(cx);
12402                self.registered_buffers
12403                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12404                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12405            }
12406            multi_buffer::Event::ExcerptsEdited { ids } => {
12407                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12408            }
12409            multi_buffer::Event::ExcerptsExpanded { ids } => {
12410                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12411            }
12412            multi_buffer::Event::Reparsed(buffer_id) => {
12413                self.tasks_update_task = Some(self.refresh_runnables(cx));
12414
12415                cx.emit(EditorEvent::Reparsed(*buffer_id));
12416            }
12417            multi_buffer::Event::LanguageChanged(buffer_id) => {
12418                linked_editing_ranges::refresh_linked_ranges(self, cx);
12419                cx.emit(EditorEvent::Reparsed(*buffer_id));
12420                cx.notify();
12421            }
12422            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12423            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12424            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12425                cx.emit(EditorEvent::TitleChanged)
12426            }
12427            // multi_buffer::Event::DiffBaseChanged => {
12428            //     self.scrollbar_marker_state.dirty = true;
12429            //     cx.emit(EditorEvent::DiffBaseChanged);
12430            //     cx.notify();
12431            // }
12432            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12433            multi_buffer::Event::DiagnosticsUpdated => {
12434                self.refresh_active_diagnostics(cx);
12435                self.scrollbar_marker_state.dirty = true;
12436                cx.notify();
12437            }
12438            _ => {}
12439        };
12440    }
12441
12442    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12443        cx.notify();
12444    }
12445
12446    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12447        self.tasks_update_task = Some(self.refresh_runnables(cx));
12448        self.refresh_inline_completion(true, false, cx);
12449        self.refresh_inlay_hints(
12450            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12451                self.selections.newest_anchor().head(),
12452                &self.buffer.read(cx).snapshot(cx),
12453                cx,
12454            )),
12455            cx,
12456        );
12457
12458        let old_cursor_shape = self.cursor_shape;
12459
12460        {
12461            let editor_settings = EditorSettings::get_global(cx);
12462            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12463            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12464            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12465        }
12466
12467        if old_cursor_shape != self.cursor_shape {
12468            cx.emit(EditorEvent::CursorShapeChanged);
12469        }
12470
12471        let project_settings = ProjectSettings::get_global(cx);
12472        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12473
12474        if self.mode == EditorMode::Full {
12475            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12476            if self.git_blame_inline_enabled != inline_blame_enabled {
12477                self.toggle_git_blame_inline_internal(false, cx);
12478            }
12479        }
12480
12481        cx.notify();
12482    }
12483
12484    pub fn set_searchable(&mut self, searchable: bool) {
12485        self.searchable = searchable;
12486    }
12487
12488    pub fn searchable(&self) -> bool {
12489        self.searchable
12490    }
12491
12492    fn open_proposed_changes_editor(
12493        &mut self,
12494        _: &OpenProposedChangesEditor,
12495        cx: &mut ViewContext<Self>,
12496    ) {
12497        let Some(workspace) = self.workspace() else {
12498            cx.propagate();
12499            return;
12500        };
12501
12502        let selections = self.selections.all::<usize>(cx);
12503        let multi_buffer = self.buffer.read(cx);
12504        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12505        let mut new_selections_by_buffer = HashMap::default();
12506        for selection in selections {
12507            for (excerpt, range) in
12508                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12509            {
12510                let mut range = range.to_point(excerpt.buffer());
12511                range.start.column = 0;
12512                range.end.column = excerpt.buffer().line_len(range.end.row);
12513                new_selections_by_buffer
12514                    .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12515                    .or_insert(Vec::new())
12516                    .push(range)
12517            }
12518        }
12519
12520        let proposed_changes_buffers = new_selections_by_buffer
12521            .into_iter()
12522            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12523            .collect::<Vec<_>>();
12524        let proposed_changes_editor = cx.new_view(|cx| {
12525            ProposedChangesEditor::new(
12526                "Proposed changes",
12527                proposed_changes_buffers,
12528                self.project.clone(),
12529                cx,
12530            )
12531        });
12532
12533        cx.window_context().defer(move |cx| {
12534            workspace.update(cx, |workspace, cx| {
12535                workspace.active_pane().update(cx, |pane, cx| {
12536                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12537                });
12538            });
12539        });
12540    }
12541
12542    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12543        self.open_excerpts_common(None, true, cx)
12544    }
12545
12546    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12547        self.open_excerpts_common(None, false, cx)
12548    }
12549
12550    fn open_excerpts_common(
12551        &mut self,
12552        jump_data: Option<JumpData>,
12553        split: bool,
12554        cx: &mut ViewContext<Self>,
12555    ) {
12556        let Some(workspace) = self.workspace() else {
12557            cx.propagate();
12558            return;
12559        };
12560
12561        if self.buffer.read(cx).is_singleton() {
12562            cx.propagate();
12563            return;
12564        }
12565
12566        let mut new_selections_by_buffer = HashMap::default();
12567        match &jump_data {
12568            Some(JumpData::MultiBufferPoint {
12569                excerpt_id,
12570                position,
12571                anchor,
12572                line_offset_from_top,
12573            }) => {
12574                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12575                if let Some(buffer) = multi_buffer_snapshot
12576                    .buffer_id_for_excerpt(*excerpt_id)
12577                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12578                {
12579                    let buffer_snapshot = buffer.read(cx).snapshot();
12580                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12581                        language::ToPoint::to_point(anchor, &buffer_snapshot)
12582                    } else {
12583                        buffer_snapshot.clip_point(*position, Bias::Left)
12584                    };
12585                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12586                    new_selections_by_buffer.insert(
12587                        buffer,
12588                        (
12589                            vec![jump_to_offset..jump_to_offset],
12590                            Some(*line_offset_from_top),
12591                        ),
12592                    );
12593                }
12594            }
12595            Some(JumpData::MultiBufferRow {
12596                row,
12597                line_offset_from_top,
12598            }) => {
12599                let point = MultiBufferPoint::new(row.0, 0);
12600                if let Some((buffer, buffer_point, _)) =
12601                    self.buffer.read(cx).point_to_buffer_point(point, cx)
12602                {
12603                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12604                    new_selections_by_buffer
12605                        .entry(buffer)
12606                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
12607                        .0
12608                        .push(buffer_offset..buffer_offset)
12609                }
12610            }
12611            None => {
12612                let selections = self.selections.all::<usize>(cx);
12613                let multi_buffer = self.buffer.read(cx);
12614                for selection in selections {
12615                    for (excerpt, mut range) in multi_buffer
12616                        .snapshot(cx)
12617                        .range_to_buffer_ranges(selection.range())
12618                    {
12619                        // When editing branch buffers, jump to the corresponding location
12620                        // in their base buffer.
12621                        let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12622                        let buffer = buffer_handle.read(cx);
12623                        if let Some(base_buffer) = buffer.base_buffer() {
12624                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12625                            buffer_handle = base_buffer;
12626                        }
12627
12628                        if selection.reversed {
12629                            mem::swap(&mut range.start, &mut range.end);
12630                        }
12631                        new_selections_by_buffer
12632                            .entry(buffer_handle)
12633                            .or_insert((Vec::new(), None))
12634                            .0
12635                            .push(range)
12636                    }
12637                }
12638            }
12639        }
12640
12641        if new_selections_by_buffer.is_empty() {
12642            return;
12643        }
12644
12645        // We defer the pane interaction because we ourselves are a workspace item
12646        // and activating a new item causes the pane to call a method on us reentrantly,
12647        // which panics if we're on the stack.
12648        cx.window_context().defer(move |cx| {
12649            workspace.update(cx, |workspace, cx| {
12650                let pane = if split {
12651                    workspace.adjacent_pane(cx)
12652                } else {
12653                    workspace.active_pane().clone()
12654                };
12655
12656                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12657                    let editor = buffer
12658                        .read(cx)
12659                        .file()
12660                        .is_none()
12661                        .then(|| {
12662                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12663                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12664                            // Instead, we try to activate the existing editor in the pane first.
12665                            let (editor, pane_item_index) =
12666                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12667                                    let editor = item.downcast::<Editor>()?;
12668                                    let singleton_buffer =
12669                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12670                                    if singleton_buffer == buffer {
12671                                        Some((editor, i))
12672                                    } else {
12673                                        None
12674                                    }
12675                                })?;
12676                            pane.update(cx, |pane, cx| {
12677                                pane.activate_item(pane_item_index, true, true, cx)
12678                            });
12679                            Some(editor)
12680                        })
12681                        .flatten()
12682                        .unwrap_or_else(|| {
12683                            workspace.open_project_item::<Self>(
12684                                pane.clone(),
12685                                buffer,
12686                                true,
12687                                true,
12688                                cx,
12689                            )
12690                        });
12691
12692                    editor.update(cx, |editor, cx| {
12693                        let autoscroll = match scroll_offset {
12694                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12695                            None => Autoscroll::newest(),
12696                        };
12697                        let nav_history = editor.nav_history.take();
12698                        editor.change_selections(Some(autoscroll), cx, |s| {
12699                            s.select_ranges(ranges);
12700                        });
12701                        editor.nav_history = nav_history;
12702                    });
12703                }
12704            })
12705        });
12706    }
12707
12708    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12709        let snapshot = self.buffer.read(cx).read(cx);
12710        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12711        Some(
12712            ranges
12713                .iter()
12714                .map(move |range| {
12715                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12716                })
12717                .collect(),
12718        )
12719    }
12720
12721    fn selection_replacement_ranges(
12722        &self,
12723        range: Range<OffsetUtf16>,
12724        cx: &mut AppContext,
12725    ) -> Vec<Range<OffsetUtf16>> {
12726        let selections = self.selections.all::<OffsetUtf16>(cx);
12727        let newest_selection = selections
12728            .iter()
12729            .max_by_key(|selection| selection.id)
12730            .unwrap();
12731        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12732        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12733        let snapshot = self.buffer.read(cx).read(cx);
12734        selections
12735            .into_iter()
12736            .map(|mut selection| {
12737                selection.start.0 =
12738                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12739                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12740                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12741                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12742            })
12743            .collect()
12744    }
12745
12746    fn report_editor_event(
12747        &self,
12748        event_type: &'static str,
12749        file_extension: Option<String>,
12750        cx: &AppContext,
12751    ) {
12752        if cfg!(any(test, feature = "test-support")) {
12753            return;
12754        }
12755
12756        let Some(project) = &self.project else { return };
12757
12758        // If None, we are in a file without an extension
12759        let file = self
12760            .buffer
12761            .read(cx)
12762            .as_singleton()
12763            .and_then(|b| b.read(cx).file());
12764        let file_extension = file_extension.or(file
12765            .as_ref()
12766            .and_then(|file| Path::new(file.file_name(cx)).extension())
12767            .and_then(|e| e.to_str())
12768            .map(|a| a.to_string()));
12769
12770        let vim_mode = cx
12771            .global::<SettingsStore>()
12772            .raw_user_settings()
12773            .get("vim_mode")
12774            == Some(&serde_json::Value::Bool(true));
12775
12776        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12777            == language::language_settings::InlineCompletionProvider::Copilot;
12778        let copilot_enabled_for_language = self
12779            .buffer
12780            .read(cx)
12781            .settings_at(0, cx)
12782            .show_inline_completions;
12783
12784        let project = project.read(cx);
12785        telemetry::event!(
12786            event_type,
12787            file_extension,
12788            vim_mode,
12789            copilot_enabled,
12790            copilot_enabled_for_language,
12791            is_via_ssh = project.is_via_ssh(),
12792        );
12793    }
12794
12795    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12796    /// with each line being an array of {text, highlight} objects.
12797    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12798        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12799            return;
12800        };
12801
12802        #[derive(Serialize)]
12803        struct Chunk<'a> {
12804            text: String,
12805            highlight: Option<&'a str>,
12806        }
12807
12808        let snapshot = buffer.read(cx).snapshot();
12809        let range = self
12810            .selected_text_range(false, cx)
12811            .and_then(|selection| {
12812                if selection.range.is_empty() {
12813                    None
12814                } else {
12815                    Some(selection.range)
12816                }
12817            })
12818            .unwrap_or_else(|| 0..snapshot.len());
12819
12820        let chunks = snapshot.chunks(range, true);
12821        let mut lines = Vec::new();
12822        let mut line: VecDeque<Chunk> = VecDeque::new();
12823
12824        let Some(style) = self.style.as_ref() else {
12825            return;
12826        };
12827
12828        for chunk in chunks {
12829            let highlight = chunk
12830                .syntax_highlight_id
12831                .and_then(|id| id.name(&style.syntax));
12832            let mut chunk_lines = chunk.text.split('\n').peekable();
12833            while let Some(text) = chunk_lines.next() {
12834                let mut merged_with_last_token = false;
12835                if let Some(last_token) = line.back_mut() {
12836                    if last_token.highlight == highlight {
12837                        last_token.text.push_str(text);
12838                        merged_with_last_token = true;
12839                    }
12840                }
12841
12842                if !merged_with_last_token {
12843                    line.push_back(Chunk {
12844                        text: text.into(),
12845                        highlight,
12846                    });
12847                }
12848
12849                if chunk_lines.peek().is_some() {
12850                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12851                        line.pop_front();
12852                    }
12853                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12854                        line.pop_back();
12855                    }
12856
12857                    lines.push(mem::take(&mut line));
12858                }
12859            }
12860        }
12861
12862        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12863            return;
12864        };
12865        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12866    }
12867
12868    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12869        self.request_autoscroll(Autoscroll::newest(), cx);
12870        let position = self.selections.newest_display(cx).start;
12871        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12872    }
12873
12874    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12875        &self.inlay_hint_cache
12876    }
12877
12878    pub fn replay_insert_event(
12879        &mut self,
12880        text: &str,
12881        relative_utf16_range: Option<Range<isize>>,
12882        cx: &mut ViewContext<Self>,
12883    ) {
12884        if !self.input_enabled {
12885            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12886            return;
12887        }
12888        if let Some(relative_utf16_range) = relative_utf16_range {
12889            let selections = self.selections.all::<OffsetUtf16>(cx);
12890            self.change_selections(None, cx, |s| {
12891                let new_ranges = selections.into_iter().map(|range| {
12892                    let start = OffsetUtf16(
12893                        range
12894                            .head()
12895                            .0
12896                            .saturating_add_signed(relative_utf16_range.start),
12897                    );
12898                    let end = OffsetUtf16(
12899                        range
12900                            .head()
12901                            .0
12902                            .saturating_add_signed(relative_utf16_range.end),
12903                    );
12904                    start..end
12905                });
12906                s.select_ranges(new_ranges);
12907            });
12908        }
12909
12910        self.handle_input(text, cx);
12911    }
12912
12913    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12914        let Some(provider) = self.semantics_provider.as_ref() else {
12915            return false;
12916        };
12917
12918        let mut supports = false;
12919        self.buffer().read(cx).for_each_buffer(|buffer| {
12920            supports |= provider.supports_inlay_hints(buffer, cx);
12921        });
12922        supports
12923    }
12924
12925    pub fn focus(&self, cx: &mut WindowContext) {
12926        cx.focus(&self.focus_handle)
12927    }
12928
12929    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12930        self.focus_handle.is_focused(cx)
12931    }
12932
12933    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12934        cx.emit(EditorEvent::Focused);
12935
12936        if let Some(descendant) = self
12937            .last_focused_descendant
12938            .take()
12939            .and_then(|descendant| descendant.upgrade())
12940        {
12941            cx.focus(&descendant);
12942        } else {
12943            if let Some(blame) = self.blame.as_ref() {
12944                blame.update(cx, GitBlame::focus)
12945            }
12946
12947            self.blink_manager.update(cx, BlinkManager::enable);
12948            self.show_cursor_names(cx);
12949            self.buffer.update(cx, |buffer, cx| {
12950                buffer.finalize_last_transaction(cx);
12951                if self.leader_peer_id.is_none() {
12952                    buffer.set_active_selections(
12953                        &self.selections.disjoint_anchors(),
12954                        self.selections.line_mode,
12955                        self.cursor_shape,
12956                        cx,
12957                    );
12958                }
12959            });
12960        }
12961    }
12962
12963    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12964        cx.emit(EditorEvent::FocusedIn)
12965    }
12966
12967    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12968        if event.blurred != self.focus_handle {
12969            self.last_focused_descendant = Some(event.blurred);
12970        }
12971    }
12972
12973    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12974        self.blink_manager.update(cx, BlinkManager::disable);
12975        self.buffer
12976            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12977
12978        if let Some(blame) = self.blame.as_ref() {
12979            blame.update(cx, GitBlame::blur)
12980        }
12981        if !self.hover_state.focused(cx) {
12982            hide_hover(self, cx);
12983        }
12984
12985        self.hide_context_menu(cx);
12986        cx.emit(EditorEvent::Blurred);
12987        cx.notify();
12988    }
12989
12990    pub fn register_action<A: Action>(
12991        &mut self,
12992        listener: impl Fn(&A, &mut WindowContext) + 'static,
12993    ) -> Subscription {
12994        let id = self.next_editor_action_id.post_inc();
12995        let listener = Arc::new(listener);
12996        self.editor_actions.borrow_mut().insert(
12997            id,
12998            Box::new(move |cx| {
12999                let cx = cx.window_context();
13000                let listener = listener.clone();
13001                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13002                    let action = action.downcast_ref().unwrap();
13003                    if phase == DispatchPhase::Bubble {
13004                        listener(action, cx)
13005                    }
13006                })
13007            }),
13008        );
13009
13010        let editor_actions = self.editor_actions.clone();
13011        Subscription::new(move || {
13012            editor_actions.borrow_mut().remove(&id);
13013        })
13014    }
13015
13016    pub fn file_header_size(&self) -> u32 {
13017        FILE_HEADER_HEIGHT
13018    }
13019
13020    pub fn revert(
13021        &mut self,
13022        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13023        cx: &mut ViewContext<Self>,
13024    ) {
13025        self.buffer().update(cx, |multi_buffer, cx| {
13026            for (buffer_id, changes) in revert_changes {
13027                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13028                    buffer.update(cx, |buffer, cx| {
13029                        buffer.edit(
13030                            changes.into_iter().map(|(range, text)| {
13031                                (range, text.to_string().map(Arc::<str>::from))
13032                            }),
13033                            None,
13034                            cx,
13035                        );
13036                    });
13037                }
13038            }
13039        });
13040        self.change_selections(None, cx, |selections| selections.refresh());
13041    }
13042
13043    pub fn to_pixel_point(
13044        &mut self,
13045        source: multi_buffer::Anchor,
13046        editor_snapshot: &EditorSnapshot,
13047        cx: &mut ViewContext<Self>,
13048    ) -> Option<gpui::Point<Pixels>> {
13049        let source_point = source.to_display_point(editor_snapshot);
13050        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13051    }
13052
13053    pub fn display_to_pixel_point(
13054        &self,
13055        source: DisplayPoint,
13056        editor_snapshot: &EditorSnapshot,
13057        cx: &WindowContext,
13058    ) -> Option<gpui::Point<Pixels>> {
13059        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13060        let text_layout_details = self.text_layout_details(cx);
13061        let scroll_top = text_layout_details
13062            .scroll_anchor
13063            .scroll_position(editor_snapshot)
13064            .y;
13065
13066        if source.row().as_f32() < scroll_top.floor() {
13067            return None;
13068        }
13069        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13070        let source_y = line_height * (source.row().as_f32() - scroll_top);
13071        Some(gpui::Point::new(source_x, source_y))
13072    }
13073
13074    pub fn has_active_completions_menu(&self) -> bool {
13075        self.context_menu.borrow().as_ref().map_or(false, |menu| {
13076            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13077        })
13078    }
13079
13080    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13081        self.addons
13082            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13083    }
13084
13085    pub fn unregister_addon<T: Addon>(&mut self) {
13086        self.addons.remove(&std::any::TypeId::of::<T>());
13087    }
13088
13089    pub fn addon<T: Addon>(&self) -> Option<&T> {
13090        let type_id = std::any::TypeId::of::<T>();
13091        self.addons
13092            .get(&type_id)
13093            .and_then(|item| item.to_any().downcast_ref::<T>())
13094    }
13095
13096    pub fn add_change_set(
13097        &mut self,
13098        change_set: Model<BufferChangeSet>,
13099        cx: &mut ViewContext<Self>,
13100    ) {
13101        self.diff_map.add_change_set(change_set, cx);
13102    }
13103
13104    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13105        let text_layout_details = self.text_layout_details(cx);
13106        let style = &text_layout_details.editor_style;
13107        let font_id = cx.text_system().resolve_font(&style.text.font());
13108        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13109        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13110
13111        let em_width = cx
13112            .text_system()
13113            .typographic_bounds(font_id, font_size, 'm')
13114            .unwrap()
13115            .size
13116            .width;
13117
13118        gpui::Point::new(em_width, line_height)
13119    }
13120}
13121
13122fn get_unstaged_changes_for_buffers(
13123    project: &Model<Project>,
13124    buffers: impl IntoIterator<Item = Model<Buffer>>,
13125    cx: &mut ViewContext<Editor>,
13126) {
13127    let mut tasks = Vec::new();
13128    project.update(cx, |project, cx| {
13129        for buffer in buffers {
13130            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13131        }
13132    });
13133    cx.spawn(|this, mut cx| async move {
13134        let change_sets = futures::future::join_all(tasks).await;
13135        this.update(&mut cx, |this, cx| {
13136            for change_set in change_sets {
13137                if let Some(change_set) = change_set.log_err() {
13138                    this.diff_map.add_change_set(change_set, cx);
13139                }
13140            }
13141        })
13142        .ok();
13143    })
13144    .detach();
13145}
13146
13147fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13148    let tab_size = tab_size.get() as usize;
13149    let mut width = offset;
13150
13151    for ch in text.chars() {
13152        width += if ch == '\t' {
13153            tab_size - (width % tab_size)
13154        } else {
13155            1
13156        };
13157    }
13158
13159    width - offset
13160}
13161
13162#[cfg(test)]
13163mod tests {
13164    use super::*;
13165
13166    #[test]
13167    fn test_string_size_with_expanded_tabs() {
13168        let nz = |val| NonZeroU32::new(val).unwrap();
13169        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13170        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13171        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13172        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13173        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13174        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13175        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13176        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13177    }
13178}
13179
13180/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13181struct WordBreakingTokenizer<'a> {
13182    input: &'a str,
13183}
13184
13185impl<'a> WordBreakingTokenizer<'a> {
13186    fn new(input: &'a str) -> Self {
13187        Self { input }
13188    }
13189}
13190
13191fn is_char_ideographic(ch: char) -> bool {
13192    use unicode_script::Script::*;
13193    use unicode_script::UnicodeScript;
13194    matches!(ch.script(), Han | Tangut | Yi)
13195}
13196
13197fn is_grapheme_ideographic(text: &str) -> bool {
13198    text.chars().any(is_char_ideographic)
13199}
13200
13201fn is_grapheme_whitespace(text: &str) -> bool {
13202    text.chars().any(|x| x.is_whitespace())
13203}
13204
13205fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13206    text.chars().next().map_or(false, |ch| {
13207        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13208    })
13209}
13210
13211#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13212struct WordBreakToken<'a> {
13213    token: &'a str,
13214    grapheme_len: usize,
13215    is_whitespace: bool,
13216}
13217
13218impl<'a> Iterator for WordBreakingTokenizer<'a> {
13219    /// Yields a span, the count of graphemes in the token, and whether it was
13220    /// whitespace. Note that it also breaks at word boundaries.
13221    type Item = WordBreakToken<'a>;
13222
13223    fn next(&mut self) -> Option<Self::Item> {
13224        use unicode_segmentation::UnicodeSegmentation;
13225        if self.input.is_empty() {
13226            return None;
13227        }
13228
13229        let mut iter = self.input.graphemes(true).peekable();
13230        let mut offset = 0;
13231        let mut graphemes = 0;
13232        if let Some(first_grapheme) = iter.next() {
13233            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13234            offset += first_grapheme.len();
13235            graphemes += 1;
13236            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13237                if let Some(grapheme) = iter.peek().copied() {
13238                    if should_stay_with_preceding_ideograph(grapheme) {
13239                        offset += grapheme.len();
13240                        graphemes += 1;
13241                    }
13242                }
13243            } else {
13244                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13245                let mut next_word_bound = words.peek().copied();
13246                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13247                    next_word_bound = words.next();
13248                }
13249                while let Some(grapheme) = iter.peek().copied() {
13250                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13251                        break;
13252                    };
13253                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13254                        break;
13255                    };
13256                    offset += grapheme.len();
13257                    graphemes += 1;
13258                    iter.next();
13259                }
13260            }
13261            let token = &self.input[..offset];
13262            self.input = &self.input[offset..];
13263            if is_whitespace {
13264                Some(WordBreakToken {
13265                    token: " ",
13266                    grapheme_len: 1,
13267                    is_whitespace: true,
13268                })
13269            } else {
13270                Some(WordBreakToken {
13271                    token,
13272                    grapheme_len: graphemes,
13273                    is_whitespace: false,
13274                })
13275            }
13276        } else {
13277            None
13278        }
13279    }
13280}
13281
13282#[test]
13283fn test_word_breaking_tokenizer() {
13284    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13285        ("", &[]),
13286        ("  ", &[(" ", 1, true)]),
13287        ("Ʒ", &[("Ʒ", 1, false)]),
13288        ("Ǽ", &[("Ǽ", 1, false)]),
13289        ("", &[("", 1, false)]),
13290        ("⋑⋑", &[("⋑⋑", 2, false)]),
13291        (
13292            "原理,进而",
13293            &[
13294                ("", 1, false),
13295                ("理,", 2, false),
13296                ("", 1, false),
13297                ("", 1, false),
13298            ],
13299        ),
13300        (
13301            "hello world",
13302            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13303        ),
13304        (
13305            "hello, world",
13306            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13307        ),
13308        (
13309            "  hello world",
13310            &[
13311                (" ", 1, true),
13312                ("hello", 5, false),
13313                (" ", 1, true),
13314                ("world", 5, false),
13315            ],
13316        ),
13317        (
13318            "这是什么 \n 钢笔",
13319            &[
13320                ("", 1, false),
13321                ("", 1, false),
13322                ("", 1, false),
13323                ("", 1, false),
13324                (" ", 1, true),
13325                ("", 1, false),
13326                ("", 1, false),
13327            ],
13328        ),
13329        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13330    ];
13331
13332    for (input, result) in tests {
13333        assert_eq!(
13334            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13335            result
13336                .iter()
13337                .copied()
13338                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13339                    token,
13340                    grapheme_len,
13341                    is_whitespace,
13342                })
13343                .collect::<Vec<_>>()
13344        );
13345    }
13346}
13347
13348fn wrap_with_prefix(
13349    line_prefix: String,
13350    unwrapped_text: String,
13351    wrap_column: usize,
13352    tab_size: NonZeroU32,
13353) -> String {
13354    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13355    let mut wrapped_text = String::new();
13356    let mut current_line = line_prefix.clone();
13357
13358    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13359    let mut current_line_len = line_prefix_len;
13360    for WordBreakToken {
13361        token,
13362        grapheme_len,
13363        is_whitespace,
13364    } in tokenizer
13365    {
13366        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13367            wrapped_text.push_str(current_line.trim_end());
13368            wrapped_text.push('\n');
13369            current_line.truncate(line_prefix.len());
13370            current_line_len = line_prefix_len;
13371            if !is_whitespace {
13372                current_line.push_str(token);
13373                current_line_len += grapheme_len;
13374            }
13375        } else if !is_whitespace {
13376            current_line.push_str(token);
13377            current_line_len += grapheme_len;
13378        } else if current_line_len != line_prefix_len {
13379            current_line.push(' ');
13380            current_line_len += 1;
13381        }
13382    }
13383
13384    if !current_line.is_empty() {
13385        wrapped_text.push_str(&current_line);
13386    }
13387    wrapped_text
13388}
13389
13390#[test]
13391fn test_wrap_with_prefix() {
13392    assert_eq!(
13393        wrap_with_prefix(
13394            "# ".to_string(),
13395            "abcdefg".to_string(),
13396            4,
13397            NonZeroU32::new(4).unwrap()
13398        ),
13399        "# abcdefg"
13400    );
13401    assert_eq!(
13402        wrap_with_prefix(
13403            "".to_string(),
13404            "\thello world".to_string(),
13405            8,
13406            NonZeroU32::new(4).unwrap()
13407        ),
13408        "hello\nworld"
13409    );
13410    assert_eq!(
13411        wrap_with_prefix(
13412            "// ".to_string(),
13413            "xx \nyy zz aa bb cc".to_string(),
13414            12,
13415            NonZeroU32::new(4).unwrap()
13416        ),
13417        "// xx yy zz\n// aa bb cc"
13418    );
13419    assert_eq!(
13420        wrap_with_prefix(
13421            String::new(),
13422            "这是什么 \n 钢笔".to_string(),
13423            3,
13424            NonZeroU32::new(4).unwrap()
13425        ),
13426        "这是什\n么 钢\n"
13427    );
13428}
13429
13430fn hunks_for_selections(
13431    snapshot: &EditorSnapshot,
13432    selections: &[Selection<Point>],
13433) -> Vec<MultiBufferDiffHunk> {
13434    hunks_for_ranges(
13435        selections.iter().map(|selection| selection.range()),
13436        snapshot,
13437    )
13438}
13439
13440pub fn hunks_for_ranges(
13441    ranges: impl Iterator<Item = Range<Point>>,
13442    snapshot: &EditorSnapshot,
13443) -> Vec<MultiBufferDiffHunk> {
13444    let mut hunks = Vec::new();
13445    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13446        HashMap::default();
13447    for query_range in ranges {
13448        let query_rows =
13449            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13450        for hunk in snapshot.diff_map.diff_hunks_in_range(
13451            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13452            &snapshot.buffer_snapshot,
13453        ) {
13454            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13455            // when the caret is just above or just below the deleted hunk.
13456            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13457            let related_to_selection = if allow_adjacent {
13458                hunk.row_range.overlaps(&query_rows)
13459                    || hunk.row_range.start == query_rows.end
13460                    || hunk.row_range.end == query_rows.start
13461            } else {
13462                hunk.row_range.overlaps(&query_rows)
13463            };
13464            if related_to_selection {
13465                if !processed_buffer_rows
13466                    .entry(hunk.buffer_id)
13467                    .or_default()
13468                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13469                {
13470                    continue;
13471                }
13472                hunks.push(hunk);
13473            }
13474        }
13475    }
13476
13477    hunks
13478}
13479
13480pub trait CollaborationHub {
13481    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13482    fn user_participant_indices<'a>(
13483        &self,
13484        cx: &'a AppContext,
13485    ) -> &'a HashMap<u64, ParticipantIndex>;
13486    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13487}
13488
13489impl CollaborationHub for Model<Project> {
13490    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13491        self.read(cx).collaborators()
13492    }
13493
13494    fn user_participant_indices<'a>(
13495        &self,
13496        cx: &'a AppContext,
13497    ) -> &'a HashMap<u64, ParticipantIndex> {
13498        self.read(cx).user_store().read(cx).participant_indices()
13499    }
13500
13501    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13502        let this = self.read(cx);
13503        let user_ids = this.collaborators().values().map(|c| c.user_id);
13504        this.user_store().read_with(cx, |user_store, cx| {
13505            user_store.participant_names(user_ids, cx)
13506        })
13507    }
13508}
13509
13510pub trait SemanticsProvider {
13511    fn hover(
13512        &self,
13513        buffer: &Model<Buffer>,
13514        position: text::Anchor,
13515        cx: &mut AppContext,
13516    ) -> Option<Task<Vec<project::Hover>>>;
13517
13518    fn inlay_hints(
13519        &self,
13520        buffer_handle: Model<Buffer>,
13521        range: Range<text::Anchor>,
13522        cx: &mut AppContext,
13523    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13524
13525    fn resolve_inlay_hint(
13526        &self,
13527        hint: InlayHint,
13528        buffer_handle: Model<Buffer>,
13529        server_id: LanguageServerId,
13530        cx: &mut AppContext,
13531    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13532
13533    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13534
13535    fn document_highlights(
13536        &self,
13537        buffer: &Model<Buffer>,
13538        position: text::Anchor,
13539        cx: &mut AppContext,
13540    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13541
13542    fn definitions(
13543        &self,
13544        buffer: &Model<Buffer>,
13545        position: text::Anchor,
13546        kind: GotoDefinitionKind,
13547        cx: &mut AppContext,
13548    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13549
13550    fn range_for_rename(
13551        &self,
13552        buffer: &Model<Buffer>,
13553        position: text::Anchor,
13554        cx: &mut AppContext,
13555    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13556
13557    fn perform_rename(
13558        &self,
13559        buffer: &Model<Buffer>,
13560        position: text::Anchor,
13561        new_name: String,
13562        cx: &mut AppContext,
13563    ) -> Option<Task<Result<ProjectTransaction>>>;
13564}
13565
13566pub trait CompletionProvider {
13567    fn completions(
13568        &self,
13569        buffer: &Model<Buffer>,
13570        buffer_position: text::Anchor,
13571        trigger: CompletionContext,
13572        cx: &mut ViewContext<Editor>,
13573    ) -> Task<Result<Vec<Completion>>>;
13574
13575    fn resolve_completions(
13576        &self,
13577        buffer: Model<Buffer>,
13578        completion_indices: Vec<usize>,
13579        completions: Rc<RefCell<Box<[Completion]>>>,
13580        cx: &mut ViewContext<Editor>,
13581    ) -> Task<Result<bool>>;
13582
13583    fn apply_additional_edits_for_completion(
13584        &self,
13585        _buffer: Model<Buffer>,
13586        _completions: Rc<RefCell<Box<[Completion]>>>,
13587        _completion_index: usize,
13588        _push_to_history: bool,
13589        _cx: &mut ViewContext<Editor>,
13590    ) -> Task<Result<Option<language::Transaction>>> {
13591        Task::ready(Ok(None))
13592    }
13593
13594    fn is_completion_trigger(
13595        &self,
13596        buffer: &Model<Buffer>,
13597        position: language::Anchor,
13598        text: &str,
13599        trigger_in_words: bool,
13600        cx: &mut ViewContext<Editor>,
13601    ) -> bool;
13602
13603    fn sort_completions(&self) -> bool {
13604        true
13605    }
13606}
13607
13608pub trait CodeActionProvider {
13609    fn id(&self) -> Arc<str>;
13610
13611    fn code_actions(
13612        &self,
13613        buffer: &Model<Buffer>,
13614        range: Range<text::Anchor>,
13615        cx: &mut WindowContext,
13616    ) -> Task<Result<Vec<CodeAction>>>;
13617
13618    fn apply_code_action(
13619        &self,
13620        buffer_handle: Model<Buffer>,
13621        action: CodeAction,
13622        excerpt_id: ExcerptId,
13623        push_to_history: bool,
13624        cx: &mut WindowContext,
13625    ) -> Task<Result<ProjectTransaction>>;
13626}
13627
13628impl CodeActionProvider for Model<Project> {
13629    fn id(&self) -> Arc<str> {
13630        "project".into()
13631    }
13632
13633    fn code_actions(
13634        &self,
13635        buffer: &Model<Buffer>,
13636        range: Range<text::Anchor>,
13637        cx: &mut WindowContext,
13638    ) -> Task<Result<Vec<CodeAction>>> {
13639        self.update(cx, |project, cx| {
13640            project.code_actions(buffer, range, None, cx)
13641        })
13642    }
13643
13644    fn apply_code_action(
13645        &self,
13646        buffer_handle: Model<Buffer>,
13647        action: CodeAction,
13648        _excerpt_id: ExcerptId,
13649        push_to_history: bool,
13650        cx: &mut WindowContext,
13651    ) -> Task<Result<ProjectTransaction>> {
13652        self.update(cx, |project, cx| {
13653            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13654        })
13655    }
13656}
13657
13658fn snippet_completions(
13659    project: &Project,
13660    buffer: &Model<Buffer>,
13661    buffer_position: text::Anchor,
13662    cx: &mut AppContext,
13663) -> Task<Result<Vec<Completion>>> {
13664    let language = buffer.read(cx).language_at(buffer_position);
13665    let language_name = language.as_ref().map(|language| language.lsp_id());
13666    let snippet_store = project.snippets().read(cx);
13667    let snippets = snippet_store.snippets_for(language_name, cx);
13668
13669    if snippets.is_empty() {
13670        return Task::ready(Ok(vec![]));
13671    }
13672    let snapshot = buffer.read(cx).text_snapshot();
13673    let chars: String = snapshot
13674        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13675        .collect();
13676
13677    let scope = language.map(|language| language.default_scope());
13678    let executor = cx.background_executor().clone();
13679
13680    cx.background_executor().spawn(async move {
13681        let classifier = CharClassifier::new(scope).for_completion(true);
13682        let mut last_word = chars
13683            .chars()
13684            .take_while(|c| classifier.is_word(*c))
13685            .collect::<String>();
13686        last_word = last_word.chars().rev().collect();
13687
13688        if last_word.is_empty() {
13689            return Ok(vec![]);
13690        }
13691
13692        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13693        let to_lsp = |point: &text::Anchor| {
13694            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13695            point_to_lsp(end)
13696        };
13697        let lsp_end = to_lsp(&buffer_position);
13698
13699        let candidates = snippets
13700            .iter()
13701            .enumerate()
13702            .flat_map(|(ix, snippet)| {
13703                snippet
13704                    .prefix
13705                    .iter()
13706                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13707            })
13708            .collect::<Vec<StringMatchCandidate>>();
13709
13710        let mut matches = fuzzy::match_strings(
13711            &candidates,
13712            &last_word,
13713            last_word.chars().any(|c| c.is_uppercase()),
13714            100,
13715            &Default::default(),
13716            executor,
13717        )
13718        .await;
13719
13720        // Remove all candidates where the query's start does not match the start of any word in the candidate
13721        if let Some(query_start) = last_word.chars().next() {
13722            matches.retain(|string_match| {
13723                split_words(&string_match.string).any(|word| {
13724                    // Check that the first codepoint of the word as lowercase matches the first
13725                    // codepoint of the query as lowercase
13726                    word.chars()
13727                        .flat_map(|codepoint| codepoint.to_lowercase())
13728                        .zip(query_start.to_lowercase())
13729                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13730                })
13731            });
13732        }
13733
13734        let matched_strings = matches
13735            .into_iter()
13736            .map(|m| m.string)
13737            .collect::<HashSet<_>>();
13738
13739        let result: Vec<Completion> = snippets
13740            .into_iter()
13741            .filter_map(|snippet| {
13742                let matching_prefix = snippet
13743                    .prefix
13744                    .iter()
13745                    .find(|prefix| matched_strings.contains(*prefix))?;
13746                let start = as_offset - last_word.len();
13747                let start = snapshot.anchor_before(start);
13748                let range = start..buffer_position;
13749                let lsp_start = to_lsp(&start);
13750                let lsp_range = lsp::Range {
13751                    start: lsp_start,
13752                    end: lsp_end,
13753                };
13754                Some(Completion {
13755                    old_range: range,
13756                    new_text: snippet.body.clone(),
13757                    resolved: false,
13758                    label: CodeLabel {
13759                        text: matching_prefix.clone(),
13760                        runs: vec![],
13761                        filter_range: 0..matching_prefix.len(),
13762                    },
13763                    server_id: LanguageServerId(usize::MAX),
13764                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13765                    lsp_completion: lsp::CompletionItem {
13766                        label: snippet.prefix.first().unwrap().clone(),
13767                        kind: Some(CompletionItemKind::SNIPPET),
13768                        label_details: snippet.description.as_ref().map(|description| {
13769                            lsp::CompletionItemLabelDetails {
13770                                detail: Some(description.clone()),
13771                                description: None,
13772                            }
13773                        }),
13774                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13775                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13776                            lsp::InsertReplaceEdit {
13777                                new_text: snippet.body.clone(),
13778                                insert: lsp_range,
13779                                replace: lsp_range,
13780                            },
13781                        )),
13782                        filter_text: Some(snippet.body.clone()),
13783                        sort_text: Some(char::MAX.to_string()),
13784                        ..Default::default()
13785                    },
13786                    confirm: None,
13787                })
13788            })
13789            .collect();
13790
13791        Ok(result)
13792    })
13793}
13794
13795impl CompletionProvider for Model<Project> {
13796    fn completions(
13797        &self,
13798        buffer: &Model<Buffer>,
13799        buffer_position: text::Anchor,
13800        options: CompletionContext,
13801        cx: &mut ViewContext<Editor>,
13802    ) -> Task<Result<Vec<Completion>>> {
13803        self.update(cx, |project, cx| {
13804            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13805            let project_completions = project.completions(buffer, buffer_position, options, cx);
13806            cx.background_executor().spawn(async move {
13807                let mut completions = project_completions.await?;
13808                let snippets_completions = snippets.await?;
13809                completions.extend(snippets_completions);
13810                Ok(completions)
13811            })
13812        })
13813    }
13814
13815    fn resolve_completions(
13816        &self,
13817        buffer: Model<Buffer>,
13818        completion_indices: Vec<usize>,
13819        completions: Rc<RefCell<Box<[Completion]>>>,
13820        cx: &mut ViewContext<Editor>,
13821    ) -> Task<Result<bool>> {
13822        self.update(cx, |project, cx| {
13823            project.lsp_store().update(cx, |lsp_store, cx| {
13824                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13825            })
13826        })
13827    }
13828
13829    fn apply_additional_edits_for_completion(
13830        &self,
13831        buffer: Model<Buffer>,
13832        completions: Rc<RefCell<Box<[Completion]>>>,
13833        completion_index: usize,
13834        push_to_history: bool,
13835        cx: &mut ViewContext<Editor>,
13836    ) -> Task<Result<Option<language::Transaction>>> {
13837        self.update(cx, |project, cx| {
13838            project.lsp_store().update(cx, |lsp_store, cx| {
13839                lsp_store.apply_additional_edits_for_completion(
13840                    buffer,
13841                    completions,
13842                    completion_index,
13843                    push_to_history,
13844                    cx,
13845                )
13846            })
13847        })
13848    }
13849
13850    fn is_completion_trigger(
13851        &self,
13852        buffer: &Model<Buffer>,
13853        position: language::Anchor,
13854        text: &str,
13855        trigger_in_words: bool,
13856        cx: &mut ViewContext<Editor>,
13857    ) -> bool {
13858        let mut chars = text.chars();
13859        let char = if let Some(char) = chars.next() {
13860            char
13861        } else {
13862            return false;
13863        };
13864        if chars.next().is_some() {
13865            return false;
13866        }
13867
13868        let buffer = buffer.read(cx);
13869        let snapshot = buffer.snapshot();
13870        if !snapshot.settings_at(position, cx).show_completions_on_input {
13871            return false;
13872        }
13873        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13874        if trigger_in_words && classifier.is_word(char) {
13875            return true;
13876        }
13877
13878        buffer.completion_triggers().contains(text)
13879    }
13880}
13881
13882impl SemanticsProvider for Model<Project> {
13883    fn hover(
13884        &self,
13885        buffer: &Model<Buffer>,
13886        position: text::Anchor,
13887        cx: &mut AppContext,
13888    ) -> Option<Task<Vec<project::Hover>>> {
13889        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13890    }
13891
13892    fn document_highlights(
13893        &self,
13894        buffer: &Model<Buffer>,
13895        position: text::Anchor,
13896        cx: &mut AppContext,
13897    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13898        Some(self.update(cx, |project, cx| {
13899            project.document_highlights(buffer, position, cx)
13900        }))
13901    }
13902
13903    fn definitions(
13904        &self,
13905        buffer: &Model<Buffer>,
13906        position: text::Anchor,
13907        kind: GotoDefinitionKind,
13908        cx: &mut AppContext,
13909    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13910        Some(self.update(cx, |project, cx| match kind {
13911            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13912            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13913            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13914            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13915        }))
13916    }
13917
13918    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13919        // TODO: make this work for remote projects
13920        self.read(cx)
13921            .language_servers_for_local_buffer(buffer.read(cx), cx)
13922            .any(
13923                |(_, server)| match server.capabilities().inlay_hint_provider {
13924                    Some(lsp::OneOf::Left(enabled)) => enabled,
13925                    Some(lsp::OneOf::Right(_)) => true,
13926                    None => false,
13927                },
13928            )
13929    }
13930
13931    fn inlay_hints(
13932        &self,
13933        buffer_handle: Model<Buffer>,
13934        range: Range<text::Anchor>,
13935        cx: &mut AppContext,
13936    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13937        Some(self.update(cx, |project, cx| {
13938            project.inlay_hints(buffer_handle, range, cx)
13939        }))
13940    }
13941
13942    fn resolve_inlay_hint(
13943        &self,
13944        hint: InlayHint,
13945        buffer_handle: Model<Buffer>,
13946        server_id: LanguageServerId,
13947        cx: &mut AppContext,
13948    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13949        Some(self.update(cx, |project, cx| {
13950            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13951        }))
13952    }
13953
13954    fn range_for_rename(
13955        &self,
13956        buffer: &Model<Buffer>,
13957        position: text::Anchor,
13958        cx: &mut AppContext,
13959    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13960        Some(self.update(cx, |project, cx| {
13961            let buffer = buffer.clone();
13962            let task = project.prepare_rename(buffer.clone(), position, cx);
13963            cx.spawn(|_, mut cx| async move {
13964                Ok(match task.await? {
13965                    PrepareRenameResponse::Success(range) => Some(range),
13966                    PrepareRenameResponse::InvalidPosition => None,
13967                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
13968                        // Fallback on using TreeSitter info to determine identifier range
13969                        buffer.update(&mut cx, |buffer, _| {
13970                            let snapshot = buffer.snapshot();
13971                            let (range, kind) = snapshot.surrounding_word(position);
13972                            if kind != Some(CharKind::Word) {
13973                                return None;
13974                            }
13975                            Some(
13976                                snapshot.anchor_before(range.start)
13977                                    ..snapshot.anchor_after(range.end),
13978                            )
13979                        })?
13980                    }
13981                })
13982            })
13983        }))
13984    }
13985
13986    fn perform_rename(
13987        &self,
13988        buffer: &Model<Buffer>,
13989        position: text::Anchor,
13990        new_name: String,
13991        cx: &mut AppContext,
13992    ) -> Option<Task<Result<ProjectTransaction>>> {
13993        Some(self.update(cx, |project, cx| {
13994            project.perform_rename(buffer.clone(), position, new_name, cx)
13995        }))
13996    }
13997}
13998
13999fn inlay_hint_settings(
14000    location: Anchor,
14001    snapshot: &MultiBufferSnapshot,
14002    cx: &mut ViewContext<Editor>,
14003) -> InlayHintSettings {
14004    let file = snapshot.file_at(location);
14005    let language = snapshot.language_at(location).map(|l| l.name());
14006    language_settings(language, file, cx).inlay_hints
14007}
14008
14009fn consume_contiguous_rows(
14010    contiguous_row_selections: &mut Vec<Selection<Point>>,
14011    selection: &Selection<Point>,
14012    display_map: &DisplaySnapshot,
14013    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14014) -> (MultiBufferRow, MultiBufferRow) {
14015    contiguous_row_selections.push(selection.clone());
14016    let start_row = MultiBufferRow(selection.start.row);
14017    let mut end_row = ending_row(selection, display_map);
14018
14019    while let Some(next_selection) = selections.peek() {
14020        if next_selection.start.row <= end_row.0 {
14021            end_row = ending_row(next_selection, display_map);
14022            contiguous_row_selections.push(selections.next().unwrap().clone());
14023        } else {
14024            break;
14025        }
14026    }
14027    (start_row, end_row)
14028}
14029
14030fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14031    if next_selection.end.column > 0 || next_selection.is_empty() {
14032        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14033    } else {
14034        MultiBufferRow(next_selection.end.row)
14035    }
14036}
14037
14038impl EditorSnapshot {
14039    pub fn remote_selections_in_range<'a>(
14040        &'a self,
14041        range: &'a Range<Anchor>,
14042        collaboration_hub: &dyn CollaborationHub,
14043        cx: &'a AppContext,
14044    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14045        let participant_names = collaboration_hub.user_names(cx);
14046        let participant_indices = collaboration_hub.user_participant_indices(cx);
14047        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14048        let collaborators_by_replica_id = collaborators_by_peer_id
14049            .iter()
14050            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14051            .collect::<HashMap<_, _>>();
14052        self.buffer_snapshot
14053            .selections_in_range(range, false)
14054            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14055                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14056                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14057                let user_name = participant_names.get(&collaborator.user_id).cloned();
14058                Some(RemoteSelection {
14059                    replica_id,
14060                    selection,
14061                    cursor_shape,
14062                    line_mode,
14063                    participant_index,
14064                    peer_id: collaborator.peer_id,
14065                    user_name,
14066                })
14067            })
14068    }
14069
14070    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14071        self.display_snapshot.buffer_snapshot.language_at(position)
14072    }
14073
14074    pub fn is_focused(&self) -> bool {
14075        self.is_focused
14076    }
14077
14078    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14079        self.placeholder_text.as_ref()
14080    }
14081
14082    pub fn scroll_position(&self) -> gpui::Point<f32> {
14083        self.scroll_anchor.scroll_position(&self.display_snapshot)
14084    }
14085
14086    fn gutter_dimensions(
14087        &self,
14088        font_id: FontId,
14089        font_size: Pixels,
14090        em_width: Pixels,
14091        em_advance: Pixels,
14092        max_line_number_width: Pixels,
14093        cx: &AppContext,
14094    ) -> GutterDimensions {
14095        if !self.show_gutter {
14096            return GutterDimensions::default();
14097        }
14098        let descent = cx.text_system().descent(font_id, font_size);
14099
14100        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14101            matches!(
14102                ProjectSettings::get_global(cx).git.git_gutter,
14103                Some(GitGutterSetting::TrackedFiles)
14104            )
14105        });
14106        let gutter_settings = EditorSettings::get_global(cx).gutter;
14107        let show_line_numbers = self
14108            .show_line_numbers
14109            .unwrap_or(gutter_settings.line_numbers);
14110        let line_gutter_width = if show_line_numbers {
14111            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14112            let min_width_for_number_on_gutter = em_advance * 4.0;
14113            max_line_number_width.max(min_width_for_number_on_gutter)
14114        } else {
14115            0.0.into()
14116        };
14117
14118        let show_code_actions = self
14119            .show_code_actions
14120            .unwrap_or(gutter_settings.code_actions);
14121
14122        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14123
14124        let git_blame_entries_width =
14125            self.git_blame_gutter_max_author_length
14126                .map(|max_author_length| {
14127                    // Length of the author name, but also space for the commit hash,
14128                    // the spacing and the timestamp.
14129                    let max_char_count = max_author_length
14130                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14131                        + 7 // length of commit sha
14132                        + 14 // length of max relative timestamp ("60 minutes ago")
14133                        + 4; // gaps and margins
14134
14135                    em_advance * max_char_count
14136                });
14137
14138        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14139        left_padding += if show_code_actions || show_runnables {
14140            em_width * 3.0
14141        } else if show_git_gutter && show_line_numbers {
14142            em_width * 2.0
14143        } else if show_git_gutter || show_line_numbers {
14144            em_width
14145        } else {
14146            px(0.)
14147        };
14148
14149        let right_padding = if gutter_settings.folds && show_line_numbers {
14150            em_width * 4.0
14151        } else if gutter_settings.folds {
14152            em_width * 3.0
14153        } else if show_line_numbers {
14154            em_width
14155        } else {
14156            px(0.)
14157        };
14158
14159        GutterDimensions {
14160            left_padding,
14161            right_padding,
14162            width: line_gutter_width + left_padding + right_padding,
14163            margin: -descent,
14164            git_blame_entries_width,
14165        }
14166    }
14167
14168    pub fn render_crease_toggle(
14169        &self,
14170        buffer_row: MultiBufferRow,
14171        row_contains_cursor: bool,
14172        editor: View<Editor>,
14173        cx: &mut WindowContext,
14174    ) -> Option<AnyElement> {
14175        let folded = self.is_line_folded(buffer_row);
14176        let mut is_foldable = false;
14177
14178        if let Some(crease) = self
14179            .crease_snapshot
14180            .query_row(buffer_row, &self.buffer_snapshot)
14181        {
14182            is_foldable = true;
14183            match crease {
14184                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14185                    if let Some(render_toggle) = render_toggle {
14186                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14187                            if folded {
14188                                editor.update(cx, |editor, cx| {
14189                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14190                                });
14191                            } else {
14192                                editor.update(cx, |editor, cx| {
14193                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14194                                });
14195                            }
14196                        });
14197                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14198                    }
14199                }
14200            }
14201        }
14202
14203        is_foldable |= self.starts_indent(buffer_row);
14204
14205        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14206            Some(
14207                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14208                    .toggle_state(folded)
14209                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14210                        if folded {
14211                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14212                        } else {
14213                            this.fold_at(&FoldAt { buffer_row }, cx);
14214                        }
14215                    }))
14216                    .into_any_element(),
14217            )
14218        } else {
14219            None
14220        }
14221    }
14222
14223    pub fn render_crease_trailer(
14224        &self,
14225        buffer_row: MultiBufferRow,
14226        cx: &mut WindowContext,
14227    ) -> Option<AnyElement> {
14228        let folded = self.is_line_folded(buffer_row);
14229        if let Crease::Inline { render_trailer, .. } = self
14230            .crease_snapshot
14231            .query_row(buffer_row, &self.buffer_snapshot)?
14232        {
14233            let render_trailer = render_trailer.as_ref()?;
14234            Some(render_trailer(buffer_row, folded, cx))
14235        } else {
14236            None
14237        }
14238    }
14239}
14240
14241impl Deref for EditorSnapshot {
14242    type Target = DisplaySnapshot;
14243
14244    fn deref(&self) -> &Self::Target {
14245        &self.display_snapshot
14246    }
14247}
14248
14249#[derive(Clone, Debug, PartialEq, Eq)]
14250pub enum EditorEvent {
14251    InputIgnored {
14252        text: Arc<str>,
14253    },
14254    InputHandled {
14255        utf16_range_to_replace: Option<Range<isize>>,
14256        text: Arc<str>,
14257    },
14258    ExcerptsAdded {
14259        buffer: Model<Buffer>,
14260        predecessor: ExcerptId,
14261        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14262    },
14263    ExcerptsRemoved {
14264        ids: Vec<ExcerptId>,
14265    },
14266    BufferFoldToggled {
14267        ids: Vec<ExcerptId>,
14268        folded: bool,
14269    },
14270    ExcerptsEdited {
14271        ids: Vec<ExcerptId>,
14272    },
14273    ExcerptsExpanded {
14274        ids: Vec<ExcerptId>,
14275    },
14276    BufferEdited,
14277    Edited {
14278        transaction_id: clock::Lamport,
14279    },
14280    Reparsed(BufferId),
14281    Focused,
14282    FocusedIn,
14283    Blurred,
14284    DirtyChanged,
14285    Saved,
14286    TitleChanged,
14287    DiffBaseChanged,
14288    SelectionsChanged {
14289        local: bool,
14290    },
14291    ScrollPositionChanged {
14292        local: bool,
14293        autoscroll: bool,
14294    },
14295    Closed,
14296    TransactionUndone {
14297        transaction_id: clock::Lamport,
14298    },
14299    TransactionBegun {
14300        transaction_id: clock::Lamport,
14301    },
14302    Reloaded,
14303    CursorShapeChanged,
14304}
14305
14306impl EventEmitter<EditorEvent> for Editor {}
14307
14308impl FocusableView for Editor {
14309    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14310        self.focus_handle.clone()
14311    }
14312}
14313
14314impl Render for Editor {
14315    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14316        let settings = ThemeSettings::get_global(cx);
14317
14318        let mut text_style = match self.mode {
14319            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14320                color: cx.theme().colors().editor_foreground,
14321                font_family: settings.ui_font.family.clone(),
14322                font_features: settings.ui_font.features.clone(),
14323                font_fallbacks: settings.ui_font.fallbacks.clone(),
14324                font_size: rems(0.875).into(),
14325                font_weight: settings.ui_font.weight,
14326                line_height: relative(settings.buffer_line_height.value()),
14327                ..Default::default()
14328            },
14329            EditorMode::Full => TextStyle {
14330                color: cx.theme().colors().editor_foreground,
14331                font_family: settings.buffer_font.family.clone(),
14332                font_features: settings.buffer_font.features.clone(),
14333                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14334                font_size: settings.buffer_font_size(cx).into(),
14335                font_weight: settings.buffer_font.weight,
14336                line_height: relative(settings.buffer_line_height.value()),
14337                ..Default::default()
14338            },
14339        };
14340        if let Some(text_style_refinement) = &self.text_style_refinement {
14341            text_style.refine(text_style_refinement)
14342        }
14343
14344        let background = match self.mode {
14345            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14346            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14347            EditorMode::Full => cx.theme().colors().editor_background,
14348        };
14349
14350        EditorElement::new(
14351            cx.view(),
14352            EditorStyle {
14353                background,
14354                local_player: cx.theme().players().local(),
14355                text: text_style,
14356                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14357                syntax: cx.theme().syntax().clone(),
14358                status: cx.theme().status().clone(),
14359                inlay_hints_style: make_inlay_hints_style(cx),
14360                inline_completion_styles: make_suggestion_styles(cx),
14361                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14362            },
14363        )
14364    }
14365}
14366
14367impl ViewInputHandler for Editor {
14368    fn text_for_range(
14369        &mut self,
14370        range_utf16: Range<usize>,
14371        adjusted_range: &mut Option<Range<usize>>,
14372        cx: &mut ViewContext<Self>,
14373    ) -> Option<String> {
14374        let snapshot = self.buffer.read(cx).read(cx);
14375        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14376        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14377        if (start.0..end.0) != range_utf16 {
14378            adjusted_range.replace(start.0..end.0);
14379        }
14380        Some(snapshot.text_for_range(start..end).collect())
14381    }
14382
14383    fn selected_text_range(
14384        &mut self,
14385        ignore_disabled_input: bool,
14386        cx: &mut ViewContext<Self>,
14387    ) -> Option<UTF16Selection> {
14388        // Prevent the IME menu from appearing when holding down an alphabetic key
14389        // while input is disabled.
14390        if !ignore_disabled_input && !self.input_enabled {
14391            return None;
14392        }
14393
14394        let selection = self.selections.newest::<OffsetUtf16>(cx);
14395        let range = selection.range();
14396
14397        Some(UTF16Selection {
14398            range: range.start.0..range.end.0,
14399            reversed: selection.reversed,
14400        })
14401    }
14402
14403    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14404        let snapshot = self.buffer.read(cx).read(cx);
14405        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14406        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14407    }
14408
14409    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14410        self.clear_highlights::<InputComposition>(cx);
14411        self.ime_transaction.take();
14412    }
14413
14414    fn replace_text_in_range(
14415        &mut self,
14416        range_utf16: Option<Range<usize>>,
14417        text: &str,
14418        cx: &mut ViewContext<Self>,
14419    ) {
14420        if !self.input_enabled {
14421            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14422            return;
14423        }
14424
14425        self.transact(cx, |this, cx| {
14426            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14427                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14428                Some(this.selection_replacement_ranges(range_utf16, cx))
14429            } else {
14430                this.marked_text_ranges(cx)
14431            };
14432
14433            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14434                let newest_selection_id = this.selections.newest_anchor().id;
14435                this.selections
14436                    .all::<OffsetUtf16>(cx)
14437                    .iter()
14438                    .zip(ranges_to_replace.iter())
14439                    .find_map(|(selection, range)| {
14440                        if selection.id == newest_selection_id {
14441                            Some(
14442                                (range.start.0 as isize - selection.head().0 as isize)
14443                                    ..(range.end.0 as isize - selection.head().0 as isize),
14444                            )
14445                        } else {
14446                            None
14447                        }
14448                    })
14449            });
14450
14451            cx.emit(EditorEvent::InputHandled {
14452                utf16_range_to_replace: range_to_replace,
14453                text: text.into(),
14454            });
14455
14456            if let Some(new_selected_ranges) = new_selected_ranges {
14457                this.change_selections(None, cx, |selections| {
14458                    selections.select_ranges(new_selected_ranges)
14459                });
14460                this.backspace(&Default::default(), cx);
14461            }
14462
14463            this.handle_input(text, cx);
14464        });
14465
14466        if let Some(transaction) = self.ime_transaction {
14467            self.buffer.update(cx, |buffer, cx| {
14468                buffer.group_until_transaction(transaction, cx);
14469            });
14470        }
14471
14472        self.unmark_text(cx);
14473    }
14474
14475    fn replace_and_mark_text_in_range(
14476        &mut self,
14477        range_utf16: Option<Range<usize>>,
14478        text: &str,
14479        new_selected_range_utf16: Option<Range<usize>>,
14480        cx: &mut ViewContext<Self>,
14481    ) {
14482        if !self.input_enabled {
14483            return;
14484        }
14485
14486        let transaction = self.transact(cx, |this, cx| {
14487            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14488                let snapshot = this.buffer.read(cx).read(cx);
14489                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14490                    for marked_range in &mut marked_ranges {
14491                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14492                        marked_range.start.0 += relative_range_utf16.start;
14493                        marked_range.start =
14494                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14495                        marked_range.end =
14496                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14497                    }
14498                }
14499                Some(marked_ranges)
14500            } else if let Some(range_utf16) = range_utf16 {
14501                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14502                Some(this.selection_replacement_ranges(range_utf16, cx))
14503            } else {
14504                None
14505            };
14506
14507            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14508                let newest_selection_id = this.selections.newest_anchor().id;
14509                this.selections
14510                    .all::<OffsetUtf16>(cx)
14511                    .iter()
14512                    .zip(ranges_to_replace.iter())
14513                    .find_map(|(selection, range)| {
14514                        if selection.id == newest_selection_id {
14515                            Some(
14516                                (range.start.0 as isize - selection.head().0 as isize)
14517                                    ..(range.end.0 as isize - selection.head().0 as isize),
14518                            )
14519                        } else {
14520                            None
14521                        }
14522                    })
14523            });
14524
14525            cx.emit(EditorEvent::InputHandled {
14526                utf16_range_to_replace: range_to_replace,
14527                text: text.into(),
14528            });
14529
14530            if let Some(ranges) = ranges_to_replace {
14531                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14532            }
14533
14534            let marked_ranges = {
14535                let snapshot = this.buffer.read(cx).read(cx);
14536                this.selections
14537                    .disjoint_anchors()
14538                    .iter()
14539                    .map(|selection| {
14540                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14541                    })
14542                    .collect::<Vec<_>>()
14543            };
14544
14545            if text.is_empty() {
14546                this.unmark_text(cx);
14547            } else {
14548                this.highlight_text::<InputComposition>(
14549                    marked_ranges.clone(),
14550                    HighlightStyle {
14551                        underline: Some(UnderlineStyle {
14552                            thickness: px(1.),
14553                            color: None,
14554                            wavy: false,
14555                        }),
14556                        ..Default::default()
14557                    },
14558                    cx,
14559                );
14560            }
14561
14562            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14563            let use_autoclose = this.use_autoclose;
14564            let use_auto_surround = this.use_auto_surround;
14565            this.set_use_autoclose(false);
14566            this.set_use_auto_surround(false);
14567            this.handle_input(text, cx);
14568            this.set_use_autoclose(use_autoclose);
14569            this.set_use_auto_surround(use_auto_surround);
14570
14571            if let Some(new_selected_range) = new_selected_range_utf16 {
14572                let snapshot = this.buffer.read(cx).read(cx);
14573                let new_selected_ranges = marked_ranges
14574                    .into_iter()
14575                    .map(|marked_range| {
14576                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14577                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14578                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14579                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14580                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14581                    })
14582                    .collect::<Vec<_>>();
14583
14584                drop(snapshot);
14585                this.change_selections(None, cx, |selections| {
14586                    selections.select_ranges(new_selected_ranges)
14587                });
14588            }
14589        });
14590
14591        self.ime_transaction = self.ime_transaction.or(transaction);
14592        if let Some(transaction) = self.ime_transaction {
14593            self.buffer.update(cx, |buffer, cx| {
14594                buffer.group_until_transaction(transaction, cx);
14595            });
14596        }
14597
14598        if self.text_highlights::<InputComposition>(cx).is_none() {
14599            self.ime_transaction.take();
14600        }
14601    }
14602
14603    fn bounds_for_range(
14604        &mut self,
14605        range_utf16: Range<usize>,
14606        element_bounds: gpui::Bounds<Pixels>,
14607        cx: &mut ViewContext<Self>,
14608    ) -> Option<gpui::Bounds<Pixels>> {
14609        let text_layout_details = self.text_layout_details(cx);
14610        let gpui::Point {
14611            x: em_width,
14612            y: line_height,
14613        } = self.character_size(cx);
14614
14615        let snapshot = self.snapshot(cx);
14616        let scroll_position = snapshot.scroll_position();
14617        let scroll_left = scroll_position.x * em_width;
14618
14619        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14620        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14621            + self.gutter_dimensions.width
14622            + self.gutter_dimensions.margin;
14623        let y = line_height * (start.row().as_f32() - scroll_position.y);
14624
14625        Some(Bounds {
14626            origin: element_bounds.origin + point(x, y),
14627            size: size(em_width, line_height),
14628        })
14629    }
14630}
14631
14632trait SelectionExt {
14633    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14634    fn spanned_rows(
14635        &self,
14636        include_end_if_at_line_start: bool,
14637        map: &DisplaySnapshot,
14638    ) -> Range<MultiBufferRow>;
14639}
14640
14641impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14642    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14643        let start = self
14644            .start
14645            .to_point(&map.buffer_snapshot)
14646            .to_display_point(map);
14647        let end = self
14648            .end
14649            .to_point(&map.buffer_snapshot)
14650            .to_display_point(map);
14651        if self.reversed {
14652            end..start
14653        } else {
14654            start..end
14655        }
14656    }
14657
14658    fn spanned_rows(
14659        &self,
14660        include_end_if_at_line_start: bool,
14661        map: &DisplaySnapshot,
14662    ) -> Range<MultiBufferRow> {
14663        let start = self.start.to_point(&map.buffer_snapshot);
14664        let mut end = self.end.to_point(&map.buffer_snapshot);
14665        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14666            end.row -= 1;
14667        }
14668
14669        let buffer_start = map.prev_line_boundary(start).0;
14670        let buffer_end = map.next_line_boundary(end).0;
14671        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14672    }
14673}
14674
14675impl<T: InvalidationRegion> InvalidationStack<T> {
14676    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14677    where
14678        S: Clone + ToOffset,
14679    {
14680        while let Some(region) = self.last() {
14681            let all_selections_inside_invalidation_ranges =
14682                if selections.len() == region.ranges().len() {
14683                    selections
14684                        .iter()
14685                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14686                        .all(|(selection, invalidation_range)| {
14687                            let head = selection.head().to_offset(buffer);
14688                            invalidation_range.start <= head && invalidation_range.end >= head
14689                        })
14690                } else {
14691                    false
14692                };
14693
14694            if all_selections_inside_invalidation_ranges {
14695                break;
14696            } else {
14697                self.pop();
14698            }
14699        }
14700    }
14701}
14702
14703impl<T> Default for InvalidationStack<T> {
14704    fn default() -> Self {
14705        Self(Default::default())
14706    }
14707}
14708
14709impl<T> Deref for InvalidationStack<T> {
14710    type Target = Vec<T>;
14711
14712    fn deref(&self) -> &Self::Target {
14713        &self.0
14714    }
14715}
14716
14717impl<T> DerefMut for InvalidationStack<T> {
14718    fn deref_mut(&mut self) -> &mut Self::Target {
14719        &mut self.0
14720    }
14721}
14722
14723impl InvalidationRegion for SnippetState {
14724    fn ranges(&self) -> &[Range<Anchor>] {
14725        &self.ranges[self.active_index]
14726    }
14727}
14728
14729pub fn diagnostic_block_renderer(
14730    diagnostic: Diagnostic,
14731    max_message_rows: Option<u8>,
14732    allow_closing: bool,
14733    _is_valid: bool,
14734) -> RenderBlock {
14735    let (text_without_backticks, code_ranges) =
14736        highlight_diagnostic_message(&diagnostic, max_message_rows);
14737
14738    Arc::new(move |cx: &mut BlockContext| {
14739        let group_id: SharedString = cx.block_id.to_string().into();
14740
14741        let mut text_style = cx.text_style().clone();
14742        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14743        let theme_settings = ThemeSettings::get_global(cx);
14744        text_style.font_family = theme_settings.buffer_font.family.clone();
14745        text_style.font_style = theme_settings.buffer_font.style;
14746        text_style.font_features = theme_settings.buffer_font.features.clone();
14747        text_style.font_weight = theme_settings.buffer_font.weight;
14748
14749        let multi_line_diagnostic = diagnostic.message.contains('\n');
14750
14751        let buttons = |diagnostic: &Diagnostic| {
14752            if multi_line_diagnostic {
14753                v_flex()
14754            } else {
14755                h_flex()
14756            }
14757            .when(allow_closing, |div| {
14758                div.children(diagnostic.is_primary.then(|| {
14759                    IconButton::new("close-block", IconName::XCircle)
14760                        .icon_color(Color::Muted)
14761                        .size(ButtonSize::Compact)
14762                        .style(ButtonStyle::Transparent)
14763                        .visible_on_hover(group_id.clone())
14764                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14765                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14766                }))
14767            })
14768            .child(
14769                IconButton::new("copy-block", IconName::Copy)
14770                    .icon_color(Color::Muted)
14771                    .size(ButtonSize::Compact)
14772                    .style(ButtonStyle::Transparent)
14773                    .visible_on_hover(group_id.clone())
14774                    .on_click({
14775                        let message = diagnostic.message.clone();
14776                        move |_click, cx| {
14777                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14778                        }
14779                    })
14780                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14781            )
14782        };
14783
14784        let icon_size = buttons(&diagnostic)
14785            .into_any_element()
14786            .layout_as_root(AvailableSpace::min_size(), cx);
14787
14788        h_flex()
14789            .id(cx.block_id)
14790            .group(group_id.clone())
14791            .relative()
14792            .size_full()
14793            .block_mouse_down()
14794            .pl(cx.gutter_dimensions.width)
14795            .w(cx.max_width - cx.gutter_dimensions.full_width())
14796            .child(
14797                div()
14798                    .flex()
14799                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14800                    .flex_shrink(),
14801            )
14802            .child(buttons(&diagnostic))
14803            .child(div().flex().flex_shrink_0().child(
14804                StyledText::new(text_without_backticks.clone()).with_highlights(
14805                    &text_style,
14806                    code_ranges.iter().map(|range| {
14807                        (
14808                            range.clone(),
14809                            HighlightStyle {
14810                                font_weight: Some(FontWeight::BOLD),
14811                                ..Default::default()
14812                            },
14813                        )
14814                    }),
14815                ),
14816            ))
14817            .into_any_element()
14818    })
14819}
14820
14821fn inline_completion_edit_text(
14822    editor_snapshot: &EditorSnapshot,
14823    edits: &Vec<(Range<Anchor>, String)>,
14824    include_deletions: bool,
14825    cx: &WindowContext,
14826) -> InlineCompletionText {
14827    let edit_start = edits
14828        .first()
14829        .unwrap()
14830        .0
14831        .start
14832        .to_display_point(editor_snapshot);
14833
14834    let mut text = String::new();
14835    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14836    let mut highlights = Vec::new();
14837    for (old_range, new_text) in edits {
14838        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14839        text.extend(
14840            editor_snapshot
14841                .buffer_snapshot
14842                .chunks(offset..old_offset_range.start, false)
14843                .map(|chunk| chunk.text),
14844        );
14845        offset = old_offset_range.end;
14846
14847        let start = text.len();
14848        let color = if include_deletions && new_text.is_empty() {
14849            text.extend(
14850                editor_snapshot
14851                    .buffer_snapshot
14852                    .chunks(old_offset_range.start..offset, false)
14853                    .map(|chunk| chunk.text),
14854            );
14855            cx.theme().status().deleted_background
14856        } else {
14857            text.push_str(new_text);
14858            cx.theme().status().created_background
14859        };
14860        let end = text.len();
14861
14862        highlights.push((
14863            start..end,
14864            HighlightStyle {
14865                background_color: Some(color),
14866                ..Default::default()
14867            },
14868        ));
14869    }
14870
14871    let edit_end = edits
14872        .last()
14873        .unwrap()
14874        .0
14875        .end
14876        .to_display_point(editor_snapshot);
14877    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14878        .to_offset(editor_snapshot, Bias::Right);
14879    text.extend(
14880        editor_snapshot
14881            .buffer_snapshot
14882            .chunks(offset..end_of_line, false)
14883            .map(|chunk| chunk.text),
14884    );
14885
14886    InlineCompletionText::Edit {
14887        text: text.into(),
14888        highlights,
14889    }
14890}
14891
14892pub fn highlight_diagnostic_message(
14893    diagnostic: &Diagnostic,
14894    mut max_message_rows: Option<u8>,
14895) -> (SharedString, Vec<Range<usize>>) {
14896    let mut text_without_backticks = String::new();
14897    let mut code_ranges = Vec::new();
14898
14899    if let Some(source) = &diagnostic.source {
14900        text_without_backticks.push_str(source);
14901        code_ranges.push(0..source.len());
14902        text_without_backticks.push_str(": ");
14903    }
14904
14905    let mut prev_offset = 0;
14906    let mut in_code_block = false;
14907    let has_row_limit = max_message_rows.is_some();
14908    let mut newline_indices = diagnostic
14909        .message
14910        .match_indices('\n')
14911        .filter(|_| has_row_limit)
14912        .map(|(ix, _)| ix)
14913        .fuse()
14914        .peekable();
14915
14916    for (quote_ix, _) in diagnostic
14917        .message
14918        .match_indices('`')
14919        .chain([(diagnostic.message.len(), "")])
14920    {
14921        let mut first_newline_ix = None;
14922        let mut last_newline_ix = None;
14923        while let Some(newline_ix) = newline_indices.peek() {
14924            if *newline_ix < quote_ix {
14925                if first_newline_ix.is_none() {
14926                    first_newline_ix = Some(*newline_ix);
14927                }
14928                last_newline_ix = Some(*newline_ix);
14929
14930                if let Some(rows_left) = &mut max_message_rows {
14931                    if *rows_left == 0 {
14932                        break;
14933                    } else {
14934                        *rows_left -= 1;
14935                    }
14936                }
14937                let _ = newline_indices.next();
14938            } else {
14939                break;
14940            }
14941        }
14942        let prev_len = text_without_backticks.len();
14943        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14944        text_without_backticks.push_str(new_text);
14945        if in_code_block {
14946            code_ranges.push(prev_len..text_without_backticks.len());
14947        }
14948        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14949        in_code_block = !in_code_block;
14950        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14951            text_without_backticks.push_str("...");
14952            break;
14953        }
14954    }
14955
14956    (text_without_backticks.into(), code_ranges)
14957}
14958
14959fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14960    match severity {
14961        DiagnosticSeverity::ERROR => colors.error,
14962        DiagnosticSeverity::WARNING => colors.warning,
14963        DiagnosticSeverity::INFORMATION => colors.info,
14964        DiagnosticSeverity::HINT => colors.info,
14965        _ => colors.ignored,
14966    }
14967}
14968
14969pub fn styled_runs_for_code_label<'a>(
14970    label: &'a CodeLabel,
14971    syntax_theme: &'a theme::SyntaxTheme,
14972) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14973    let fade_out = HighlightStyle {
14974        fade_out: Some(0.35),
14975        ..Default::default()
14976    };
14977
14978    let mut prev_end = label.filter_range.end;
14979    label
14980        .runs
14981        .iter()
14982        .enumerate()
14983        .flat_map(move |(ix, (range, highlight_id))| {
14984            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14985                style
14986            } else {
14987                return Default::default();
14988            };
14989            let mut muted_style = style;
14990            muted_style.highlight(fade_out);
14991
14992            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14993            if range.start >= label.filter_range.end {
14994                if range.start > prev_end {
14995                    runs.push((prev_end..range.start, fade_out));
14996                }
14997                runs.push((range.clone(), muted_style));
14998            } else if range.end <= label.filter_range.end {
14999                runs.push((range.clone(), style));
15000            } else {
15001                runs.push((range.start..label.filter_range.end, style));
15002                runs.push((label.filter_range.end..range.end, muted_style));
15003            }
15004            prev_end = cmp::max(prev_end, range.end);
15005
15006            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15007                runs.push((prev_end..label.text.len(), fade_out));
15008            }
15009
15010            runs
15011        })
15012}
15013
15014pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15015    let mut prev_index = 0;
15016    let mut prev_codepoint: Option<char> = None;
15017    text.char_indices()
15018        .chain([(text.len(), '\0')])
15019        .filter_map(move |(index, codepoint)| {
15020            let prev_codepoint = prev_codepoint.replace(codepoint)?;
15021            let is_boundary = index == text.len()
15022                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15023                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15024            if is_boundary {
15025                let chunk = &text[prev_index..index];
15026                prev_index = index;
15027                Some(chunk)
15028            } else {
15029                None
15030            }
15031        })
15032}
15033
15034pub trait RangeToAnchorExt: Sized {
15035    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15036
15037    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15038        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15039        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15040    }
15041}
15042
15043impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15044    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15045        let start_offset = self.start.to_offset(snapshot);
15046        let end_offset = self.end.to_offset(snapshot);
15047        if start_offset == end_offset {
15048            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15049        } else {
15050            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15051        }
15052    }
15053}
15054
15055pub trait RowExt {
15056    fn as_f32(&self) -> f32;
15057
15058    fn next_row(&self) -> Self;
15059
15060    fn previous_row(&self) -> Self;
15061
15062    fn minus(&self, other: Self) -> u32;
15063}
15064
15065impl RowExt for DisplayRow {
15066    fn as_f32(&self) -> f32 {
15067        self.0 as f32
15068    }
15069
15070    fn next_row(&self) -> Self {
15071        Self(self.0 + 1)
15072    }
15073
15074    fn previous_row(&self) -> Self {
15075        Self(self.0.saturating_sub(1))
15076    }
15077
15078    fn minus(&self, other: Self) -> u32 {
15079        self.0 - other.0
15080    }
15081}
15082
15083impl RowExt for MultiBufferRow {
15084    fn as_f32(&self) -> f32 {
15085        self.0 as f32
15086    }
15087
15088    fn next_row(&self) -> Self {
15089        Self(self.0 + 1)
15090    }
15091
15092    fn previous_row(&self) -> Self {
15093        Self(self.0.saturating_sub(1))
15094    }
15095
15096    fn minus(&self, other: Self) -> u32 {
15097        self.0 - other.0
15098    }
15099}
15100
15101trait RowRangeExt {
15102    type Row;
15103
15104    fn len(&self) -> usize;
15105
15106    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15107}
15108
15109impl RowRangeExt for Range<MultiBufferRow> {
15110    type Row = MultiBufferRow;
15111
15112    fn len(&self) -> usize {
15113        (self.end.0 - self.start.0) as usize
15114    }
15115
15116    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15117        (self.start.0..self.end.0).map(MultiBufferRow)
15118    }
15119}
15120
15121impl RowRangeExt for Range<DisplayRow> {
15122    type Row = DisplayRow;
15123
15124    fn len(&self) -> usize {
15125        (self.end.0 - self.start.0) as usize
15126    }
15127
15128    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15129        (self.start.0..self.end.0).map(DisplayRow)
15130    }
15131}
15132
15133fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15134    if hunk.diff_base_byte_range.is_empty() {
15135        DiffHunkStatus::Added
15136    } else if hunk.row_range.is_empty() {
15137        DiffHunkStatus::Removed
15138    } else {
15139        DiffHunkStatus::Modified
15140    }
15141}
15142
15143/// If select range has more than one line, we
15144/// just point the cursor to range.start.
15145fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15146    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15147        range
15148    } else {
15149        range.start..range.start
15150    }
15151}
15152
15153pub struct KillRing(ClipboardItem);
15154impl Global for KillRing {}
15155
15156const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);