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 debounced_delay;
   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;
   31mod inline_completion_provider;
   32pub mod items;
   33mod linked_editing_ranges;
   34mod lsp_ext;
   35mod mouse_context_menu;
   36pub mod movement;
   37mod persistence;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45mod signature_help;
   46#[cfg(any(test, feature = "test-support"))]
   47pub mod test;
   48
   49use ::git::diff::{DiffHunk, DiffHunkStatus};
   50use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   51pub(crate) use actions::*;
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use client::{Collaborator, ParticipantIndex};
   56use clock::ReplicaId;
   57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   58use convert_case::{Case, Casing};
   59use debounced_delay::DebouncedDelay;
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings,
   64};
   65pub use editor_settings_controls::*;
   66use element::LineWithInvisibles;
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::FutureExt;
   71use fuzzy::{StringMatch, StringMatchCandidate};
   72use git::blame::GitBlame;
   73use git::diff_hunk_to_display;
   74use gpui::{
   75    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   76    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   77    ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
   78    FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
   79    KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   80    SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   81    UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
   82    VisualContext, WeakFocusHandle, WeakView, WindowContext,
   83};
   84use highlight_matching_bracket::refresh_matching_bracket_highlights;
   85use hover_popover::{hide_hover, HoverState};
   86use hunk_diff::ExpandedHunks;
   87pub(crate) use hunk_diff::HoveredHunk;
   88use indent_guides::ActiveIndentGuidesState;
   89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   90pub use inline_completion_provider::*;
   91pub use items::MAX_TAB_TITLE_LEN;
   92use itertools::Itertools;
   93use language::{
   94    language_settings::{self, all_language_settings, InlayHintSettings},
   95    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   96    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   97    Point, Selection, SelectionGoal, TransactionId,
   98};
   99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  100use linked_editing_ranges::refresh_linked_ranges;
  101use task::{ResolvedTask, TaskTemplate, TaskVariables};
  102
  103use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  104pub use lsp::CompletionContext;
  105use lsp::{
  106    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  107    LanguageServerId,
  108};
  109use mouse_context_menu::MouseContextMenu;
  110use movement::TextLayoutDetails;
  111pub use multi_buffer::{
  112    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  113    ToPoint,
  114};
  115use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
  116use ordered_float::OrderedFloat;
  117use parking_lot::{Mutex, RwLock};
  118use project::project_settings::{GitGutterSetting, ProjectSettings};
  119use project::{
  120    CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
  121    ProjectTransaction, TaskSourceKind,
  122};
  123use rand::prelude::*;
  124use rpc::{proto::*, ErrorExt};
  125use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  126use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  127use serde::{Deserialize, Serialize};
  128use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  129use smallvec::SmallVec;
  130use snippet::Snippet;
  131use std::{
  132    any::TypeId,
  133    borrow::Cow,
  134    cell::RefCell,
  135    cmp::{self, Ordering, Reverse},
  136    mem,
  137    num::NonZeroU32,
  138    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  139    path::{Path, PathBuf},
  140    rc::Rc,
  141    sync::Arc,
  142    time::{Duration, Instant},
  143};
  144pub use sum_tree::Bias;
  145use sum_tree::TreeMap;
  146use text::{BufferId, OffsetUtf16, Rope};
  147use theme::{
  148    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  149    ThemeColors, ThemeSettings,
  150};
  151use ui::{
  152    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  153    ListItem, Popover, Tooltip,
  154};
  155use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  156use workspace::item::{ItemHandle, PreviewTabsSettings};
  157use workspace::notifications::{DetachAndPromptErr, NotificationId};
  158use workspace::{
  159    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  160};
  161use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  162
  163use crate::hover_links::find_url;
  164use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  165
  166pub const FILE_HEADER_HEIGHT: u32 = 1;
  167pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  168pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  169pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  170const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  171const MAX_LINE_LEN: usize = 1024;
  172const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  173const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  174pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  175#[doc(hidden)]
  176pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  177#[doc(hidden)]
  178pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  179
  180pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  181pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  182
  183pub fn render_parsed_markdown(
  184    element_id: impl Into<ElementId>,
  185    parsed: &language::ParsedMarkdown,
  186    editor_style: &EditorStyle,
  187    workspace: Option<WeakView<Workspace>>,
  188    cx: &mut WindowContext,
  189) -> InteractiveText {
  190    let code_span_background_color = cx
  191        .theme()
  192        .colors()
  193        .editor_document_highlight_read_background;
  194
  195    let highlights = gpui::combine_highlights(
  196        parsed.highlights.iter().filter_map(|(range, highlight)| {
  197            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  198            Some((range.clone(), highlight))
  199        }),
  200        parsed
  201            .regions
  202            .iter()
  203            .zip(&parsed.region_ranges)
  204            .filter_map(|(region, range)| {
  205                if region.code {
  206                    Some((
  207                        range.clone(),
  208                        HighlightStyle {
  209                            background_color: Some(code_span_background_color),
  210                            ..Default::default()
  211                        },
  212                    ))
  213                } else {
  214                    None
  215                }
  216            }),
  217    );
  218
  219    let mut links = Vec::new();
  220    let mut link_ranges = Vec::new();
  221    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  222        if let Some(link) = region.link.clone() {
  223            links.push(link);
  224            link_ranges.push(range.clone());
  225        }
  226    }
  227
  228    InteractiveText::new(
  229        element_id,
  230        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  231    )
  232    .on_click(link_ranges, move |clicked_range_ix, cx| {
  233        match &links[clicked_range_ix] {
  234            markdown::Link::Web { url } => cx.open_url(url),
  235            markdown::Link::Path { path } => {
  236                if let Some(workspace) = &workspace {
  237                    _ = workspace.update(cx, |workspace, cx| {
  238                        workspace.open_abs_path(path.clone(), false, cx).detach();
  239                    });
  240                }
  241            }
  242        }
  243    })
  244}
  245
  246#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  247pub(crate) enum InlayId {
  248    Suggestion(usize),
  249    Hint(usize),
  250}
  251
  252impl InlayId {
  253    fn id(&self) -> usize {
  254        match self {
  255            Self::Suggestion(id) => *id,
  256            Self::Hint(id) => *id,
  257        }
  258    }
  259}
  260
  261enum DiffRowHighlight {}
  262enum DocumentHighlightRead {}
  263enum DocumentHighlightWrite {}
  264enum InputComposition {}
  265
  266#[derive(Copy, Clone, PartialEq, Eq)]
  267pub enum Direction {
  268    Prev,
  269    Next,
  270}
  271
  272#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  273pub enum Navigated {
  274    Yes,
  275    No,
  276}
  277
  278impl Navigated {
  279    pub fn from_bool(yes: bool) -> Navigated {
  280        if yes {
  281            Navigated::Yes
  282        } else {
  283            Navigated::No
  284        }
  285    }
  286}
  287
  288pub fn init_settings(cx: &mut AppContext) {
  289    EditorSettings::register(cx);
  290}
  291
  292pub fn init(cx: &mut AppContext) {
  293    init_settings(cx);
  294
  295    workspace::register_project_item::<Editor>(cx);
  296    workspace::FollowableViewRegistry::register::<Editor>(cx);
  297    workspace::register_serializable_item::<Editor>(cx);
  298
  299    cx.observe_new_views(
  300        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  301            workspace.register_action(Editor::new_file);
  302            workspace.register_action(Editor::new_file_vertical);
  303            workspace.register_action(Editor::new_file_horizontal);
  304        },
  305    )
  306    .detach();
  307
  308    cx.on_action(move |_: &workspace::NewFile, cx| {
  309        let app_state = workspace::AppState::global(cx);
  310        if let Some(app_state) = app_state.upgrade() {
  311            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  312                Editor::new_file(workspace, &Default::default(), cx)
  313            })
  314            .detach();
  315        }
  316    });
  317    cx.on_action(move |_: &workspace::NewWindow, cx| {
  318        let app_state = workspace::AppState::global(cx);
  319        if let Some(app_state) = app_state.upgrade() {
  320            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  321                Editor::new_file(workspace, &Default::default(), cx)
  322            })
  323            .detach();
  324        }
  325    });
  326}
  327
  328pub struct SearchWithinRange;
  329
  330trait InvalidationRegion {
  331    fn ranges(&self) -> &[Range<Anchor>];
  332}
  333
  334#[derive(Clone, Debug, PartialEq)]
  335pub enum SelectPhase {
  336    Begin {
  337        position: DisplayPoint,
  338        add: bool,
  339        click_count: usize,
  340    },
  341    BeginColumnar {
  342        position: DisplayPoint,
  343        reset: bool,
  344        goal_column: u32,
  345    },
  346    Extend {
  347        position: DisplayPoint,
  348        click_count: usize,
  349    },
  350    Update {
  351        position: DisplayPoint,
  352        goal_column: u32,
  353        scroll_delta: gpui::Point<f32>,
  354    },
  355    End,
  356}
  357
  358#[derive(Clone, Debug)]
  359pub enum SelectMode {
  360    Character,
  361    Word(Range<Anchor>),
  362    Line(Range<Anchor>),
  363    All,
  364}
  365
  366#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  367pub enum EditorMode {
  368    SingleLine { auto_width: bool },
  369    AutoHeight { max_lines: usize },
  370    Full,
  371}
  372
  373#[derive(Clone, Debug)]
  374pub enum SoftWrap {
  375    None,
  376    PreferLine,
  377    EditorWidth,
  378    Column(u32),
  379    Bounded(u32),
  380}
  381
  382#[derive(Clone)]
  383pub struct EditorStyle {
  384    pub background: Hsla,
  385    pub local_player: PlayerColor,
  386    pub text: TextStyle,
  387    pub scrollbar_width: Pixels,
  388    pub syntax: Arc<SyntaxTheme>,
  389    pub status: StatusColors,
  390    pub inlay_hints_style: HighlightStyle,
  391    pub suggestions_style: HighlightStyle,
  392    pub unnecessary_code_fade: f32,
  393}
  394
  395impl Default for EditorStyle {
  396    fn default() -> Self {
  397        Self {
  398            background: Hsla::default(),
  399            local_player: PlayerColor::default(),
  400            text: TextStyle::default(),
  401            scrollbar_width: Pixels::default(),
  402            syntax: Default::default(),
  403            // HACK: Status colors don't have a real default.
  404            // We should look into removing the status colors from the editor
  405            // style and retrieve them directly from the theme.
  406            status: StatusColors::dark(),
  407            inlay_hints_style: HighlightStyle::default(),
  408            suggestions_style: HighlightStyle::default(),
  409            unnecessary_code_fade: Default::default(),
  410        }
  411    }
  412}
  413
  414type CompletionId = usize;
  415
  416#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  417struct EditorActionId(usize);
  418
  419impl EditorActionId {
  420    pub fn post_inc(&mut self) -> Self {
  421        let answer = self.0;
  422
  423        *self = Self(answer + 1);
  424
  425        Self(answer)
  426    }
  427}
  428
  429// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  430// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  431
  432type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  433type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  434
  435#[derive(Default)]
  436struct ScrollbarMarkerState {
  437    scrollbar_size: Size<Pixels>,
  438    dirty: bool,
  439    markers: Arc<[PaintQuad]>,
  440    pending_refresh: Option<Task<Result<()>>>,
  441}
  442
  443impl ScrollbarMarkerState {
  444    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  445        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  446    }
  447}
  448
  449#[derive(Clone, Debug)]
  450struct RunnableTasks {
  451    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  452    offset: MultiBufferOffset,
  453    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  454    column: u32,
  455    // Values of all named captures, including those starting with '_'
  456    extra_variables: HashMap<String, String>,
  457    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  458    context_range: Range<BufferOffset>,
  459}
  460
  461#[derive(Clone)]
  462struct ResolvedTasks {
  463    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  464    position: Anchor,
  465}
  466#[derive(Copy, Clone, Debug)]
  467struct MultiBufferOffset(usize);
  468#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  469struct BufferOffset(usize);
  470
  471// Addons allow storing per-editor state in other crates (e.g. Vim)
  472pub trait Addon: 'static {
  473    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  474
  475    fn to_any(&self) -> &dyn std::any::Any;
  476}
  477
  478/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  479///
  480/// See the [module level documentation](self) for more information.
  481pub struct Editor {
  482    focus_handle: FocusHandle,
  483    last_focused_descendant: Option<WeakFocusHandle>,
  484    /// The text buffer being edited
  485    buffer: Model<MultiBuffer>,
  486    /// Map of how text in the buffer should be displayed.
  487    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  488    pub display_map: Model<DisplayMap>,
  489    pub selections: SelectionsCollection,
  490    pub scroll_manager: ScrollManager,
  491    /// When inline assist editors are linked, they all render cursors because
  492    /// typing enters text into each of them, even the ones that aren't focused.
  493    pub(crate) show_cursor_when_unfocused: bool,
  494    columnar_selection_tail: Option<Anchor>,
  495    add_selections_state: Option<AddSelectionsState>,
  496    select_next_state: Option<SelectNextState>,
  497    select_prev_state: Option<SelectNextState>,
  498    selection_history: SelectionHistory,
  499    autoclose_regions: Vec<AutocloseRegion>,
  500    snippet_stack: InvalidationStack<SnippetState>,
  501    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  502    ime_transaction: Option<TransactionId>,
  503    active_diagnostics: Option<ActiveDiagnosticGroup>,
  504    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  505    project: Option<Model<Project>>,
  506    completion_provider: Option<Box<dyn CompletionProvider>>,
  507    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  508    blink_manager: Model<BlinkManager>,
  509    show_cursor_names: bool,
  510    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  511    pub show_local_selections: bool,
  512    mode: EditorMode,
  513    show_breadcrumbs: bool,
  514    show_gutter: bool,
  515    show_line_numbers: Option<bool>,
  516    use_relative_line_numbers: Option<bool>,
  517    show_git_diff_gutter: Option<bool>,
  518    show_code_actions: Option<bool>,
  519    show_runnables: Option<bool>,
  520    show_wrap_guides: Option<bool>,
  521    show_indent_guides: Option<bool>,
  522    placeholder_text: Option<Arc<str>>,
  523    highlight_order: usize,
  524    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  525    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  526    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  527    scrollbar_marker_state: ScrollbarMarkerState,
  528    active_indent_guides_state: ActiveIndentGuidesState,
  529    nav_history: Option<ItemNavHistory>,
  530    context_menu: RwLock<Option<ContextMenu>>,
  531    mouse_context_menu: Option<MouseContextMenu>,
  532    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  533    signature_help_state: SignatureHelpState,
  534    auto_signature_help: Option<bool>,
  535    find_all_references_task_sources: Vec<Anchor>,
  536    next_completion_id: CompletionId,
  537    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  538    available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
  539    code_actions_task: Option<Task<()>>,
  540    document_highlights_task: Option<Task<()>>,
  541    linked_editing_range_task: Option<Task<Option<()>>>,
  542    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  543    pending_rename: Option<RenameState>,
  544    searchable: bool,
  545    cursor_shape: CursorShape,
  546    current_line_highlight: Option<CurrentLineHighlight>,
  547    collapse_matches: bool,
  548    autoindent_mode: Option<AutoindentMode>,
  549    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  550    input_enabled: bool,
  551    use_modal_editing: bool,
  552    read_only: bool,
  553    leader_peer_id: Option<PeerId>,
  554    remote_id: Option<ViewId>,
  555    hover_state: HoverState,
  556    gutter_hovered: bool,
  557    hovered_link_state: Option<HoveredLinkState>,
  558    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  559    active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
  560    // enable_inline_completions is a switch that Vim can use to disable
  561    // inline completions based on its mode.
  562    enable_inline_completions: bool,
  563    show_inline_completions_override: Option<bool>,
  564    inlay_hint_cache: InlayHintCache,
  565    expanded_hunks: ExpandedHunks,
  566    next_inlay_id: usize,
  567    _subscriptions: Vec<Subscription>,
  568    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  569    gutter_dimensions: GutterDimensions,
  570    style: Option<EditorStyle>,
  571    next_editor_action_id: EditorActionId,
  572    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  573    use_autoclose: bool,
  574    use_auto_surround: bool,
  575    auto_replace_emoji_shortcode: bool,
  576    show_git_blame_gutter: bool,
  577    show_git_blame_inline: bool,
  578    show_git_blame_inline_delay_task: Option<Task<()>>,
  579    git_blame_inline_enabled: bool,
  580    serialize_dirty_buffers: bool,
  581    show_selection_menu: Option<bool>,
  582    blame: Option<Model<GitBlame>>,
  583    blame_subscription: Option<Subscription>,
  584    custom_context_menu: Option<
  585        Box<
  586            dyn 'static
  587                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  588        >,
  589    >,
  590    last_bounds: Option<Bounds<Pixels>>,
  591    expect_bounds_change: Option<Bounds<Pixels>>,
  592    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  593    tasks_update_task: Option<Task<()>>,
  594    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  595    file_header_size: u32,
  596    breadcrumb_header: Option<String>,
  597    focused_block: Option<FocusedBlock>,
  598    next_scroll_position: NextScrollCursorCenterTopBottom,
  599    addons: HashMap<TypeId, Box<dyn Addon>>,
  600    _scroll_cursor_center_top_bottom_task: Task<()>,
  601}
  602
  603#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  604enum NextScrollCursorCenterTopBottom {
  605    #[default]
  606    Center,
  607    Top,
  608    Bottom,
  609}
  610
  611impl NextScrollCursorCenterTopBottom {
  612    fn next(&self) -> Self {
  613        match self {
  614            Self::Center => Self::Top,
  615            Self::Top => Self::Bottom,
  616            Self::Bottom => Self::Center,
  617        }
  618    }
  619}
  620
  621#[derive(Clone)]
  622pub struct EditorSnapshot {
  623    pub mode: EditorMode,
  624    show_gutter: bool,
  625    show_line_numbers: Option<bool>,
  626    show_git_diff_gutter: Option<bool>,
  627    show_code_actions: Option<bool>,
  628    show_runnables: Option<bool>,
  629    render_git_blame_gutter: bool,
  630    pub display_snapshot: DisplaySnapshot,
  631    pub placeholder_text: Option<Arc<str>>,
  632    is_focused: bool,
  633    scroll_anchor: ScrollAnchor,
  634    ongoing_scroll: OngoingScroll,
  635    current_line_highlight: CurrentLineHighlight,
  636    gutter_hovered: bool,
  637}
  638
  639const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
  640
  641#[derive(Default, Debug, Clone, Copy)]
  642pub struct GutterDimensions {
  643    pub left_padding: Pixels,
  644    pub right_padding: Pixels,
  645    pub width: Pixels,
  646    pub margin: Pixels,
  647    pub git_blame_entries_width: Option<Pixels>,
  648}
  649
  650impl GutterDimensions {
  651    /// The full width of the space taken up by the gutter.
  652    pub fn full_width(&self) -> Pixels {
  653        self.margin + self.width
  654    }
  655
  656    /// The width of the space reserved for the fold indicators,
  657    /// use alongside 'justify_end' and `gutter_width` to
  658    /// right align content with the line numbers
  659    pub fn fold_area_width(&self) -> Pixels {
  660        self.margin + self.right_padding
  661    }
  662}
  663
  664#[derive(Debug)]
  665pub struct RemoteSelection {
  666    pub replica_id: ReplicaId,
  667    pub selection: Selection<Anchor>,
  668    pub cursor_shape: CursorShape,
  669    pub peer_id: PeerId,
  670    pub line_mode: bool,
  671    pub participant_index: Option<ParticipantIndex>,
  672    pub user_name: Option<SharedString>,
  673}
  674
  675#[derive(Clone, Debug)]
  676struct SelectionHistoryEntry {
  677    selections: Arc<[Selection<Anchor>]>,
  678    select_next_state: Option<SelectNextState>,
  679    select_prev_state: Option<SelectNextState>,
  680    add_selections_state: Option<AddSelectionsState>,
  681}
  682
  683enum SelectionHistoryMode {
  684    Normal,
  685    Undoing,
  686    Redoing,
  687}
  688
  689#[derive(Clone, PartialEq, Eq, Hash)]
  690struct HoveredCursor {
  691    replica_id: u16,
  692    selection_id: usize,
  693}
  694
  695impl Default for SelectionHistoryMode {
  696    fn default() -> Self {
  697        Self::Normal
  698    }
  699}
  700
  701#[derive(Default)]
  702struct SelectionHistory {
  703    #[allow(clippy::type_complexity)]
  704    selections_by_transaction:
  705        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  706    mode: SelectionHistoryMode,
  707    undo_stack: VecDeque<SelectionHistoryEntry>,
  708    redo_stack: VecDeque<SelectionHistoryEntry>,
  709}
  710
  711impl SelectionHistory {
  712    fn insert_transaction(
  713        &mut self,
  714        transaction_id: TransactionId,
  715        selections: Arc<[Selection<Anchor>]>,
  716    ) {
  717        self.selections_by_transaction
  718            .insert(transaction_id, (selections, None));
  719    }
  720
  721    #[allow(clippy::type_complexity)]
  722    fn transaction(
  723        &self,
  724        transaction_id: TransactionId,
  725    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  726        self.selections_by_transaction.get(&transaction_id)
  727    }
  728
  729    #[allow(clippy::type_complexity)]
  730    fn transaction_mut(
  731        &mut self,
  732        transaction_id: TransactionId,
  733    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  734        self.selections_by_transaction.get_mut(&transaction_id)
  735    }
  736
  737    fn push(&mut self, entry: SelectionHistoryEntry) {
  738        if !entry.selections.is_empty() {
  739            match self.mode {
  740                SelectionHistoryMode::Normal => {
  741                    self.push_undo(entry);
  742                    self.redo_stack.clear();
  743                }
  744                SelectionHistoryMode::Undoing => self.push_redo(entry),
  745                SelectionHistoryMode::Redoing => self.push_undo(entry),
  746            }
  747        }
  748    }
  749
  750    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  751        if self
  752            .undo_stack
  753            .back()
  754            .map_or(true, |e| e.selections != entry.selections)
  755        {
  756            self.undo_stack.push_back(entry);
  757            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  758                self.undo_stack.pop_front();
  759            }
  760        }
  761    }
  762
  763    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  764        if self
  765            .redo_stack
  766            .back()
  767            .map_or(true, |e| e.selections != entry.selections)
  768        {
  769            self.redo_stack.push_back(entry);
  770            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  771                self.redo_stack.pop_front();
  772            }
  773        }
  774    }
  775}
  776
  777struct RowHighlight {
  778    index: usize,
  779    range: RangeInclusive<Anchor>,
  780    color: Option<Hsla>,
  781    should_autoscroll: bool,
  782}
  783
  784#[derive(Clone, Debug)]
  785struct AddSelectionsState {
  786    above: bool,
  787    stack: Vec<usize>,
  788}
  789
  790#[derive(Clone)]
  791struct SelectNextState {
  792    query: AhoCorasick,
  793    wordwise: bool,
  794    done: bool,
  795}
  796
  797impl std::fmt::Debug for SelectNextState {
  798    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  799        f.debug_struct(std::any::type_name::<Self>())
  800            .field("wordwise", &self.wordwise)
  801            .field("done", &self.done)
  802            .finish()
  803    }
  804}
  805
  806#[derive(Debug)]
  807struct AutocloseRegion {
  808    selection_id: usize,
  809    range: Range<Anchor>,
  810    pair: BracketPair,
  811}
  812
  813#[derive(Debug)]
  814struct SnippetState {
  815    ranges: Vec<Vec<Range<Anchor>>>,
  816    active_index: usize,
  817}
  818
  819#[doc(hidden)]
  820pub struct RenameState {
  821    pub range: Range<Anchor>,
  822    pub old_name: Arc<str>,
  823    pub editor: View<Editor>,
  824    block_id: CustomBlockId,
  825}
  826
  827struct InvalidationStack<T>(Vec<T>);
  828
  829struct RegisteredInlineCompletionProvider {
  830    provider: Arc<dyn InlineCompletionProviderHandle>,
  831    _subscription: Subscription,
  832}
  833
  834enum ContextMenu {
  835    Completions(CompletionsMenu),
  836    CodeActions(CodeActionsMenu),
  837}
  838
  839impl ContextMenu {
  840    fn select_first(
  841        &mut self,
  842        project: Option<&Model<Project>>,
  843        cx: &mut ViewContext<Editor>,
  844    ) -> bool {
  845        if self.visible() {
  846            match self {
  847                ContextMenu::Completions(menu) => menu.select_first(project, cx),
  848                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  849            }
  850            true
  851        } else {
  852            false
  853        }
  854    }
  855
  856    fn select_prev(
  857        &mut self,
  858        project: Option<&Model<Project>>,
  859        cx: &mut ViewContext<Editor>,
  860    ) -> bool {
  861        if self.visible() {
  862            match self {
  863                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
  864                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  865            }
  866            true
  867        } else {
  868            false
  869        }
  870    }
  871
  872    fn select_next(
  873        &mut self,
  874        project: Option<&Model<Project>>,
  875        cx: &mut ViewContext<Editor>,
  876    ) -> bool {
  877        if self.visible() {
  878            match self {
  879                ContextMenu::Completions(menu) => menu.select_next(project, cx),
  880                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  881            }
  882            true
  883        } else {
  884            false
  885        }
  886    }
  887
  888    fn select_last(
  889        &mut self,
  890        project: Option<&Model<Project>>,
  891        cx: &mut ViewContext<Editor>,
  892    ) -> bool {
  893        if self.visible() {
  894            match self {
  895                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  896                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  897            }
  898            true
  899        } else {
  900            false
  901        }
  902    }
  903
  904    fn visible(&self) -> bool {
  905        match self {
  906            ContextMenu::Completions(menu) => menu.visible(),
  907            ContextMenu::CodeActions(menu) => menu.visible(),
  908        }
  909    }
  910
  911    fn render(
  912        &self,
  913        cursor_position: DisplayPoint,
  914        style: &EditorStyle,
  915        max_height: Pixels,
  916        workspace: Option<WeakView<Workspace>>,
  917        cx: &mut ViewContext<Editor>,
  918    ) -> (ContextMenuOrigin, AnyElement) {
  919        match self {
  920            ContextMenu::Completions(menu) => (
  921                ContextMenuOrigin::EditorPoint(cursor_position),
  922                menu.render(style, max_height, workspace, cx),
  923            ),
  924            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  925        }
  926    }
  927}
  928
  929enum ContextMenuOrigin {
  930    EditorPoint(DisplayPoint),
  931    GutterIndicator(DisplayRow),
  932}
  933
  934#[derive(Clone)]
  935struct CompletionsMenu {
  936    id: CompletionId,
  937    sort_completions: bool,
  938    initial_position: Anchor,
  939    buffer: Model<Buffer>,
  940    completions: Arc<RwLock<Box<[Completion]>>>,
  941    match_candidates: Arc<[StringMatchCandidate]>,
  942    matches: Arc<[StringMatch]>,
  943    selected_item: usize,
  944    scroll_handle: UniformListScrollHandle,
  945    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  946}
  947
  948impl CompletionsMenu {
  949    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  950        self.selected_item = 0;
  951        self.scroll_handle.scroll_to_item(self.selected_item);
  952        self.attempt_resolve_selected_completion_documentation(project, cx);
  953        cx.notify();
  954    }
  955
  956    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  957        if self.selected_item > 0 {
  958            self.selected_item -= 1;
  959        } else {
  960            self.selected_item = self.matches.len() - 1;
  961        }
  962        self.scroll_handle.scroll_to_item(self.selected_item);
  963        self.attempt_resolve_selected_completion_documentation(project, cx);
  964        cx.notify();
  965    }
  966
  967    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  968        if self.selected_item + 1 < self.matches.len() {
  969            self.selected_item += 1;
  970        } else {
  971            self.selected_item = 0;
  972        }
  973        self.scroll_handle.scroll_to_item(self.selected_item);
  974        self.attempt_resolve_selected_completion_documentation(project, cx);
  975        cx.notify();
  976    }
  977
  978    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  979        self.selected_item = self.matches.len() - 1;
  980        self.scroll_handle.scroll_to_item(self.selected_item);
  981        self.attempt_resolve_selected_completion_documentation(project, cx);
  982        cx.notify();
  983    }
  984
  985    fn pre_resolve_completion_documentation(
  986        buffer: Model<Buffer>,
  987        completions: Arc<RwLock<Box<[Completion]>>>,
  988        matches: Arc<[StringMatch]>,
  989        editor: &Editor,
  990        cx: &mut ViewContext<Editor>,
  991    ) -> Task<()> {
  992        let settings = EditorSettings::get_global(cx);
  993        if !settings.show_completion_documentation {
  994            return Task::ready(());
  995        }
  996
  997        let Some(provider) = editor.completion_provider.as_ref() else {
  998            return Task::ready(());
  999        };
 1000
 1001        let resolve_task = provider.resolve_completions(
 1002            buffer,
 1003            matches.iter().map(|m| m.candidate_id).collect(),
 1004            completions.clone(),
 1005            cx,
 1006        );
 1007
 1008        cx.spawn(move |this, mut cx| async move {
 1009            if let Some(true) = resolve_task.await.log_err() {
 1010                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1011            }
 1012        })
 1013    }
 1014
 1015    fn attempt_resolve_selected_completion_documentation(
 1016        &mut self,
 1017        project: Option<&Model<Project>>,
 1018        cx: &mut ViewContext<Editor>,
 1019    ) {
 1020        let settings = EditorSettings::get_global(cx);
 1021        if !settings.show_completion_documentation {
 1022            return;
 1023        }
 1024
 1025        let completion_index = self.matches[self.selected_item].candidate_id;
 1026        let Some(project) = project else {
 1027            return;
 1028        };
 1029
 1030        let resolve_task = project.update(cx, |project, cx| {
 1031            project.resolve_completions(
 1032                self.buffer.clone(),
 1033                vec![completion_index],
 1034                self.completions.clone(),
 1035                cx,
 1036            )
 1037        });
 1038
 1039        let delay_ms =
 1040            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1041        let delay = Duration::from_millis(delay_ms);
 1042
 1043        self.selected_completion_documentation_resolve_debounce
 1044            .lock()
 1045            .fire_new(delay, cx, |_, cx| {
 1046                cx.spawn(move |this, mut cx| async move {
 1047                    if let Some(true) = resolve_task.await.log_err() {
 1048                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1049                    }
 1050                })
 1051            });
 1052    }
 1053
 1054    fn visible(&self) -> bool {
 1055        !self.matches.is_empty()
 1056    }
 1057
 1058    fn render(
 1059        &self,
 1060        style: &EditorStyle,
 1061        max_height: Pixels,
 1062        workspace: Option<WeakView<Workspace>>,
 1063        cx: &mut ViewContext<Editor>,
 1064    ) -> AnyElement {
 1065        let settings = EditorSettings::get_global(cx);
 1066        let show_completion_documentation = settings.show_completion_documentation;
 1067
 1068        let widest_completion_ix = self
 1069            .matches
 1070            .iter()
 1071            .enumerate()
 1072            .max_by_key(|(_, mat)| {
 1073                let completions = self.completions.read();
 1074                let completion = &completions[mat.candidate_id];
 1075                let documentation = &completion.documentation;
 1076
 1077                let mut len = completion.label.text.chars().count();
 1078                if let Some(Documentation::SingleLine(text)) = documentation {
 1079                    if show_completion_documentation {
 1080                        len += text.chars().count();
 1081                    }
 1082                }
 1083
 1084                len
 1085            })
 1086            .map(|(ix, _)| ix);
 1087
 1088        let completions = self.completions.clone();
 1089        let matches = self.matches.clone();
 1090        let selected_item = self.selected_item;
 1091        let style = style.clone();
 1092
 1093        let multiline_docs = if show_completion_documentation {
 1094            let mat = &self.matches[selected_item];
 1095            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1096                Some(Documentation::MultiLinePlainText(text)) => {
 1097                    Some(div().child(SharedString::from(text.clone())))
 1098                }
 1099                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1100                    Some(div().child(render_parsed_markdown(
 1101                        "completions_markdown",
 1102                        parsed,
 1103                        &style,
 1104                        workspace,
 1105                        cx,
 1106                    )))
 1107                }
 1108                _ => None,
 1109            };
 1110            multiline_docs.map(|div| {
 1111                div.id("multiline_docs")
 1112                    .max_h(max_height)
 1113                    .flex_1()
 1114                    .px_1p5()
 1115                    .py_1()
 1116                    .min_w(px(260.))
 1117                    .max_w(px(640.))
 1118                    .w(px(500.))
 1119                    .overflow_y_scroll()
 1120                    .occlude()
 1121            })
 1122        } else {
 1123            None
 1124        };
 1125
 1126        let list = uniform_list(
 1127            cx.view().clone(),
 1128            "completions",
 1129            matches.len(),
 1130            move |_editor, range, cx| {
 1131                let start_ix = range.start;
 1132                let completions_guard = completions.read();
 1133
 1134                matches[range]
 1135                    .iter()
 1136                    .enumerate()
 1137                    .map(|(ix, mat)| {
 1138                        let item_ix = start_ix + ix;
 1139                        let candidate_id = mat.candidate_id;
 1140                        let completion = &completions_guard[candidate_id];
 1141
 1142                        let documentation = if show_completion_documentation {
 1143                            &completion.documentation
 1144                        } else {
 1145                            &None
 1146                        };
 1147
 1148                        let highlights = gpui::combine_highlights(
 1149                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1150                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1151                                |(range, mut highlight)| {
 1152                                    // Ignore font weight for syntax highlighting, as we'll use it
 1153                                    // for fuzzy matches.
 1154                                    highlight.font_weight = None;
 1155
 1156                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1157                                        highlight.strikethrough = Some(StrikethroughStyle {
 1158                                            thickness: 1.0.into(),
 1159                                            ..Default::default()
 1160                                        });
 1161                                        highlight.color = Some(cx.theme().colors().text_muted);
 1162                                    }
 1163
 1164                                    (range, highlight)
 1165                                },
 1166                            ),
 1167                        );
 1168                        let completion_label = StyledText::new(completion.label.text.clone())
 1169                            .with_highlights(&style.text, highlights);
 1170                        let documentation_label =
 1171                            if let Some(Documentation::SingleLine(text)) = documentation {
 1172                                if text.trim().is_empty() {
 1173                                    None
 1174                                } else {
 1175                                    Some(
 1176                                        Label::new(text.clone())
 1177                                            .ml_4()
 1178                                            .size(LabelSize::Small)
 1179                                            .color(Color::Muted),
 1180                                    )
 1181                                }
 1182                            } else {
 1183                                None
 1184                            };
 1185
 1186                        div().min_w(px(220.)).max_w(px(540.)).child(
 1187                            ListItem::new(mat.candidate_id)
 1188                                .inset(true)
 1189                                .selected(item_ix == selected_item)
 1190                                .on_click(cx.listener(move |editor, _event, cx| {
 1191                                    cx.stop_propagation();
 1192                                    if let Some(task) = editor.confirm_completion(
 1193                                        &ConfirmCompletion {
 1194                                            item_ix: Some(item_ix),
 1195                                        },
 1196                                        cx,
 1197                                    ) {
 1198                                        task.detach_and_log_err(cx)
 1199                                    }
 1200                                }))
 1201                                .child(h_flex().overflow_hidden().child(completion_label))
 1202                                .end_slot::<Label>(documentation_label),
 1203                        )
 1204                    })
 1205                    .collect()
 1206            },
 1207        )
 1208        .occlude()
 1209        .max_h(max_height)
 1210        .track_scroll(self.scroll_handle.clone())
 1211        .with_width_from_item(widest_completion_ix)
 1212        .with_sizing_behavior(ListSizingBehavior::Infer);
 1213
 1214        Popover::new()
 1215            .child(list)
 1216            .when_some(multiline_docs, |popover, multiline_docs| {
 1217                popover.aside(multiline_docs)
 1218            })
 1219            .into_any_element()
 1220    }
 1221
 1222    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1223        let mut matches = if let Some(query) = query {
 1224            fuzzy::match_strings(
 1225                &self.match_candidates,
 1226                query,
 1227                query.chars().any(|c| c.is_uppercase()),
 1228                100,
 1229                &Default::default(),
 1230                executor,
 1231            )
 1232            .await
 1233        } else {
 1234            self.match_candidates
 1235                .iter()
 1236                .enumerate()
 1237                .map(|(candidate_id, candidate)| StringMatch {
 1238                    candidate_id,
 1239                    score: Default::default(),
 1240                    positions: Default::default(),
 1241                    string: candidate.string.clone(),
 1242                })
 1243                .collect()
 1244        };
 1245
 1246        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1247        if let Some(query) = query {
 1248            if let Some(query_start) = query.chars().next() {
 1249                matches.retain(|string_match| {
 1250                    split_words(&string_match.string).any(|word| {
 1251                        // Check that the first codepoint of the word as lowercase matches the first
 1252                        // codepoint of the query as lowercase
 1253                        word.chars()
 1254                            .flat_map(|codepoint| codepoint.to_lowercase())
 1255                            .zip(query_start.to_lowercase())
 1256                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1257                    })
 1258                });
 1259            }
 1260        }
 1261
 1262        let completions = self.completions.read();
 1263        if self.sort_completions {
 1264            matches.sort_unstable_by_key(|mat| {
 1265                // We do want to strike a balance here between what the language server tells us
 1266                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1267                // `Creat` and there is a local variable called `CreateComponent`).
 1268                // So what we do is: we bucket all matches into two buckets
 1269                // - Strong matches
 1270                // - Weak matches
 1271                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1272                // and the Weak matches are the rest.
 1273                //
 1274                // For the strong matches, we sort by the language-servers score first and for the weak
 1275                // matches, we prefer our fuzzy finder first.
 1276                //
 1277                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1278                // us into account when it's obviously a bad match.
 1279
 1280                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1281                enum MatchScore<'a> {
 1282                    Strong {
 1283                        sort_text: Option<&'a str>,
 1284                        score: Reverse<OrderedFloat<f64>>,
 1285                        sort_key: (usize, &'a str),
 1286                    },
 1287                    Weak {
 1288                        score: Reverse<OrderedFloat<f64>>,
 1289                        sort_text: Option<&'a str>,
 1290                        sort_key: (usize, &'a str),
 1291                    },
 1292                }
 1293
 1294                let completion = &completions[mat.candidate_id];
 1295                let sort_key = completion.sort_key();
 1296                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1297                let score = Reverse(OrderedFloat(mat.score));
 1298
 1299                if mat.score >= 0.2 {
 1300                    MatchScore::Strong {
 1301                        sort_text,
 1302                        score,
 1303                        sort_key,
 1304                    }
 1305                } else {
 1306                    MatchScore::Weak {
 1307                        score,
 1308                        sort_text,
 1309                        sort_key,
 1310                    }
 1311                }
 1312            });
 1313        }
 1314
 1315        for mat in &mut matches {
 1316            let completion = &completions[mat.candidate_id];
 1317            mat.string.clone_from(&completion.label.text);
 1318            for position in &mut mat.positions {
 1319                *position += completion.label.filter_range.start;
 1320            }
 1321        }
 1322        drop(completions);
 1323
 1324        self.matches = matches.into();
 1325        self.selected_item = 0;
 1326    }
 1327}
 1328
 1329#[derive(Clone)]
 1330struct CodeActionContents {
 1331    tasks: Option<Arc<ResolvedTasks>>,
 1332    actions: Option<Arc<[CodeAction]>>,
 1333}
 1334
 1335impl CodeActionContents {
 1336    fn len(&self) -> usize {
 1337        match (&self.tasks, &self.actions) {
 1338            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1339            (Some(tasks), None) => tasks.templates.len(),
 1340            (None, Some(actions)) => actions.len(),
 1341            (None, None) => 0,
 1342        }
 1343    }
 1344
 1345    fn is_empty(&self) -> bool {
 1346        match (&self.tasks, &self.actions) {
 1347            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1348            (Some(tasks), None) => tasks.templates.is_empty(),
 1349            (None, Some(actions)) => actions.is_empty(),
 1350            (None, None) => true,
 1351        }
 1352    }
 1353
 1354    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1355        self.tasks
 1356            .iter()
 1357            .flat_map(|tasks| {
 1358                tasks
 1359                    .templates
 1360                    .iter()
 1361                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1362            })
 1363            .chain(self.actions.iter().flat_map(|actions| {
 1364                actions
 1365                    .iter()
 1366                    .map(|action| CodeActionsItem::CodeAction(action.clone()))
 1367            }))
 1368    }
 1369    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1370        match (&self.tasks, &self.actions) {
 1371            (Some(tasks), Some(actions)) => {
 1372                if index < tasks.templates.len() {
 1373                    tasks
 1374                        .templates
 1375                        .get(index)
 1376                        .cloned()
 1377                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1378                } else {
 1379                    actions
 1380                        .get(index - tasks.templates.len())
 1381                        .cloned()
 1382                        .map(CodeActionsItem::CodeAction)
 1383                }
 1384            }
 1385            (Some(tasks), None) => tasks
 1386                .templates
 1387                .get(index)
 1388                .cloned()
 1389                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1390            (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
 1391            (None, None) => None,
 1392        }
 1393    }
 1394}
 1395
 1396#[allow(clippy::large_enum_variant)]
 1397#[derive(Clone)]
 1398enum CodeActionsItem {
 1399    Task(TaskSourceKind, ResolvedTask),
 1400    CodeAction(CodeAction),
 1401}
 1402
 1403impl CodeActionsItem {
 1404    fn as_task(&self) -> Option<&ResolvedTask> {
 1405        let Self::Task(_, task) = self else {
 1406            return None;
 1407        };
 1408        Some(task)
 1409    }
 1410    fn as_code_action(&self) -> Option<&CodeAction> {
 1411        let Self::CodeAction(action) = self else {
 1412            return None;
 1413        };
 1414        Some(action)
 1415    }
 1416    fn label(&self) -> String {
 1417        match self {
 1418            Self::CodeAction(action) => action.lsp_action.title.clone(),
 1419            Self::Task(_, task) => task.resolved_label.clone(),
 1420        }
 1421    }
 1422}
 1423
 1424struct CodeActionsMenu {
 1425    actions: CodeActionContents,
 1426    buffer: Model<Buffer>,
 1427    selected_item: usize,
 1428    scroll_handle: UniformListScrollHandle,
 1429    deployed_from_indicator: Option<DisplayRow>,
 1430}
 1431
 1432impl CodeActionsMenu {
 1433    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1434        self.selected_item = 0;
 1435        self.scroll_handle.scroll_to_item(self.selected_item);
 1436        cx.notify()
 1437    }
 1438
 1439    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1440        if self.selected_item > 0 {
 1441            self.selected_item -= 1;
 1442        } else {
 1443            self.selected_item = self.actions.len() - 1;
 1444        }
 1445        self.scroll_handle.scroll_to_item(self.selected_item);
 1446        cx.notify();
 1447    }
 1448
 1449    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1450        if self.selected_item + 1 < self.actions.len() {
 1451            self.selected_item += 1;
 1452        } else {
 1453            self.selected_item = 0;
 1454        }
 1455        self.scroll_handle.scroll_to_item(self.selected_item);
 1456        cx.notify();
 1457    }
 1458
 1459    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1460        self.selected_item = self.actions.len() - 1;
 1461        self.scroll_handle.scroll_to_item(self.selected_item);
 1462        cx.notify()
 1463    }
 1464
 1465    fn visible(&self) -> bool {
 1466        !self.actions.is_empty()
 1467    }
 1468
 1469    fn render(
 1470        &self,
 1471        cursor_position: DisplayPoint,
 1472        _style: &EditorStyle,
 1473        max_height: Pixels,
 1474        cx: &mut ViewContext<Editor>,
 1475    ) -> (ContextMenuOrigin, AnyElement) {
 1476        let actions = self.actions.clone();
 1477        let selected_item = self.selected_item;
 1478        let element = uniform_list(
 1479            cx.view().clone(),
 1480            "code_actions_menu",
 1481            self.actions.len(),
 1482            move |_this, range, cx| {
 1483                actions
 1484                    .iter()
 1485                    .skip(range.start)
 1486                    .take(range.end - range.start)
 1487                    .enumerate()
 1488                    .map(|(ix, action)| {
 1489                        let item_ix = range.start + ix;
 1490                        let selected = selected_item == item_ix;
 1491                        let colors = cx.theme().colors();
 1492                        div()
 1493                            .px_1()
 1494                            .rounded_md()
 1495                            .text_color(colors.text)
 1496                            .when(selected, |style| {
 1497                                style
 1498                                    .bg(colors.element_active)
 1499                                    .text_color(colors.text_accent)
 1500                            })
 1501                            .hover(|style| {
 1502                                style
 1503                                    .bg(colors.element_hover)
 1504                                    .text_color(colors.text_accent)
 1505                            })
 1506                            .whitespace_nowrap()
 1507                            .when_some(action.as_code_action(), |this, action| {
 1508                                this.on_mouse_down(
 1509                                    MouseButton::Left,
 1510                                    cx.listener(move |editor, _, cx| {
 1511                                        cx.stop_propagation();
 1512                                        if let Some(task) = editor.confirm_code_action(
 1513                                            &ConfirmCodeAction {
 1514                                                item_ix: Some(item_ix),
 1515                                            },
 1516                                            cx,
 1517                                        ) {
 1518                                            task.detach_and_log_err(cx)
 1519                                        }
 1520                                    }),
 1521                                )
 1522                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1523                                .child(SharedString::from(action.lsp_action.title.clone()))
 1524                            })
 1525                            .when_some(action.as_task(), |this, task| {
 1526                                this.on_mouse_down(
 1527                                    MouseButton::Left,
 1528                                    cx.listener(move |editor, _, cx| {
 1529                                        cx.stop_propagation();
 1530                                        if let Some(task) = editor.confirm_code_action(
 1531                                            &ConfirmCodeAction {
 1532                                                item_ix: Some(item_ix),
 1533                                            },
 1534                                            cx,
 1535                                        ) {
 1536                                            task.detach_and_log_err(cx)
 1537                                        }
 1538                                    }),
 1539                                )
 1540                                .child(SharedString::from(task.resolved_label.clone()))
 1541                            })
 1542                    })
 1543                    .collect()
 1544            },
 1545        )
 1546        .elevation_1(cx)
 1547        .p_1()
 1548        .max_h(max_height)
 1549        .occlude()
 1550        .track_scroll(self.scroll_handle.clone())
 1551        .with_width_from_item(
 1552            self.actions
 1553                .iter()
 1554                .enumerate()
 1555                .max_by_key(|(_, action)| match action {
 1556                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1557                    CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
 1558                })
 1559                .map(|(ix, _)| ix),
 1560        )
 1561        .with_sizing_behavior(ListSizingBehavior::Infer)
 1562        .into_any_element();
 1563
 1564        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1565            ContextMenuOrigin::GutterIndicator(row)
 1566        } else {
 1567            ContextMenuOrigin::EditorPoint(cursor_position)
 1568        };
 1569
 1570        (cursor_position, element)
 1571    }
 1572}
 1573
 1574#[derive(Debug)]
 1575struct ActiveDiagnosticGroup {
 1576    primary_range: Range<Anchor>,
 1577    primary_message: String,
 1578    group_id: usize,
 1579    blocks: HashMap<CustomBlockId, Diagnostic>,
 1580    is_valid: bool,
 1581}
 1582
 1583#[derive(Serialize, Deserialize, Clone, Debug)]
 1584pub struct ClipboardSelection {
 1585    pub len: usize,
 1586    pub is_entire_line: bool,
 1587    pub first_line_indent: u32,
 1588}
 1589
 1590#[derive(Debug)]
 1591pub(crate) struct NavigationData {
 1592    cursor_anchor: Anchor,
 1593    cursor_position: Point,
 1594    scroll_anchor: ScrollAnchor,
 1595    scroll_top_row: u32,
 1596}
 1597
 1598#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1599enum GotoDefinitionKind {
 1600    Symbol,
 1601    Declaration,
 1602    Type,
 1603    Implementation,
 1604}
 1605
 1606#[derive(Debug, Clone)]
 1607enum InlayHintRefreshReason {
 1608    Toggle(bool),
 1609    SettingsChange(InlayHintSettings),
 1610    NewLinesShown,
 1611    BufferEdited(HashSet<Arc<Language>>),
 1612    RefreshRequested,
 1613    ExcerptsRemoved(Vec<ExcerptId>),
 1614}
 1615
 1616impl InlayHintRefreshReason {
 1617    fn description(&self) -> &'static str {
 1618        match self {
 1619            Self::Toggle(_) => "toggle",
 1620            Self::SettingsChange(_) => "settings change",
 1621            Self::NewLinesShown => "new lines shown",
 1622            Self::BufferEdited(_) => "buffer edited",
 1623            Self::RefreshRequested => "refresh requested",
 1624            Self::ExcerptsRemoved(_) => "excerpts removed",
 1625        }
 1626    }
 1627}
 1628
 1629pub(crate) struct FocusedBlock {
 1630    id: BlockId,
 1631    focus_handle: WeakFocusHandle,
 1632}
 1633
 1634impl Editor {
 1635    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1636        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1637        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1638        Self::new(
 1639            EditorMode::SingleLine { auto_width: false },
 1640            buffer,
 1641            None,
 1642            false,
 1643            cx,
 1644        )
 1645    }
 1646
 1647    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1648        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1649        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1650        Self::new(EditorMode::Full, buffer, None, false, cx)
 1651    }
 1652
 1653    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1654        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1655        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1656        Self::new(
 1657            EditorMode::SingleLine { auto_width: true },
 1658            buffer,
 1659            None,
 1660            false,
 1661            cx,
 1662        )
 1663    }
 1664
 1665    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1666        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1667        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1668        Self::new(
 1669            EditorMode::AutoHeight { max_lines },
 1670            buffer,
 1671            None,
 1672            false,
 1673            cx,
 1674        )
 1675    }
 1676
 1677    pub fn for_buffer(
 1678        buffer: Model<Buffer>,
 1679        project: Option<Model<Project>>,
 1680        cx: &mut ViewContext<Self>,
 1681    ) -> Self {
 1682        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1683        Self::new(EditorMode::Full, buffer, project, false, cx)
 1684    }
 1685
 1686    pub fn for_multibuffer(
 1687        buffer: Model<MultiBuffer>,
 1688        project: Option<Model<Project>>,
 1689        show_excerpt_controls: bool,
 1690        cx: &mut ViewContext<Self>,
 1691    ) -> Self {
 1692        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1693    }
 1694
 1695    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1696        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1697        let mut clone = Self::new(
 1698            self.mode,
 1699            self.buffer.clone(),
 1700            self.project.clone(),
 1701            show_excerpt_controls,
 1702            cx,
 1703        );
 1704        self.display_map.update(cx, |display_map, cx| {
 1705            let snapshot = display_map.snapshot(cx);
 1706            clone.display_map.update(cx, |display_map, cx| {
 1707                display_map.set_state(&snapshot, cx);
 1708            });
 1709        });
 1710        clone.selections.clone_state(&self.selections);
 1711        clone.scroll_manager.clone_state(&self.scroll_manager);
 1712        clone.searchable = self.searchable;
 1713        clone
 1714    }
 1715
 1716    pub fn new(
 1717        mode: EditorMode,
 1718        buffer: Model<MultiBuffer>,
 1719        project: Option<Model<Project>>,
 1720        show_excerpt_controls: bool,
 1721        cx: &mut ViewContext<Self>,
 1722    ) -> Self {
 1723        let style = cx.text_style();
 1724        let font_size = style.font_size.to_pixels(cx.rem_size());
 1725        let editor = cx.view().downgrade();
 1726        let fold_placeholder = FoldPlaceholder {
 1727            constrain_width: true,
 1728            render: Arc::new(move |fold_id, fold_range, cx| {
 1729                let editor = editor.clone();
 1730                div()
 1731                    .id(fold_id)
 1732                    .bg(cx.theme().colors().ghost_element_background)
 1733                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1734                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1735                    .rounded_sm()
 1736                    .size_full()
 1737                    .cursor_pointer()
 1738                    .child("")
 1739                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1740                    .on_click(move |_, cx| {
 1741                        editor
 1742                            .update(cx, |editor, cx| {
 1743                                editor.unfold_ranges(
 1744                                    [fold_range.start..fold_range.end],
 1745                                    true,
 1746                                    false,
 1747                                    cx,
 1748                                );
 1749                                cx.stop_propagation();
 1750                            })
 1751                            .ok();
 1752                    })
 1753                    .into_any()
 1754            }),
 1755            merge_adjacent: true,
 1756        };
 1757        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1758        let display_map = cx.new_model(|cx| {
 1759            DisplayMap::new(
 1760                buffer.clone(),
 1761                style.font(),
 1762                font_size,
 1763                None,
 1764                show_excerpt_controls,
 1765                file_header_size,
 1766                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1767                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1768                fold_placeholder,
 1769                cx,
 1770            )
 1771        });
 1772
 1773        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1774
 1775        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1776
 1777        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1778            .then(|| language_settings::SoftWrap::PreferLine);
 1779
 1780        let mut project_subscriptions = Vec::new();
 1781        if mode == EditorMode::Full {
 1782            if let Some(project) = project.as_ref() {
 1783                if buffer.read(cx).is_singleton() {
 1784                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1785                        cx.emit(EditorEvent::TitleChanged);
 1786                    }));
 1787                }
 1788                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1789                    if let project::Event::RefreshInlayHints = event {
 1790                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1791                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1792                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1793                            let focus_handle = editor.focus_handle(cx);
 1794                            if focus_handle.is_focused(cx) {
 1795                                let snapshot = buffer.read(cx).snapshot();
 1796                                for (range, snippet) in snippet_edits {
 1797                                    let editor_range =
 1798                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1799                                    editor
 1800                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1801                                        .ok();
 1802                                }
 1803                            }
 1804                        }
 1805                    }
 1806                }));
 1807                let task_inventory = project.read(cx).task_inventory().clone();
 1808                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1809                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1810                }));
 1811            }
 1812        }
 1813
 1814        let inlay_hint_settings = inlay_hint_settings(
 1815            selections.newest_anchor().head(),
 1816            &buffer.read(cx).snapshot(cx),
 1817            cx,
 1818        );
 1819        let focus_handle = cx.focus_handle();
 1820        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1821        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1822            .detach();
 1823        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1824            .detach();
 1825        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1826
 1827        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1828            Some(false)
 1829        } else {
 1830            None
 1831        };
 1832
 1833        let mut this = Self {
 1834            focus_handle,
 1835            show_cursor_when_unfocused: false,
 1836            last_focused_descendant: None,
 1837            buffer: buffer.clone(),
 1838            display_map: display_map.clone(),
 1839            selections,
 1840            scroll_manager: ScrollManager::new(cx),
 1841            columnar_selection_tail: None,
 1842            add_selections_state: None,
 1843            select_next_state: None,
 1844            select_prev_state: None,
 1845            selection_history: Default::default(),
 1846            autoclose_regions: Default::default(),
 1847            snippet_stack: Default::default(),
 1848            select_larger_syntax_node_stack: Vec::new(),
 1849            ime_transaction: Default::default(),
 1850            active_diagnostics: None,
 1851            soft_wrap_mode_override,
 1852            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1853            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1854            project,
 1855            blink_manager: blink_manager.clone(),
 1856            show_local_selections: true,
 1857            mode,
 1858            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1859            show_gutter: mode == EditorMode::Full,
 1860            show_line_numbers: None,
 1861            use_relative_line_numbers: None,
 1862            show_git_diff_gutter: None,
 1863            show_code_actions: None,
 1864            show_runnables: None,
 1865            show_wrap_guides: None,
 1866            show_indent_guides,
 1867            placeholder_text: None,
 1868            highlight_order: 0,
 1869            highlighted_rows: HashMap::default(),
 1870            background_highlights: Default::default(),
 1871            gutter_highlights: TreeMap::default(),
 1872            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1873            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1874            nav_history: None,
 1875            context_menu: RwLock::new(None),
 1876            mouse_context_menu: None,
 1877            completion_tasks: Default::default(),
 1878            signature_help_state: SignatureHelpState::default(),
 1879            auto_signature_help: None,
 1880            find_all_references_task_sources: Vec::new(),
 1881            next_completion_id: 0,
 1882            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1883            next_inlay_id: 0,
 1884            available_code_actions: Default::default(),
 1885            code_actions_task: Default::default(),
 1886            document_highlights_task: Default::default(),
 1887            linked_editing_range_task: Default::default(),
 1888            pending_rename: Default::default(),
 1889            searchable: true,
 1890            cursor_shape: Default::default(),
 1891            current_line_highlight: None,
 1892            autoindent_mode: Some(AutoindentMode::EachLine),
 1893            collapse_matches: false,
 1894            workspace: None,
 1895            input_enabled: true,
 1896            use_modal_editing: mode == EditorMode::Full,
 1897            read_only: false,
 1898            use_autoclose: true,
 1899            use_auto_surround: true,
 1900            auto_replace_emoji_shortcode: false,
 1901            leader_peer_id: None,
 1902            remote_id: None,
 1903            hover_state: Default::default(),
 1904            hovered_link_state: Default::default(),
 1905            inline_completion_provider: None,
 1906            active_inline_completion: None,
 1907            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1908            expanded_hunks: ExpandedHunks::default(),
 1909            gutter_hovered: false,
 1910            pixel_position_of_newest_cursor: None,
 1911            last_bounds: None,
 1912            expect_bounds_change: None,
 1913            gutter_dimensions: GutterDimensions::default(),
 1914            style: None,
 1915            show_cursor_names: false,
 1916            hovered_cursors: Default::default(),
 1917            next_editor_action_id: EditorActionId::default(),
 1918            editor_actions: Rc::default(),
 1919            show_inline_completions_override: None,
 1920            enable_inline_completions: true,
 1921            custom_context_menu: None,
 1922            show_git_blame_gutter: false,
 1923            show_git_blame_inline: false,
 1924            show_selection_menu: None,
 1925            show_git_blame_inline_delay_task: None,
 1926            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1927            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1928                .session
 1929                .restore_unsaved_buffers,
 1930            blame: None,
 1931            blame_subscription: None,
 1932            file_header_size,
 1933            tasks: Default::default(),
 1934            _subscriptions: vec![
 1935                cx.observe(&buffer, Self::on_buffer_changed),
 1936                cx.subscribe(&buffer, Self::on_buffer_event),
 1937                cx.observe(&display_map, Self::on_display_map_changed),
 1938                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1939                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1940                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1941                cx.observe_window_activation(|editor, cx| {
 1942                    let active = cx.is_window_active();
 1943                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1944                        if active {
 1945                            blink_manager.enable(cx);
 1946                        } else {
 1947                            blink_manager.disable(cx);
 1948                        }
 1949                    });
 1950                }),
 1951            ],
 1952            tasks_update_task: None,
 1953            linked_edit_ranges: Default::default(),
 1954            previous_search_ranges: None,
 1955            breadcrumb_header: None,
 1956            focused_block: None,
 1957            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1958            addons: HashMap::default(),
 1959            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1960        };
 1961        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1962        this._subscriptions.extend(project_subscriptions);
 1963
 1964        this.end_selection(cx);
 1965        this.scroll_manager.show_scrollbar(cx);
 1966
 1967        if mode == EditorMode::Full {
 1968            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1969            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1970
 1971            if this.git_blame_inline_enabled {
 1972                this.git_blame_inline_enabled = true;
 1973                this.start_git_blame_inline(false, cx);
 1974            }
 1975        }
 1976
 1977        this.report_editor_event("open", None, cx);
 1978        this
 1979    }
 1980
 1981    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1982        self.mouse_context_menu
 1983            .as_ref()
 1984            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1985    }
 1986
 1987    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1988        let mut key_context = KeyContext::new_with_defaults();
 1989        key_context.add("Editor");
 1990        let mode = match self.mode {
 1991            EditorMode::SingleLine { .. } => "single_line",
 1992            EditorMode::AutoHeight { .. } => "auto_height",
 1993            EditorMode::Full => "full",
 1994        };
 1995
 1996        if EditorSettings::jupyter_enabled(cx) {
 1997            key_context.add("jupyter");
 1998        }
 1999
 2000        key_context.set("mode", mode);
 2001        if self.pending_rename.is_some() {
 2002            key_context.add("renaming");
 2003        }
 2004        if self.context_menu_visible() {
 2005            match self.context_menu.read().as_ref() {
 2006                Some(ContextMenu::Completions(_)) => {
 2007                    key_context.add("menu");
 2008                    key_context.add("showing_completions")
 2009                }
 2010                Some(ContextMenu::CodeActions(_)) => {
 2011                    key_context.add("menu");
 2012                    key_context.add("showing_code_actions")
 2013                }
 2014                None => {}
 2015            }
 2016        }
 2017
 2018        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2019        if !self.focus_handle(cx).contains_focused(cx)
 2020            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2021        {
 2022            for addon in self.addons.values() {
 2023                addon.extend_key_context(&mut key_context, cx)
 2024            }
 2025        }
 2026
 2027        if let Some(extension) = self
 2028            .buffer
 2029            .read(cx)
 2030            .as_singleton()
 2031            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2032        {
 2033            key_context.set("extension", extension.to_string());
 2034        }
 2035
 2036        if self.has_active_inline_completion(cx) {
 2037            key_context.add("copilot_suggestion");
 2038            key_context.add("inline_completion");
 2039        }
 2040
 2041        key_context
 2042    }
 2043
 2044    pub fn new_file(
 2045        workspace: &mut Workspace,
 2046        _: &workspace::NewFile,
 2047        cx: &mut ViewContext<Workspace>,
 2048    ) {
 2049        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2050            "Failed to create buffer",
 2051            cx,
 2052            |e, _| match e.error_code() {
 2053                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2054                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2055                e.error_tag("required").unwrap_or("the latest version")
 2056            )),
 2057                _ => None,
 2058            },
 2059        );
 2060    }
 2061
 2062    pub fn new_in_workspace(
 2063        workspace: &mut Workspace,
 2064        cx: &mut ViewContext<Workspace>,
 2065    ) -> Task<Result<View<Editor>>> {
 2066        let project = workspace.project().clone();
 2067        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2068
 2069        cx.spawn(|workspace, mut cx| async move {
 2070            let buffer = create.await?;
 2071            workspace.update(&mut cx, |workspace, cx| {
 2072                let editor =
 2073                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2074                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2075                editor
 2076            })
 2077        })
 2078    }
 2079
 2080    fn new_file_vertical(
 2081        workspace: &mut Workspace,
 2082        _: &workspace::NewFileSplitVertical,
 2083        cx: &mut ViewContext<Workspace>,
 2084    ) {
 2085        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2086    }
 2087
 2088    fn new_file_horizontal(
 2089        workspace: &mut Workspace,
 2090        _: &workspace::NewFileSplitHorizontal,
 2091        cx: &mut ViewContext<Workspace>,
 2092    ) {
 2093        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2094    }
 2095
 2096    fn new_file_in_direction(
 2097        workspace: &mut Workspace,
 2098        direction: SplitDirection,
 2099        cx: &mut ViewContext<Workspace>,
 2100    ) {
 2101        let project = workspace.project().clone();
 2102        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2103
 2104        cx.spawn(|workspace, mut cx| async move {
 2105            let buffer = create.await?;
 2106            workspace.update(&mut cx, move |workspace, cx| {
 2107                workspace.split_item(
 2108                    direction,
 2109                    Box::new(
 2110                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2111                    ),
 2112                    cx,
 2113                )
 2114            })?;
 2115            anyhow::Ok(())
 2116        })
 2117        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2118            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2119                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2120                e.error_tag("required").unwrap_or("the latest version")
 2121            )),
 2122            _ => None,
 2123        });
 2124    }
 2125
 2126    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 2127        self.buffer.read(cx).replica_id()
 2128    }
 2129
 2130    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2131        self.leader_peer_id
 2132    }
 2133
 2134    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2135        &self.buffer
 2136    }
 2137
 2138    pub fn workspace(&self) -> Option<View<Workspace>> {
 2139        self.workspace.as_ref()?.0.upgrade()
 2140    }
 2141
 2142    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2143        self.buffer().read(cx).title(cx)
 2144    }
 2145
 2146    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2147        EditorSnapshot {
 2148            mode: self.mode,
 2149            show_gutter: self.show_gutter,
 2150            show_line_numbers: self.show_line_numbers,
 2151            show_git_diff_gutter: self.show_git_diff_gutter,
 2152            show_code_actions: self.show_code_actions,
 2153            show_runnables: self.show_runnables,
 2154            render_git_blame_gutter: self.render_git_blame_gutter(cx),
 2155            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2156            scroll_anchor: self.scroll_manager.anchor(),
 2157            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2158            placeholder_text: self.placeholder_text.clone(),
 2159            is_focused: self.focus_handle.is_focused(cx),
 2160            current_line_highlight: self
 2161                .current_line_highlight
 2162                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2163            gutter_hovered: self.gutter_hovered,
 2164        }
 2165    }
 2166
 2167    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2168        self.buffer.read(cx).language_at(point, cx)
 2169    }
 2170
 2171    pub fn file_at<T: ToOffset>(
 2172        &self,
 2173        point: T,
 2174        cx: &AppContext,
 2175    ) -> Option<Arc<dyn language::File>> {
 2176        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2177    }
 2178
 2179    pub fn active_excerpt(
 2180        &self,
 2181        cx: &AppContext,
 2182    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2183        self.buffer
 2184            .read(cx)
 2185            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2186    }
 2187
 2188    pub fn mode(&self) -> EditorMode {
 2189        self.mode
 2190    }
 2191
 2192    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2193        self.collaboration_hub.as_deref()
 2194    }
 2195
 2196    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2197        self.collaboration_hub = Some(hub);
 2198    }
 2199
 2200    pub fn set_custom_context_menu(
 2201        &mut self,
 2202        f: impl 'static
 2203            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2204    ) {
 2205        self.custom_context_menu = Some(Box::new(f))
 2206    }
 2207
 2208    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2209        self.completion_provider = Some(provider);
 2210    }
 2211
 2212    pub fn set_inline_completion_provider<T>(
 2213        &mut self,
 2214        provider: Option<Model<T>>,
 2215        cx: &mut ViewContext<Self>,
 2216    ) where
 2217        T: InlineCompletionProvider,
 2218    {
 2219        self.inline_completion_provider =
 2220            provider.map(|provider| RegisteredInlineCompletionProvider {
 2221                _subscription: cx.observe(&provider, |this, _, cx| {
 2222                    if this.focus_handle.is_focused(cx) {
 2223                        this.update_visible_inline_completion(cx);
 2224                    }
 2225                }),
 2226                provider: Arc::new(provider),
 2227            });
 2228        self.refresh_inline_completion(false, false, cx);
 2229    }
 2230
 2231    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2232        self.placeholder_text.as_deref()
 2233    }
 2234
 2235    pub fn set_placeholder_text(
 2236        &mut self,
 2237        placeholder_text: impl Into<Arc<str>>,
 2238        cx: &mut ViewContext<Self>,
 2239    ) {
 2240        let placeholder_text = Some(placeholder_text.into());
 2241        if self.placeholder_text != placeholder_text {
 2242            self.placeholder_text = placeholder_text;
 2243            cx.notify();
 2244        }
 2245    }
 2246
 2247    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2248        self.cursor_shape = cursor_shape;
 2249
 2250        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2251        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2252
 2253        cx.notify();
 2254    }
 2255
 2256    pub fn set_current_line_highlight(
 2257        &mut self,
 2258        current_line_highlight: Option<CurrentLineHighlight>,
 2259    ) {
 2260        self.current_line_highlight = current_line_highlight;
 2261    }
 2262
 2263    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2264        self.collapse_matches = collapse_matches;
 2265    }
 2266
 2267    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2268        if self.collapse_matches {
 2269            return range.start..range.start;
 2270        }
 2271        range.clone()
 2272    }
 2273
 2274    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2275        if self.display_map.read(cx).clip_at_line_ends != clip {
 2276            self.display_map
 2277                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2278        }
 2279    }
 2280
 2281    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2282        self.input_enabled = input_enabled;
 2283    }
 2284
 2285    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2286        self.enable_inline_completions = enabled;
 2287    }
 2288
 2289    pub fn set_autoindent(&mut self, autoindent: bool) {
 2290        if autoindent {
 2291            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2292        } else {
 2293            self.autoindent_mode = None;
 2294        }
 2295    }
 2296
 2297    pub fn read_only(&self, cx: &AppContext) -> bool {
 2298        self.read_only || self.buffer.read(cx).read_only()
 2299    }
 2300
 2301    pub fn set_read_only(&mut self, read_only: bool) {
 2302        self.read_only = read_only;
 2303    }
 2304
 2305    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2306        self.use_autoclose = autoclose;
 2307    }
 2308
 2309    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2310        self.use_auto_surround = auto_surround;
 2311    }
 2312
 2313    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2314        self.auto_replace_emoji_shortcode = auto_replace;
 2315    }
 2316
 2317    pub fn toggle_inline_completions(
 2318        &mut self,
 2319        _: &ToggleInlineCompletions,
 2320        cx: &mut ViewContext<Self>,
 2321    ) {
 2322        if self.show_inline_completions_override.is_some() {
 2323            self.set_show_inline_completions(None, cx);
 2324        } else {
 2325            let cursor = self.selections.newest_anchor().head();
 2326            if let Some((buffer, cursor_buffer_position)) =
 2327                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2328            {
 2329                let show_inline_completions =
 2330                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2331                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2332            }
 2333        }
 2334    }
 2335
 2336    pub fn set_show_inline_completions(
 2337        &mut self,
 2338        show_inline_completions: Option<bool>,
 2339        cx: &mut ViewContext<Self>,
 2340    ) {
 2341        self.show_inline_completions_override = show_inline_completions;
 2342        self.refresh_inline_completion(false, true, cx);
 2343    }
 2344
 2345    fn should_show_inline_completions(
 2346        &self,
 2347        buffer: &Model<Buffer>,
 2348        buffer_position: language::Anchor,
 2349        cx: &AppContext,
 2350    ) -> bool {
 2351        if let Some(provider) = self.inline_completion_provider() {
 2352            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2353                show_inline_completions
 2354            } else {
 2355                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2356            }
 2357        } else {
 2358            false
 2359        }
 2360    }
 2361
 2362    pub fn set_use_modal_editing(&mut self, to: bool) {
 2363        self.use_modal_editing = to;
 2364    }
 2365
 2366    pub fn use_modal_editing(&self) -> bool {
 2367        self.use_modal_editing
 2368    }
 2369
 2370    fn selections_did_change(
 2371        &mut self,
 2372        local: bool,
 2373        old_cursor_position: &Anchor,
 2374        show_completions: bool,
 2375        cx: &mut ViewContext<Self>,
 2376    ) {
 2377        cx.invalidate_character_coordinates();
 2378
 2379        // Copy selections to primary selection buffer
 2380        #[cfg(target_os = "linux")]
 2381        if local {
 2382            let selections = self.selections.all::<usize>(cx);
 2383            let buffer_handle = self.buffer.read(cx).read(cx);
 2384
 2385            let mut text = String::new();
 2386            for (index, selection) in selections.iter().enumerate() {
 2387                let text_for_selection = buffer_handle
 2388                    .text_for_range(selection.start..selection.end)
 2389                    .collect::<String>();
 2390
 2391                text.push_str(&text_for_selection);
 2392                if index != selections.len() - 1 {
 2393                    text.push('\n');
 2394                }
 2395            }
 2396
 2397            if !text.is_empty() {
 2398                cx.write_to_primary(ClipboardItem::new_string(text));
 2399            }
 2400        }
 2401
 2402        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2403            self.buffer.update(cx, |buffer, cx| {
 2404                buffer.set_active_selections(
 2405                    &self.selections.disjoint_anchors(),
 2406                    self.selections.line_mode,
 2407                    self.cursor_shape,
 2408                    cx,
 2409                )
 2410            });
 2411        }
 2412        let display_map = self
 2413            .display_map
 2414            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2415        let buffer = &display_map.buffer_snapshot;
 2416        self.add_selections_state = None;
 2417        self.select_next_state = None;
 2418        self.select_prev_state = None;
 2419        self.select_larger_syntax_node_stack.clear();
 2420        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2421        self.snippet_stack
 2422            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2423        self.take_rename(false, cx);
 2424
 2425        let new_cursor_position = self.selections.newest_anchor().head();
 2426
 2427        self.push_to_nav_history(
 2428            *old_cursor_position,
 2429            Some(new_cursor_position.to_point(buffer)),
 2430            cx,
 2431        );
 2432
 2433        if local {
 2434            let new_cursor_position = self.selections.newest_anchor().head();
 2435            let mut context_menu = self.context_menu.write();
 2436            let completion_menu = match context_menu.as_ref() {
 2437                Some(ContextMenu::Completions(menu)) => Some(menu),
 2438
 2439                _ => {
 2440                    *context_menu = None;
 2441                    None
 2442                }
 2443            };
 2444
 2445            if let Some(completion_menu) = completion_menu {
 2446                let cursor_position = new_cursor_position.to_offset(buffer);
 2447                let (word_range, kind) =
 2448                    buffer.surrounding_word(completion_menu.initial_position, true);
 2449                if kind == Some(CharKind::Word)
 2450                    && word_range.to_inclusive().contains(&cursor_position)
 2451                {
 2452                    let mut completion_menu = completion_menu.clone();
 2453                    drop(context_menu);
 2454
 2455                    let query = Self::completion_query(buffer, cursor_position);
 2456                    cx.spawn(move |this, mut cx| async move {
 2457                        completion_menu
 2458                            .filter(query.as_deref(), cx.background_executor().clone())
 2459                            .await;
 2460
 2461                        this.update(&mut cx, |this, cx| {
 2462                            let mut context_menu = this.context_menu.write();
 2463                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2464                                return;
 2465                            };
 2466
 2467                            if menu.id > completion_menu.id {
 2468                                return;
 2469                            }
 2470
 2471                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2472                            drop(context_menu);
 2473                            cx.notify();
 2474                        })
 2475                    })
 2476                    .detach();
 2477
 2478                    if show_completions {
 2479                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2480                    }
 2481                } else {
 2482                    drop(context_menu);
 2483                    self.hide_context_menu(cx);
 2484                }
 2485            } else {
 2486                drop(context_menu);
 2487            }
 2488
 2489            hide_hover(self, cx);
 2490
 2491            if old_cursor_position.to_display_point(&display_map).row()
 2492                != new_cursor_position.to_display_point(&display_map).row()
 2493            {
 2494                self.available_code_actions.take();
 2495            }
 2496            self.refresh_code_actions(cx);
 2497            self.refresh_document_highlights(cx);
 2498            refresh_matching_bracket_highlights(self, cx);
 2499            self.discard_inline_completion(false, cx);
 2500            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2501            if self.git_blame_inline_enabled {
 2502                self.start_inline_blame_timer(cx);
 2503            }
 2504        }
 2505
 2506        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2507        cx.emit(EditorEvent::SelectionsChanged { local });
 2508
 2509        if self.selections.disjoint_anchors().len() == 1 {
 2510            cx.emit(SearchEvent::ActiveMatchChanged)
 2511        }
 2512        cx.notify();
 2513    }
 2514
 2515    pub fn change_selections<R>(
 2516        &mut self,
 2517        autoscroll: Option<Autoscroll>,
 2518        cx: &mut ViewContext<Self>,
 2519        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2520    ) -> R {
 2521        self.change_selections_inner(autoscroll, true, cx, change)
 2522    }
 2523
 2524    pub fn change_selections_inner<R>(
 2525        &mut self,
 2526        autoscroll: Option<Autoscroll>,
 2527        request_completions: bool,
 2528        cx: &mut ViewContext<Self>,
 2529        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2530    ) -> R {
 2531        let old_cursor_position = self.selections.newest_anchor().head();
 2532        self.push_to_selection_history();
 2533
 2534        let (changed, result) = self.selections.change_with(cx, change);
 2535
 2536        if changed {
 2537            if let Some(autoscroll) = autoscroll {
 2538                self.request_autoscroll(autoscroll, cx);
 2539            }
 2540            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2541
 2542            if self.should_open_signature_help_automatically(
 2543                &old_cursor_position,
 2544                self.signature_help_state.backspace_pressed(),
 2545                cx,
 2546            ) {
 2547                self.show_signature_help(&ShowSignatureHelp, cx);
 2548            }
 2549            self.signature_help_state.set_backspace_pressed(false);
 2550        }
 2551
 2552        result
 2553    }
 2554
 2555    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2556    where
 2557        I: IntoIterator<Item = (Range<S>, T)>,
 2558        S: ToOffset,
 2559        T: Into<Arc<str>>,
 2560    {
 2561        if self.read_only(cx) {
 2562            return;
 2563        }
 2564
 2565        self.buffer
 2566            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2567    }
 2568
 2569    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2570    where
 2571        I: IntoIterator<Item = (Range<S>, T)>,
 2572        S: ToOffset,
 2573        T: Into<Arc<str>>,
 2574    {
 2575        if self.read_only(cx) {
 2576            return;
 2577        }
 2578
 2579        self.buffer.update(cx, |buffer, cx| {
 2580            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2581        });
 2582    }
 2583
 2584    pub fn edit_with_block_indent<I, S, T>(
 2585        &mut self,
 2586        edits: I,
 2587        original_indent_columns: Vec<u32>,
 2588        cx: &mut ViewContext<Self>,
 2589    ) where
 2590        I: IntoIterator<Item = (Range<S>, T)>,
 2591        S: ToOffset,
 2592        T: Into<Arc<str>>,
 2593    {
 2594        if self.read_only(cx) {
 2595            return;
 2596        }
 2597
 2598        self.buffer.update(cx, |buffer, cx| {
 2599            buffer.edit(
 2600                edits,
 2601                Some(AutoindentMode::Block {
 2602                    original_indent_columns,
 2603                }),
 2604                cx,
 2605            )
 2606        });
 2607    }
 2608
 2609    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2610        self.hide_context_menu(cx);
 2611
 2612        match phase {
 2613            SelectPhase::Begin {
 2614                position,
 2615                add,
 2616                click_count,
 2617            } => self.begin_selection(position, add, click_count, cx),
 2618            SelectPhase::BeginColumnar {
 2619                position,
 2620                goal_column,
 2621                reset,
 2622            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2623            SelectPhase::Extend {
 2624                position,
 2625                click_count,
 2626            } => self.extend_selection(position, click_count, cx),
 2627            SelectPhase::Update {
 2628                position,
 2629                goal_column,
 2630                scroll_delta,
 2631            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2632            SelectPhase::End => self.end_selection(cx),
 2633        }
 2634    }
 2635
 2636    fn extend_selection(
 2637        &mut self,
 2638        position: DisplayPoint,
 2639        click_count: usize,
 2640        cx: &mut ViewContext<Self>,
 2641    ) {
 2642        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2643        let tail = self.selections.newest::<usize>(cx).tail();
 2644        self.begin_selection(position, false, click_count, cx);
 2645
 2646        let position = position.to_offset(&display_map, Bias::Left);
 2647        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2648
 2649        let mut pending_selection = self
 2650            .selections
 2651            .pending_anchor()
 2652            .expect("extend_selection not called with pending selection");
 2653        if position >= tail {
 2654            pending_selection.start = tail_anchor;
 2655        } else {
 2656            pending_selection.end = tail_anchor;
 2657            pending_selection.reversed = true;
 2658        }
 2659
 2660        let mut pending_mode = self.selections.pending_mode().unwrap();
 2661        match &mut pending_mode {
 2662            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2663            _ => {}
 2664        }
 2665
 2666        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2667            s.set_pending(pending_selection, pending_mode)
 2668        });
 2669    }
 2670
 2671    fn begin_selection(
 2672        &mut self,
 2673        position: DisplayPoint,
 2674        add: bool,
 2675        click_count: usize,
 2676        cx: &mut ViewContext<Self>,
 2677    ) {
 2678        if !self.focus_handle.is_focused(cx) {
 2679            self.last_focused_descendant = None;
 2680            cx.focus(&self.focus_handle);
 2681        }
 2682
 2683        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2684        let buffer = &display_map.buffer_snapshot;
 2685        let newest_selection = self.selections.newest_anchor().clone();
 2686        let position = display_map.clip_point(position, Bias::Left);
 2687
 2688        let start;
 2689        let end;
 2690        let mode;
 2691        let auto_scroll;
 2692        match click_count {
 2693            1 => {
 2694                start = buffer.anchor_before(position.to_point(&display_map));
 2695                end = start;
 2696                mode = SelectMode::Character;
 2697                auto_scroll = true;
 2698            }
 2699            2 => {
 2700                let range = movement::surrounding_word(&display_map, position);
 2701                start = buffer.anchor_before(range.start.to_point(&display_map));
 2702                end = buffer.anchor_before(range.end.to_point(&display_map));
 2703                mode = SelectMode::Word(start..end);
 2704                auto_scroll = true;
 2705            }
 2706            3 => {
 2707                let position = display_map
 2708                    .clip_point(position, Bias::Left)
 2709                    .to_point(&display_map);
 2710                let line_start = display_map.prev_line_boundary(position).0;
 2711                let next_line_start = buffer.clip_point(
 2712                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2713                    Bias::Left,
 2714                );
 2715                start = buffer.anchor_before(line_start);
 2716                end = buffer.anchor_before(next_line_start);
 2717                mode = SelectMode::Line(start..end);
 2718                auto_scroll = true;
 2719            }
 2720            _ => {
 2721                start = buffer.anchor_before(0);
 2722                end = buffer.anchor_before(buffer.len());
 2723                mode = SelectMode::All;
 2724                auto_scroll = false;
 2725            }
 2726        }
 2727
 2728        let point_to_delete: Option<usize> = {
 2729            let selected_points: Vec<Selection<Point>> =
 2730                self.selections.disjoint_in_range(start..end, cx);
 2731
 2732            if !add || click_count > 1 {
 2733                None
 2734            } else if !selected_points.is_empty() {
 2735                Some(selected_points[0].id)
 2736            } else {
 2737                let clicked_point_already_selected =
 2738                    self.selections.disjoint.iter().find(|selection| {
 2739                        selection.start.to_point(buffer) == start.to_point(buffer)
 2740                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2741                    });
 2742
 2743                clicked_point_already_selected.map(|selection| selection.id)
 2744            }
 2745        };
 2746
 2747        let selections_count = self.selections.count();
 2748
 2749        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2750            if let Some(point_to_delete) = point_to_delete {
 2751                s.delete(point_to_delete);
 2752
 2753                if selections_count == 1 {
 2754                    s.set_pending_anchor_range(start..end, mode);
 2755                }
 2756            } else {
 2757                if !add {
 2758                    s.clear_disjoint();
 2759                } else if click_count > 1 {
 2760                    s.delete(newest_selection.id)
 2761                }
 2762
 2763                s.set_pending_anchor_range(start..end, mode);
 2764            }
 2765        });
 2766    }
 2767
 2768    fn begin_columnar_selection(
 2769        &mut self,
 2770        position: DisplayPoint,
 2771        goal_column: u32,
 2772        reset: bool,
 2773        cx: &mut ViewContext<Self>,
 2774    ) {
 2775        if !self.focus_handle.is_focused(cx) {
 2776            self.last_focused_descendant = None;
 2777            cx.focus(&self.focus_handle);
 2778        }
 2779
 2780        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2781
 2782        if reset {
 2783            let pointer_position = display_map
 2784                .buffer_snapshot
 2785                .anchor_before(position.to_point(&display_map));
 2786
 2787            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2788                s.clear_disjoint();
 2789                s.set_pending_anchor_range(
 2790                    pointer_position..pointer_position,
 2791                    SelectMode::Character,
 2792                );
 2793            });
 2794        }
 2795
 2796        let tail = self.selections.newest::<Point>(cx).tail();
 2797        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2798
 2799        if !reset {
 2800            self.select_columns(
 2801                tail.to_display_point(&display_map),
 2802                position,
 2803                goal_column,
 2804                &display_map,
 2805                cx,
 2806            );
 2807        }
 2808    }
 2809
 2810    fn update_selection(
 2811        &mut self,
 2812        position: DisplayPoint,
 2813        goal_column: u32,
 2814        scroll_delta: gpui::Point<f32>,
 2815        cx: &mut ViewContext<Self>,
 2816    ) {
 2817        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2818
 2819        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2820            let tail = tail.to_display_point(&display_map);
 2821            self.select_columns(tail, position, goal_column, &display_map, cx);
 2822        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2823            let buffer = self.buffer.read(cx).snapshot(cx);
 2824            let head;
 2825            let tail;
 2826            let mode = self.selections.pending_mode().unwrap();
 2827            match &mode {
 2828                SelectMode::Character => {
 2829                    head = position.to_point(&display_map);
 2830                    tail = pending.tail().to_point(&buffer);
 2831                }
 2832                SelectMode::Word(original_range) => {
 2833                    let original_display_range = original_range.start.to_display_point(&display_map)
 2834                        ..original_range.end.to_display_point(&display_map);
 2835                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2836                        ..original_display_range.end.to_point(&display_map);
 2837                    if movement::is_inside_word(&display_map, position)
 2838                        || original_display_range.contains(&position)
 2839                    {
 2840                        let word_range = movement::surrounding_word(&display_map, position);
 2841                        if word_range.start < original_display_range.start {
 2842                            head = word_range.start.to_point(&display_map);
 2843                        } else {
 2844                            head = word_range.end.to_point(&display_map);
 2845                        }
 2846                    } else {
 2847                        head = position.to_point(&display_map);
 2848                    }
 2849
 2850                    if head <= original_buffer_range.start {
 2851                        tail = original_buffer_range.end;
 2852                    } else {
 2853                        tail = original_buffer_range.start;
 2854                    }
 2855                }
 2856                SelectMode::Line(original_range) => {
 2857                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2858
 2859                    let position = display_map
 2860                        .clip_point(position, Bias::Left)
 2861                        .to_point(&display_map);
 2862                    let line_start = display_map.prev_line_boundary(position).0;
 2863                    let next_line_start = buffer.clip_point(
 2864                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2865                        Bias::Left,
 2866                    );
 2867
 2868                    if line_start < original_range.start {
 2869                        head = line_start
 2870                    } else {
 2871                        head = next_line_start
 2872                    }
 2873
 2874                    if head <= original_range.start {
 2875                        tail = original_range.end;
 2876                    } else {
 2877                        tail = original_range.start;
 2878                    }
 2879                }
 2880                SelectMode::All => {
 2881                    return;
 2882                }
 2883            };
 2884
 2885            if head < tail {
 2886                pending.start = buffer.anchor_before(head);
 2887                pending.end = buffer.anchor_before(tail);
 2888                pending.reversed = true;
 2889            } else {
 2890                pending.start = buffer.anchor_before(tail);
 2891                pending.end = buffer.anchor_before(head);
 2892                pending.reversed = false;
 2893            }
 2894
 2895            self.change_selections(None, cx, |s| {
 2896                s.set_pending(pending, mode);
 2897            });
 2898        } else {
 2899            log::error!("update_selection dispatched with no pending selection");
 2900            return;
 2901        }
 2902
 2903        self.apply_scroll_delta(scroll_delta, cx);
 2904        cx.notify();
 2905    }
 2906
 2907    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2908        self.columnar_selection_tail.take();
 2909        if self.selections.pending_anchor().is_some() {
 2910            let selections = self.selections.all::<usize>(cx);
 2911            self.change_selections(None, cx, |s| {
 2912                s.select(selections);
 2913                s.clear_pending();
 2914            });
 2915        }
 2916    }
 2917
 2918    fn select_columns(
 2919        &mut self,
 2920        tail: DisplayPoint,
 2921        head: DisplayPoint,
 2922        goal_column: u32,
 2923        display_map: &DisplaySnapshot,
 2924        cx: &mut ViewContext<Self>,
 2925    ) {
 2926        let start_row = cmp::min(tail.row(), head.row());
 2927        let end_row = cmp::max(tail.row(), head.row());
 2928        let start_column = cmp::min(tail.column(), goal_column);
 2929        let end_column = cmp::max(tail.column(), goal_column);
 2930        let reversed = start_column < tail.column();
 2931
 2932        let selection_ranges = (start_row.0..=end_row.0)
 2933            .map(DisplayRow)
 2934            .filter_map(|row| {
 2935                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2936                    let start = display_map
 2937                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2938                        .to_point(display_map);
 2939                    let end = display_map
 2940                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2941                        .to_point(display_map);
 2942                    if reversed {
 2943                        Some(end..start)
 2944                    } else {
 2945                        Some(start..end)
 2946                    }
 2947                } else {
 2948                    None
 2949                }
 2950            })
 2951            .collect::<Vec<_>>();
 2952
 2953        self.change_selections(None, cx, |s| {
 2954            s.select_ranges(selection_ranges);
 2955        });
 2956        cx.notify();
 2957    }
 2958
 2959    pub fn has_pending_nonempty_selection(&self) -> bool {
 2960        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2961            Some(Selection { start, end, .. }) => start != end,
 2962            None => false,
 2963        };
 2964
 2965        pending_nonempty_selection
 2966            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2967    }
 2968
 2969    pub fn has_pending_selection(&self) -> bool {
 2970        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2971    }
 2972
 2973    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2974        if self.clear_clicked_diff_hunks(cx) {
 2975            cx.notify();
 2976            return;
 2977        }
 2978        if self.dismiss_menus_and_popups(true, cx) {
 2979            return;
 2980        }
 2981
 2982        if self.mode == EditorMode::Full
 2983            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2984        {
 2985            return;
 2986        }
 2987
 2988        cx.propagate();
 2989    }
 2990
 2991    pub fn dismiss_menus_and_popups(
 2992        &mut self,
 2993        should_report_inline_completion_event: bool,
 2994        cx: &mut ViewContext<Self>,
 2995    ) -> bool {
 2996        if self.take_rename(false, cx).is_some() {
 2997            return true;
 2998        }
 2999
 3000        if hide_hover(self, cx) {
 3001            return true;
 3002        }
 3003
 3004        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3005            return true;
 3006        }
 3007
 3008        if self.hide_context_menu(cx).is_some() {
 3009            return true;
 3010        }
 3011
 3012        if self.mouse_context_menu.take().is_some() {
 3013            return true;
 3014        }
 3015
 3016        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3017            return true;
 3018        }
 3019
 3020        if self.snippet_stack.pop().is_some() {
 3021            return true;
 3022        }
 3023
 3024        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3025            self.dismiss_diagnostics(cx);
 3026            return true;
 3027        }
 3028
 3029        false
 3030    }
 3031
 3032    fn linked_editing_ranges_for(
 3033        &self,
 3034        selection: Range<text::Anchor>,
 3035        cx: &AppContext,
 3036    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3037        if self.linked_edit_ranges.is_empty() {
 3038            return None;
 3039        }
 3040        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3041            selection.end.buffer_id.and_then(|end_buffer_id| {
 3042                if selection.start.buffer_id != Some(end_buffer_id) {
 3043                    return None;
 3044                }
 3045                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3046                let snapshot = buffer.read(cx).snapshot();
 3047                self.linked_edit_ranges
 3048                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3049                    .map(|ranges| (ranges, snapshot, buffer))
 3050            })?;
 3051        use text::ToOffset as TO;
 3052        // find offset from the start of current range to current cursor position
 3053        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3054
 3055        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3056        let start_difference = start_offset - start_byte_offset;
 3057        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3058        let end_difference = end_offset - start_byte_offset;
 3059        // Current range has associated linked ranges.
 3060        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3061        for range in linked_ranges.iter() {
 3062            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3063            let end_offset = start_offset + end_difference;
 3064            let start_offset = start_offset + start_difference;
 3065            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3066                continue;
 3067            }
 3068            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3069                if s.start.buffer_id != selection.start.buffer_id
 3070                    || s.end.buffer_id != selection.end.buffer_id
 3071                {
 3072                    return false;
 3073                }
 3074                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3075                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3076            }) {
 3077                continue;
 3078            }
 3079            let start = buffer_snapshot.anchor_after(start_offset);
 3080            let end = buffer_snapshot.anchor_after(end_offset);
 3081            linked_edits
 3082                .entry(buffer.clone())
 3083                .or_default()
 3084                .push(start..end);
 3085        }
 3086        Some(linked_edits)
 3087    }
 3088
 3089    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3090        let text: Arc<str> = text.into();
 3091
 3092        if self.read_only(cx) {
 3093            return;
 3094        }
 3095
 3096        let selections = self.selections.all_adjusted(cx);
 3097        let mut bracket_inserted = false;
 3098        let mut edits = Vec::new();
 3099        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3100        let mut new_selections = Vec::with_capacity(selections.len());
 3101        let mut new_autoclose_regions = Vec::new();
 3102        let snapshot = self.buffer.read(cx).read(cx);
 3103
 3104        for (selection, autoclose_region) in
 3105            self.selections_with_autoclose_regions(selections, &snapshot)
 3106        {
 3107            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3108                // Determine if the inserted text matches the opening or closing
 3109                // bracket of any of this language's bracket pairs.
 3110                let mut bracket_pair = None;
 3111                let mut is_bracket_pair_start = false;
 3112                let mut is_bracket_pair_end = false;
 3113                if !text.is_empty() {
 3114                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3115                    //  and they are removing the character that triggered IME popup.
 3116                    for (pair, enabled) in scope.brackets() {
 3117                        if !pair.close && !pair.surround {
 3118                            continue;
 3119                        }
 3120
 3121                        if enabled && pair.start.ends_with(text.as_ref()) {
 3122                            bracket_pair = Some(pair.clone());
 3123                            is_bracket_pair_start = true;
 3124                            break;
 3125                        }
 3126                        if pair.end.as_str() == text.as_ref() {
 3127                            bracket_pair = Some(pair.clone());
 3128                            is_bracket_pair_end = true;
 3129                            break;
 3130                        }
 3131                    }
 3132                }
 3133
 3134                if let Some(bracket_pair) = bracket_pair {
 3135                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3136                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3137                    let auto_surround =
 3138                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3139                    if selection.is_empty() {
 3140                        if is_bracket_pair_start {
 3141                            let prefix_len = bracket_pair.start.len() - text.len();
 3142
 3143                            // If the inserted text is a suffix of an opening bracket and the
 3144                            // selection is preceded by the rest of the opening bracket, then
 3145                            // insert the closing bracket.
 3146                            let following_text_allows_autoclose = snapshot
 3147                                .chars_at(selection.start)
 3148                                .next()
 3149                                .map_or(true, |c| scope.should_autoclose_before(c));
 3150                            let preceding_text_matches_prefix = prefix_len == 0
 3151                                || (selection.start.column >= (prefix_len as u32)
 3152                                    && snapshot.contains_str_at(
 3153                                        Point::new(
 3154                                            selection.start.row,
 3155                                            selection.start.column - (prefix_len as u32),
 3156                                        ),
 3157                                        &bracket_pair.start[..prefix_len],
 3158                                    ));
 3159
 3160                            if autoclose
 3161                                && bracket_pair.close
 3162                                && following_text_allows_autoclose
 3163                                && preceding_text_matches_prefix
 3164                            {
 3165                                let anchor = snapshot.anchor_before(selection.end);
 3166                                new_selections.push((selection.map(|_| anchor), text.len()));
 3167                                new_autoclose_regions.push((
 3168                                    anchor,
 3169                                    text.len(),
 3170                                    selection.id,
 3171                                    bracket_pair.clone(),
 3172                                ));
 3173                                edits.push((
 3174                                    selection.range(),
 3175                                    format!("{}{}", text, bracket_pair.end).into(),
 3176                                ));
 3177                                bracket_inserted = true;
 3178                                continue;
 3179                            }
 3180                        }
 3181
 3182                        if let Some(region) = autoclose_region {
 3183                            // If the selection is followed by an auto-inserted closing bracket,
 3184                            // then don't insert that closing bracket again; just move the selection
 3185                            // past the closing bracket.
 3186                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3187                                && text.as_ref() == region.pair.end.as_str();
 3188                            if should_skip {
 3189                                let anchor = snapshot.anchor_after(selection.end);
 3190                                new_selections
 3191                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3192                                continue;
 3193                            }
 3194                        }
 3195
 3196                        let always_treat_brackets_as_autoclosed = snapshot
 3197                            .settings_at(selection.start, cx)
 3198                            .always_treat_brackets_as_autoclosed;
 3199                        if always_treat_brackets_as_autoclosed
 3200                            && is_bracket_pair_end
 3201                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3202                        {
 3203                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3204                            // and the inserted text is a closing bracket and the selection is followed
 3205                            // by the closing bracket then move the selection past the closing bracket.
 3206                            let anchor = snapshot.anchor_after(selection.end);
 3207                            new_selections.push((selection.map(|_| anchor), text.len()));
 3208                            continue;
 3209                        }
 3210                    }
 3211                    // If an opening bracket is 1 character long and is typed while
 3212                    // text is selected, then surround that text with the bracket pair.
 3213                    else if auto_surround
 3214                        && bracket_pair.surround
 3215                        && is_bracket_pair_start
 3216                        && bracket_pair.start.chars().count() == 1
 3217                    {
 3218                        edits.push((selection.start..selection.start, text.clone()));
 3219                        edits.push((
 3220                            selection.end..selection.end,
 3221                            bracket_pair.end.as_str().into(),
 3222                        ));
 3223                        bracket_inserted = true;
 3224                        new_selections.push((
 3225                            Selection {
 3226                                id: selection.id,
 3227                                start: snapshot.anchor_after(selection.start),
 3228                                end: snapshot.anchor_before(selection.end),
 3229                                reversed: selection.reversed,
 3230                                goal: selection.goal,
 3231                            },
 3232                            0,
 3233                        ));
 3234                        continue;
 3235                    }
 3236                }
 3237            }
 3238
 3239            if self.auto_replace_emoji_shortcode
 3240                && selection.is_empty()
 3241                && text.as_ref().ends_with(':')
 3242            {
 3243                if let Some(possible_emoji_short_code) =
 3244                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3245                {
 3246                    if !possible_emoji_short_code.is_empty() {
 3247                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3248                            let emoji_shortcode_start = Point::new(
 3249                                selection.start.row,
 3250                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3251                            );
 3252
 3253                            // Remove shortcode from buffer
 3254                            edits.push((
 3255                                emoji_shortcode_start..selection.start,
 3256                                "".to_string().into(),
 3257                            ));
 3258                            new_selections.push((
 3259                                Selection {
 3260                                    id: selection.id,
 3261                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3262                                    end: snapshot.anchor_before(selection.start),
 3263                                    reversed: selection.reversed,
 3264                                    goal: selection.goal,
 3265                                },
 3266                                0,
 3267                            ));
 3268
 3269                            // Insert emoji
 3270                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3271                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3272                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3273
 3274                            continue;
 3275                        }
 3276                    }
 3277                }
 3278            }
 3279
 3280            // If not handling any auto-close operation, then just replace the selected
 3281            // text with the given input and move the selection to the end of the
 3282            // newly inserted text.
 3283            let anchor = snapshot.anchor_after(selection.end);
 3284            if !self.linked_edit_ranges.is_empty() {
 3285                let start_anchor = snapshot.anchor_before(selection.start);
 3286
 3287                let is_word_char = text.chars().next().map_or(true, |char| {
 3288                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3289                    classifier.is_word(char)
 3290                });
 3291
 3292                if is_word_char {
 3293                    if let Some(ranges) = self
 3294                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3295                    {
 3296                        for (buffer, edits) in ranges {
 3297                            linked_edits
 3298                                .entry(buffer.clone())
 3299                                .or_default()
 3300                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3301                        }
 3302                    }
 3303                }
 3304            }
 3305
 3306            new_selections.push((selection.map(|_| anchor), 0));
 3307            edits.push((selection.start..selection.end, text.clone()));
 3308        }
 3309
 3310        drop(snapshot);
 3311
 3312        self.transact(cx, |this, cx| {
 3313            this.buffer.update(cx, |buffer, cx| {
 3314                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3315            });
 3316            for (buffer, edits) in linked_edits {
 3317                buffer.update(cx, |buffer, cx| {
 3318                    let snapshot = buffer.snapshot();
 3319                    let edits = edits
 3320                        .into_iter()
 3321                        .map(|(range, text)| {
 3322                            use text::ToPoint as TP;
 3323                            let end_point = TP::to_point(&range.end, &snapshot);
 3324                            let start_point = TP::to_point(&range.start, &snapshot);
 3325                            (start_point..end_point, text)
 3326                        })
 3327                        .sorted_by_key(|(range, _)| range.start)
 3328                        .collect::<Vec<_>>();
 3329                    buffer.edit(edits, None, cx);
 3330                })
 3331            }
 3332            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3333            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3334            let snapshot = this.buffer.read(cx).read(cx);
 3335            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3336                .zip(new_selection_deltas)
 3337                .map(|(selection, delta)| Selection {
 3338                    id: selection.id,
 3339                    start: selection.start + delta,
 3340                    end: selection.end + delta,
 3341                    reversed: selection.reversed,
 3342                    goal: SelectionGoal::None,
 3343                })
 3344                .collect::<Vec<_>>();
 3345
 3346            let mut i = 0;
 3347            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3348                let position = position.to_offset(&snapshot) + delta;
 3349                let start = snapshot.anchor_before(position);
 3350                let end = snapshot.anchor_after(position);
 3351                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3352                    match existing_state.range.start.cmp(&start, &snapshot) {
 3353                        Ordering::Less => i += 1,
 3354                        Ordering::Greater => break,
 3355                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3356                            Ordering::Less => i += 1,
 3357                            Ordering::Equal => break,
 3358                            Ordering::Greater => break,
 3359                        },
 3360                    }
 3361                }
 3362                this.autoclose_regions.insert(
 3363                    i,
 3364                    AutocloseRegion {
 3365                        selection_id,
 3366                        range: start..end,
 3367                        pair,
 3368                    },
 3369                );
 3370            }
 3371
 3372            drop(snapshot);
 3373            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3374            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3375                s.select(new_selections)
 3376            });
 3377
 3378            if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
 3379                if let Some(on_type_format_task) =
 3380                    this.trigger_on_type_formatting(text.to_string(), cx)
 3381                {
 3382                    on_type_format_task.detach_and_log_err(cx);
 3383                }
 3384            }
 3385
 3386            let editor_settings = EditorSettings::get_global(cx);
 3387            if bracket_inserted
 3388                && (editor_settings.auto_signature_help
 3389                    || editor_settings.show_signature_help_after_edits)
 3390            {
 3391                this.show_signature_help(&ShowSignatureHelp, cx);
 3392            }
 3393
 3394            let trigger_in_words = !had_active_inline_completion;
 3395            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3396            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3397            this.refresh_inline_completion(true, false, cx);
 3398        });
 3399    }
 3400
 3401    fn find_possible_emoji_shortcode_at_position(
 3402        snapshot: &MultiBufferSnapshot,
 3403        position: Point,
 3404    ) -> Option<String> {
 3405        let mut chars = Vec::new();
 3406        let mut found_colon = false;
 3407        for char in snapshot.reversed_chars_at(position).take(100) {
 3408            // Found a possible emoji shortcode in the middle of the buffer
 3409            if found_colon {
 3410                if char.is_whitespace() {
 3411                    chars.reverse();
 3412                    return Some(chars.iter().collect());
 3413                }
 3414                // If the previous character is not a whitespace, we are in the middle of a word
 3415                // and we only want to complete the shortcode if the word is made up of other emojis
 3416                let mut containing_word = String::new();
 3417                for ch in snapshot
 3418                    .reversed_chars_at(position)
 3419                    .skip(chars.len() + 1)
 3420                    .take(100)
 3421                {
 3422                    if ch.is_whitespace() {
 3423                        break;
 3424                    }
 3425                    containing_word.push(ch);
 3426                }
 3427                let containing_word = containing_word.chars().rev().collect::<String>();
 3428                if util::word_consists_of_emojis(containing_word.as_str()) {
 3429                    chars.reverse();
 3430                    return Some(chars.iter().collect());
 3431                }
 3432            }
 3433
 3434            if char.is_whitespace() || !char.is_ascii() {
 3435                return None;
 3436            }
 3437            if char == ':' {
 3438                found_colon = true;
 3439            } else {
 3440                chars.push(char);
 3441            }
 3442        }
 3443        // Found a possible emoji shortcode at the beginning of the buffer
 3444        chars.reverse();
 3445        Some(chars.iter().collect())
 3446    }
 3447
 3448    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3449        self.transact(cx, |this, cx| {
 3450            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3451                let selections = this.selections.all::<usize>(cx);
 3452                let multi_buffer = this.buffer.read(cx);
 3453                let buffer = multi_buffer.snapshot(cx);
 3454                selections
 3455                    .iter()
 3456                    .map(|selection| {
 3457                        let start_point = selection.start.to_point(&buffer);
 3458                        let mut indent =
 3459                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3460                        indent.len = cmp::min(indent.len, start_point.column);
 3461                        let start = selection.start;
 3462                        let end = selection.end;
 3463                        let selection_is_empty = start == end;
 3464                        let language_scope = buffer.language_scope_at(start);
 3465                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3466                            &language_scope
 3467                        {
 3468                            let leading_whitespace_len = buffer
 3469                                .reversed_chars_at(start)
 3470                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3471                                .map(|c| c.len_utf8())
 3472                                .sum::<usize>();
 3473
 3474                            let trailing_whitespace_len = buffer
 3475                                .chars_at(end)
 3476                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3477                                .map(|c| c.len_utf8())
 3478                                .sum::<usize>();
 3479
 3480                            let insert_extra_newline =
 3481                                language.brackets().any(|(pair, enabled)| {
 3482                                    let pair_start = pair.start.trim_end();
 3483                                    let pair_end = pair.end.trim_start();
 3484
 3485                                    enabled
 3486                                        && pair.newline
 3487                                        && buffer.contains_str_at(
 3488                                            end + trailing_whitespace_len,
 3489                                            pair_end,
 3490                                        )
 3491                                        && buffer.contains_str_at(
 3492                                            (start - leading_whitespace_len)
 3493                                                .saturating_sub(pair_start.len()),
 3494                                            pair_start,
 3495                                        )
 3496                                });
 3497
 3498                            // Comment extension on newline is allowed only for cursor selections
 3499                            let comment_delimiter = maybe!({
 3500                                if !selection_is_empty {
 3501                                    return None;
 3502                                }
 3503
 3504                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3505                                    return None;
 3506                                }
 3507
 3508                                let delimiters = language.line_comment_prefixes();
 3509                                let max_len_of_delimiter =
 3510                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3511                                let (snapshot, range) =
 3512                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3513
 3514                                let mut index_of_first_non_whitespace = 0;
 3515                                let comment_candidate = snapshot
 3516                                    .chars_for_range(range)
 3517                                    .skip_while(|c| {
 3518                                        let should_skip = c.is_whitespace();
 3519                                        if should_skip {
 3520                                            index_of_first_non_whitespace += 1;
 3521                                        }
 3522                                        should_skip
 3523                                    })
 3524                                    .take(max_len_of_delimiter)
 3525                                    .collect::<String>();
 3526                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3527                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3528                                })?;
 3529                                let cursor_is_placed_after_comment_marker =
 3530                                    index_of_first_non_whitespace + comment_prefix.len()
 3531                                        <= start_point.column as usize;
 3532                                if cursor_is_placed_after_comment_marker {
 3533                                    Some(comment_prefix.clone())
 3534                                } else {
 3535                                    None
 3536                                }
 3537                            });
 3538                            (comment_delimiter, insert_extra_newline)
 3539                        } else {
 3540                            (None, false)
 3541                        };
 3542
 3543                        let capacity_for_delimiter = comment_delimiter
 3544                            .as_deref()
 3545                            .map(str::len)
 3546                            .unwrap_or_default();
 3547                        let mut new_text =
 3548                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3549                        new_text.push('\n');
 3550                        new_text.extend(indent.chars());
 3551                        if let Some(delimiter) = &comment_delimiter {
 3552                            new_text.push_str(delimiter);
 3553                        }
 3554                        if insert_extra_newline {
 3555                            new_text = new_text.repeat(2);
 3556                        }
 3557
 3558                        let anchor = buffer.anchor_after(end);
 3559                        let new_selection = selection.map(|_| anchor);
 3560                        (
 3561                            (start..end, new_text),
 3562                            (insert_extra_newline, new_selection),
 3563                        )
 3564                    })
 3565                    .unzip()
 3566            };
 3567
 3568            this.edit_with_autoindent(edits, cx);
 3569            let buffer = this.buffer.read(cx).snapshot(cx);
 3570            let new_selections = selection_fixup_info
 3571                .into_iter()
 3572                .map(|(extra_newline_inserted, new_selection)| {
 3573                    let mut cursor = new_selection.end.to_point(&buffer);
 3574                    if extra_newline_inserted {
 3575                        cursor.row -= 1;
 3576                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3577                    }
 3578                    new_selection.map(|_| cursor)
 3579                })
 3580                .collect();
 3581
 3582            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3583            this.refresh_inline_completion(true, false, cx);
 3584        });
 3585    }
 3586
 3587    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3588        let buffer = self.buffer.read(cx);
 3589        let snapshot = buffer.snapshot(cx);
 3590
 3591        let mut edits = Vec::new();
 3592        let mut rows = Vec::new();
 3593
 3594        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3595            let cursor = selection.head();
 3596            let row = cursor.row;
 3597
 3598            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3599
 3600            let newline = "\n".to_string();
 3601            edits.push((start_of_line..start_of_line, newline));
 3602
 3603            rows.push(row + rows_inserted as u32);
 3604        }
 3605
 3606        self.transact(cx, |editor, cx| {
 3607            editor.edit(edits, cx);
 3608
 3609            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3610                let mut index = 0;
 3611                s.move_cursors_with(|map, _, _| {
 3612                    let row = rows[index];
 3613                    index += 1;
 3614
 3615                    let point = Point::new(row, 0);
 3616                    let boundary = map.next_line_boundary(point).1;
 3617                    let clipped = map.clip_point(boundary, Bias::Left);
 3618
 3619                    (clipped, SelectionGoal::None)
 3620                });
 3621            });
 3622
 3623            let mut indent_edits = Vec::new();
 3624            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3625            for row in rows {
 3626                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3627                for (row, indent) in indents {
 3628                    if indent.len == 0 {
 3629                        continue;
 3630                    }
 3631
 3632                    let text = match indent.kind {
 3633                        IndentKind::Space => " ".repeat(indent.len as usize),
 3634                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3635                    };
 3636                    let point = Point::new(row.0, 0);
 3637                    indent_edits.push((point..point, text));
 3638                }
 3639            }
 3640            editor.edit(indent_edits, cx);
 3641        });
 3642    }
 3643
 3644    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3645        let buffer = self.buffer.read(cx);
 3646        let snapshot = buffer.snapshot(cx);
 3647
 3648        let mut edits = Vec::new();
 3649        let mut rows = Vec::new();
 3650        let mut rows_inserted = 0;
 3651
 3652        for selection in self.selections.all_adjusted(cx) {
 3653            let cursor = selection.head();
 3654            let row = cursor.row;
 3655
 3656            let point = Point::new(row + 1, 0);
 3657            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3658
 3659            let newline = "\n".to_string();
 3660            edits.push((start_of_line..start_of_line, newline));
 3661
 3662            rows_inserted += 1;
 3663            rows.push(row + rows_inserted);
 3664        }
 3665
 3666        self.transact(cx, |editor, cx| {
 3667            editor.edit(edits, cx);
 3668
 3669            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3670                let mut index = 0;
 3671                s.move_cursors_with(|map, _, _| {
 3672                    let row = rows[index];
 3673                    index += 1;
 3674
 3675                    let point = Point::new(row, 0);
 3676                    let boundary = map.next_line_boundary(point).1;
 3677                    let clipped = map.clip_point(boundary, Bias::Left);
 3678
 3679                    (clipped, SelectionGoal::None)
 3680                });
 3681            });
 3682
 3683            let mut indent_edits = Vec::new();
 3684            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3685            for row in rows {
 3686                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3687                for (row, indent) in indents {
 3688                    if indent.len == 0 {
 3689                        continue;
 3690                    }
 3691
 3692                    let text = match indent.kind {
 3693                        IndentKind::Space => " ".repeat(indent.len as usize),
 3694                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3695                    };
 3696                    let point = Point::new(row.0, 0);
 3697                    indent_edits.push((point..point, text));
 3698                }
 3699            }
 3700            editor.edit(indent_edits, cx);
 3701        });
 3702    }
 3703
 3704    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3705        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3706            original_indent_columns: Vec::new(),
 3707        });
 3708        self.insert_with_autoindent_mode(text, autoindent, cx);
 3709    }
 3710
 3711    fn insert_with_autoindent_mode(
 3712        &mut self,
 3713        text: &str,
 3714        autoindent_mode: Option<AutoindentMode>,
 3715        cx: &mut ViewContext<Self>,
 3716    ) {
 3717        if self.read_only(cx) {
 3718            return;
 3719        }
 3720
 3721        let text: Arc<str> = text.into();
 3722        self.transact(cx, |this, cx| {
 3723            let old_selections = this.selections.all_adjusted(cx);
 3724            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3725                let anchors = {
 3726                    let snapshot = buffer.read(cx);
 3727                    old_selections
 3728                        .iter()
 3729                        .map(|s| {
 3730                            let anchor = snapshot.anchor_after(s.head());
 3731                            s.map(|_| anchor)
 3732                        })
 3733                        .collect::<Vec<_>>()
 3734                };
 3735                buffer.edit(
 3736                    old_selections
 3737                        .iter()
 3738                        .map(|s| (s.start..s.end, text.clone())),
 3739                    autoindent_mode,
 3740                    cx,
 3741                );
 3742                anchors
 3743            });
 3744
 3745            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3746                s.select_anchors(selection_anchors);
 3747            })
 3748        });
 3749    }
 3750
 3751    fn trigger_completion_on_input(
 3752        &mut self,
 3753        text: &str,
 3754        trigger_in_words: bool,
 3755        cx: &mut ViewContext<Self>,
 3756    ) {
 3757        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3758            self.show_completions(
 3759                &ShowCompletions {
 3760                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3761                },
 3762                cx,
 3763            );
 3764        } else {
 3765            self.hide_context_menu(cx);
 3766        }
 3767    }
 3768
 3769    fn is_completion_trigger(
 3770        &self,
 3771        text: &str,
 3772        trigger_in_words: bool,
 3773        cx: &mut ViewContext<Self>,
 3774    ) -> bool {
 3775        let position = self.selections.newest_anchor().head();
 3776        let multibuffer = self.buffer.read(cx);
 3777        let Some(buffer) = position
 3778            .buffer_id
 3779            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3780        else {
 3781            return false;
 3782        };
 3783
 3784        if let Some(completion_provider) = &self.completion_provider {
 3785            completion_provider.is_completion_trigger(
 3786                &buffer,
 3787                position.text_anchor,
 3788                text,
 3789                trigger_in_words,
 3790                cx,
 3791            )
 3792        } else {
 3793            false
 3794        }
 3795    }
 3796
 3797    /// If any empty selections is touching the start of its innermost containing autoclose
 3798    /// region, expand it to select the brackets.
 3799    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3800        let selections = self.selections.all::<usize>(cx);
 3801        let buffer = self.buffer.read(cx).read(cx);
 3802        let new_selections = self
 3803            .selections_with_autoclose_regions(selections, &buffer)
 3804            .map(|(mut selection, region)| {
 3805                if !selection.is_empty() {
 3806                    return selection;
 3807                }
 3808
 3809                if let Some(region) = region {
 3810                    let mut range = region.range.to_offset(&buffer);
 3811                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3812                        range.start -= region.pair.start.len();
 3813                        if buffer.contains_str_at(range.start, &region.pair.start)
 3814                            && buffer.contains_str_at(range.end, &region.pair.end)
 3815                        {
 3816                            range.end += region.pair.end.len();
 3817                            selection.start = range.start;
 3818                            selection.end = range.end;
 3819
 3820                            return selection;
 3821                        }
 3822                    }
 3823                }
 3824
 3825                let always_treat_brackets_as_autoclosed = buffer
 3826                    .settings_at(selection.start, cx)
 3827                    .always_treat_brackets_as_autoclosed;
 3828
 3829                if !always_treat_brackets_as_autoclosed {
 3830                    return selection;
 3831                }
 3832
 3833                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3834                    for (pair, enabled) in scope.brackets() {
 3835                        if !enabled || !pair.close {
 3836                            continue;
 3837                        }
 3838
 3839                        if buffer.contains_str_at(selection.start, &pair.end) {
 3840                            let pair_start_len = pair.start.len();
 3841                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3842                            {
 3843                                selection.start -= pair_start_len;
 3844                                selection.end += pair.end.len();
 3845
 3846                                return selection;
 3847                            }
 3848                        }
 3849                    }
 3850                }
 3851
 3852                selection
 3853            })
 3854            .collect();
 3855
 3856        drop(buffer);
 3857        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3858    }
 3859
 3860    /// Iterate the given selections, and for each one, find the smallest surrounding
 3861    /// autoclose region. This uses the ordering of the selections and the autoclose
 3862    /// regions to avoid repeated comparisons.
 3863    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3864        &'a self,
 3865        selections: impl IntoIterator<Item = Selection<D>>,
 3866        buffer: &'a MultiBufferSnapshot,
 3867    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3868        let mut i = 0;
 3869        let mut regions = self.autoclose_regions.as_slice();
 3870        selections.into_iter().map(move |selection| {
 3871            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3872
 3873            let mut enclosing = None;
 3874            while let Some(pair_state) = regions.get(i) {
 3875                if pair_state.range.end.to_offset(buffer) < range.start {
 3876                    regions = &regions[i + 1..];
 3877                    i = 0;
 3878                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3879                    break;
 3880                } else {
 3881                    if pair_state.selection_id == selection.id {
 3882                        enclosing = Some(pair_state);
 3883                    }
 3884                    i += 1;
 3885                }
 3886            }
 3887
 3888            (selection.clone(), enclosing)
 3889        })
 3890    }
 3891
 3892    /// Remove any autoclose regions that no longer contain their selection.
 3893    fn invalidate_autoclose_regions(
 3894        &mut self,
 3895        mut selections: &[Selection<Anchor>],
 3896        buffer: &MultiBufferSnapshot,
 3897    ) {
 3898        self.autoclose_regions.retain(|state| {
 3899            let mut i = 0;
 3900            while let Some(selection) = selections.get(i) {
 3901                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3902                    selections = &selections[1..];
 3903                    continue;
 3904                }
 3905                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3906                    break;
 3907                }
 3908                if selection.id == state.selection_id {
 3909                    return true;
 3910                } else {
 3911                    i += 1;
 3912                }
 3913            }
 3914            false
 3915        });
 3916    }
 3917
 3918    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3919        let offset = position.to_offset(buffer);
 3920        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3921        if offset > word_range.start && kind == Some(CharKind::Word) {
 3922            Some(
 3923                buffer
 3924                    .text_for_range(word_range.start..offset)
 3925                    .collect::<String>(),
 3926            )
 3927        } else {
 3928            None
 3929        }
 3930    }
 3931
 3932    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3933        self.refresh_inlay_hints(
 3934            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3935            cx,
 3936        );
 3937    }
 3938
 3939    pub fn inlay_hints_enabled(&self) -> bool {
 3940        self.inlay_hint_cache.enabled
 3941    }
 3942
 3943    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3944        if self.project.is_none() || self.mode != EditorMode::Full {
 3945            return;
 3946        }
 3947
 3948        let reason_description = reason.description();
 3949        let ignore_debounce = matches!(
 3950            reason,
 3951            InlayHintRefreshReason::SettingsChange(_)
 3952                | InlayHintRefreshReason::Toggle(_)
 3953                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3954        );
 3955        let (invalidate_cache, required_languages) = match reason {
 3956            InlayHintRefreshReason::Toggle(enabled) => {
 3957                self.inlay_hint_cache.enabled = enabled;
 3958                if enabled {
 3959                    (InvalidationStrategy::RefreshRequested, None)
 3960                } else {
 3961                    self.inlay_hint_cache.clear();
 3962                    self.splice_inlays(
 3963                        self.visible_inlay_hints(cx)
 3964                            .iter()
 3965                            .map(|inlay| inlay.id)
 3966                            .collect(),
 3967                        Vec::new(),
 3968                        cx,
 3969                    );
 3970                    return;
 3971                }
 3972            }
 3973            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3974                match self.inlay_hint_cache.update_settings(
 3975                    &self.buffer,
 3976                    new_settings,
 3977                    self.visible_inlay_hints(cx),
 3978                    cx,
 3979                ) {
 3980                    ControlFlow::Break(Some(InlaySplice {
 3981                        to_remove,
 3982                        to_insert,
 3983                    })) => {
 3984                        self.splice_inlays(to_remove, to_insert, cx);
 3985                        return;
 3986                    }
 3987                    ControlFlow::Break(None) => return,
 3988                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3989                }
 3990            }
 3991            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3992                if let Some(InlaySplice {
 3993                    to_remove,
 3994                    to_insert,
 3995                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3996                {
 3997                    self.splice_inlays(to_remove, to_insert, cx);
 3998                }
 3999                return;
 4000            }
 4001            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4002            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4003                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4004            }
 4005            InlayHintRefreshReason::RefreshRequested => {
 4006                (InvalidationStrategy::RefreshRequested, None)
 4007            }
 4008        };
 4009
 4010        if let Some(InlaySplice {
 4011            to_remove,
 4012            to_insert,
 4013        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4014            reason_description,
 4015            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4016            invalidate_cache,
 4017            ignore_debounce,
 4018            cx,
 4019        ) {
 4020            self.splice_inlays(to_remove, to_insert, cx);
 4021        }
 4022    }
 4023
 4024    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4025        self.display_map
 4026            .read(cx)
 4027            .current_inlays()
 4028            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4029            .cloned()
 4030            .collect()
 4031    }
 4032
 4033    pub fn excerpts_for_inlay_hints_query(
 4034        &self,
 4035        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4036        cx: &mut ViewContext<Editor>,
 4037    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4038        let Some(project) = self.project.as_ref() else {
 4039            return HashMap::default();
 4040        };
 4041        let project = project.read(cx);
 4042        let multi_buffer = self.buffer().read(cx);
 4043        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4044        let multi_buffer_visible_start = self
 4045            .scroll_manager
 4046            .anchor()
 4047            .anchor
 4048            .to_point(&multi_buffer_snapshot);
 4049        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4050            multi_buffer_visible_start
 4051                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4052            Bias::Left,
 4053        );
 4054        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4055        multi_buffer
 4056            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4057            .into_iter()
 4058            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4059            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4060                let buffer = buffer_handle.read(cx);
 4061                let buffer_file = project::File::from_dyn(buffer.file())?;
 4062                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4063                let worktree_entry = buffer_worktree
 4064                    .read(cx)
 4065                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4066                if worktree_entry.is_ignored {
 4067                    return None;
 4068                }
 4069
 4070                let language = buffer.language()?;
 4071                if let Some(restrict_to_languages) = restrict_to_languages {
 4072                    if !restrict_to_languages.contains(language) {
 4073                        return None;
 4074                    }
 4075                }
 4076                Some((
 4077                    excerpt_id,
 4078                    (
 4079                        buffer_handle,
 4080                        buffer.version().clone(),
 4081                        excerpt_visible_range,
 4082                    ),
 4083                ))
 4084            })
 4085            .collect()
 4086    }
 4087
 4088    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4089        TextLayoutDetails {
 4090            text_system: cx.text_system().clone(),
 4091            editor_style: self.style.clone().unwrap(),
 4092            rem_size: cx.rem_size(),
 4093            scroll_anchor: self.scroll_manager.anchor(),
 4094            visible_rows: self.visible_line_count(),
 4095            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4096        }
 4097    }
 4098
 4099    fn splice_inlays(
 4100        &self,
 4101        to_remove: Vec<InlayId>,
 4102        to_insert: Vec<Inlay>,
 4103        cx: &mut ViewContext<Self>,
 4104    ) {
 4105        self.display_map.update(cx, |display_map, cx| {
 4106            display_map.splice_inlays(to_remove, to_insert, cx);
 4107        });
 4108        cx.notify();
 4109    }
 4110
 4111    fn trigger_on_type_formatting(
 4112        &self,
 4113        input: String,
 4114        cx: &mut ViewContext<Self>,
 4115    ) -> Option<Task<Result<()>>> {
 4116        if input.len() != 1 {
 4117            return None;
 4118        }
 4119
 4120        let project = self.project.as_ref()?;
 4121        let position = self.selections.newest_anchor().head();
 4122        let (buffer, buffer_position) = self
 4123            .buffer
 4124            .read(cx)
 4125            .text_anchor_for_position(position, cx)?;
 4126
 4127        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4128        // hence we do LSP request & edit on host side only — add formats to host's history.
 4129        let push_to_lsp_host_history = true;
 4130        // If this is not the host, append its history with new edits.
 4131        let push_to_client_history = project.read(cx).is_via_collab();
 4132
 4133        let on_type_formatting = project.update(cx, |project, cx| {
 4134            project.on_type_format(
 4135                buffer.clone(),
 4136                buffer_position,
 4137                input,
 4138                push_to_lsp_host_history,
 4139                cx,
 4140            )
 4141        });
 4142        Some(cx.spawn(|editor, mut cx| async move {
 4143            if let Some(transaction) = on_type_formatting.await? {
 4144                if push_to_client_history {
 4145                    buffer
 4146                        .update(&mut cx, |buffer, _| {
 4147                            buffer.push_transaction(transaction, Instant::now());
 4148                        })
 4149                        .ok();
 4150                }
 4151                editor.update(&mut cx, |editor, cx| {
 4152                    editor.refresh_document_highlights(cx);
 4153                })?;
 4154            }
 4155            Ok(())
 4156        }))
 4157    }
 4158
 4159    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4160        if self.pending_rename.is_some() {
 4161            return;
 4162        }
 4163
 4164        let Some(provider) = self.completion_provider.as_ref() else {
 4165            return;
 4166        };
 4167
 4168        let position = self.selections.newest_anchor().head();
 4169        let (buffer, buffer_position) =
 4170            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4171                output
 4172            } else {
 4173                return;
 4174            };
 4175
 4176        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4177        let is_followup_invoke = {
 4178            let context_menu_state = self.context_menu.read();
 4179            matches!(
 4180                context_menu_state.deref(),
 4181                Some(ContextMenu::Completions(_))
 4182            )
 4183        };
 4184        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4185            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4186            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4187                CompletionTriggerKind::TRIGGER_CHARACTER
 4188            }
 4189
 4190            _ => CompletionTriggerKind::INVOKED,
 4191        };
 4192        let completion_context = CompletionContext {
 4193            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4194                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4195                    Some(String::from(trigger))
 4196                } else {
 4197                    None
 4198                }
 4199            }),
 4200            trigger_kind,
 4201        };
 4202        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4203        let sort_completions = provider.sort_completions();
 4204
 4205        let id = post_inc(&mut self.next_completion_id);
 4206        let task = cx.spawn(|this, mut cx| {
 4207            async move {
 4208                this.update(&mut cx, |this, _| {
 4209                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4210                })?;
 4211                let completions = completions.await.log_err();
 4212                let menu = if let Some(completions) = completions {
 4213                    let mut menu = CompletionsMenu {
 4214                        id,
 4215                        sort_completions,
 4216                        initial_position: position,
 4217                        match_candidates: completions
 4218                            .iter()
 4219                            .enumerate()
 4220                            .map(|(id, completion)| {
 4221                                StringMatchCandidate::new(
 4222                                    id,
 4223                                    completion.label.text[completion.label.filter_range.clone()]
 4224                                        .into(),
 4225                                )
 4226                            })
 4227                            .collect(),
 4228                        buffer: buffer.clone(),
 4229                        completions: Arc::new(RwLock::new(completions.into())),
 4230                        matches: Vec::new().into(),
 4231                        selected_item: 0,
 4232                        scroll_handle: UniformListScrollHandle::new(),
 4233                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4234                            DebouncedDelay::new(),
 4235                        )),
 4236                    };
 4237                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4238                        .await;
 4239
 4240                    if menu.matches.is_empty() {
 4241                        None
 4242                    } else {
 4243                        this.update(&mut cx, |editor, cx| {
 4244                            let completions = menu.completions.clone();
 4245                            let matches = menu.matches.clone();
 4246
 4247                            let delay_ms = EditorSettings::get_global(cx)
 4248                                .completion_documentation_secondary_query_debounce;
 4249                            let delay = Duration::from_millis(delay_ms);
 4250                            editor
 4251                                .completion_documentation_pre_resolve_debounce
 4252                                .fire_new(delay, cx, |editor, cx| {
 4253                                    CompletionsMenu::pre_resolve_completion_documentation(
 4254                                        buffer,
 4255                                        completions,
 4256                                        matches,
 4257                                        editor,
 4258                                        cx,
 4259                                    )
 4260                                });
 4261                        })
 4262                        .ok();
 4263                        Some(menu)
 4264                    }
 4265                } else {
 4266                    None
 4267                };
 4268
 4269                this.update(&mut cx, |this, cx| {
 4270                    let mut context_menu = this.context_menu.write();
 4271                    match context_menu.as_ref() {
 4272                        None => {}
 4273
 4274                        Some(ContextMenu::Completions(prev_menu)) => {
 4275                            if prev_menu.id > id {
 4276                                return;
 4277                            }
 4278                        }
 4279
 4280                        _ => return,
 4281                    }
 4282
 4283                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4284                        let menu = menu.unwrap();
 4285                        *context_menu = Some(ContextMenu::Completions(menu));
 4286                        drop(context_menu);
 4287                        this.discard_inline_completion(false, cx);
 4288                        cx.notify();
 4289                    } else if this.completion_tasks.len() <= 1 {
 4290                        // If there are no more completion tasks and the last menu was
 4291                        // empty, we should hide it. If it was already hidden, we should
 4292                        // also show the copilot completion when available.
 4293                        drop(context_menu);
 4294                        if this.hide_context_menu(cx).is_none() {
 4295                            this.update_visible_inline_completion(cx);
 4296                        }
 4297                    }
 4298                })?;
 4299
 4300                Ok::<_, anyhow::Error>(())
 4301            }
 4302            .log_err()
 4303        });
 4304
 4305        self.completion_tasks.push((id, task));
 4306    }
 4307
 4308    pub fn confirm_completion(
 4309        &mut self,
 4310        action: &ConfirmCompletion,
 4311        cx: &mut ViewContext<Self>,
 4312    ) -> Option<Task<Result<()>>> {
 4313        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4314    }
 4315
 4316    pub fn compose_completion(
 4317        &mut self,
 4318        action: &ComposeCompletion,
 4319        cx: &mut ViewContext<Self>,
 4320    ) -> Option<Task<Result<()>>> {
 4321        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4322    }
 4323
 4324    fn do_completion(
 4325        &mut self,
 4326        item_ix: Option<usize>,
 4327        intent: CompletionIntent,
 4328        cx: &mut ViewContext<Editor>,
 4329    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4330        use language::ToOffset as _;
 4331
 4332        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4333            menu
 4334        } else {
 4335            return None;
 4336        };
 4337
 4338        let mat = completions_menu
 4339            .matches
 4340            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4341        let buffer_handle = completions_menu.buffer;
 4342        let completions = completions_menu.completions.read();
 4343        let completion = completions.get(mat.candidate_id)?;
 4344        cx.stop_propagation();
 4345
 4346        let snippet;
 4347        let text;
 4348
 4349        if completion.is_snippet() {
 4350            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4351            text = snippet.as_ref().unwrap().text.clone();
 4352        } else {
 4353            snippet = None;
 4354            text = completion.new_text.clone();
 4355        };
 4356        let selections = self.selections.all::<usize>(cx);
 4357        let buffer = buffer_handle.read(cx);
 4358        let old_range = completion.old_range.to_offset(buffer);
 4359        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4360
 4361        let newest_selection = self.selections.newest_anchor();
 4362        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4363            return None;
 4364        }
 4365
 4366        let lookbehind = newest_selection
 4367            .start
 4368            .text_anchor
 4369            .to_offset(buffer)
 4370            .saturating_sub(old_range.start);
 4371        let lookahead = old_range
 4372            .end
 4373            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4374        let mut common_prefix_len = old_text
 4375            .bytes()
 4376            .zip(text.bytes())
 4377            .take_while(|(a, b)| a == b)
 4378            .count();
 4379
 4380        let snapshot = self.buffer.read(cx).snapshot(cx);
 4381        let mut range_to_replace: Option<Range<isize>> = None;
 4382        let mut ranges = Vec::new();
 4383        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4384        for selection in &selections {
 4385            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4386                let start = selection.start.saturating_sub(lookbehind);
 4387                let end = selection.end + lookahead;
 4388                if selection.id == newest_selection.id {
 4389                    range_to_replace = Some(
 4390                        ((start + common_prefix_len) as isize - selection.start as isize)
 4391                            ..(end as isize - selection.start as isize),
 4392                    );
 4393                }
 4394                ranges.push(start + common_prefix_len..end);
 4395            } else {
 4396                common_prefix_len = 0;
 4397                ranges.clear();
 4398                ranges.extend(selections.iter().map(|s| {
 4399                    if s.id == newest_selection.id {
 4400                        range_to_replace = Some(
 4401                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4402                                - selection.start as isize
 4403                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4404                                    - selection.start as isize,
 4405                        );
 4406                        old_range.clone()
 4407                    } else {
 4408                        s.start..s.end
 4409                    }
 4410                }));
 4411                break;
 4412            }
 4413            if !self.linked_edit_ranges.is_empty() {
 4414                let start_anchor = snapshot.anchor_before(selection.head());
 4415                let end_anchor = snapshot.anchor_after(selection.tail());
 4416                if let Some(ranges) = self
 4417                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4418                {
 4419                    for (buffer, edits) in ranges {
 4420                        linked_edits.entry(buffer.clone()).or_default().extend(
 4421                            edits
 4422                                .into_iter()
 4423                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4424                        );
 4425                    }
 4426                }
 4427            }
 4428        }
 4429        let text = &text[common_prefix_len..];
 4430
 4431        cx.emit(EditorEvent::InputHandled {
 4432            utf16_range_to_replace: range_to_replace,
 4433            text: text.into(),
 4434        });
 4435
 4436        self.transact(cx, |this, cx| {
 4437            if let Some(mut snippet) = snippet {
 4438                snippet.text = text.to_string();
 4439                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4440                    tabstop.start -= common_prefix_len as isize;
 4441                    tabstop.end -= common_prefix_len as isize;
 4442                }
 4443
 4444                this.insert_snippet(&ranges, snippet, cx).log_err();
 4445            } else {
 4446                this.buffer.update(cx, |buffer, cx| {
 4447                    buffer.edit(
 4448                        ranges.iter().map(|range| (range.clone(), text)),
 4449                        this.autoindent_mode.clone(),
 4450                        cx,
 4451                    );
 4452                });
 4453            }
 4454            for (buffer, edits) in linked_edits {
 4455                buffer.update(cx, |buffer, cx| {
 4456                    let snapshot = buffer.snapshot();
 4457                    let edits = edits
 4458                        .into_iter()
 4459                        .map(|(range, text)| {
 4460                            use text::ToPoint as TP;
 4461                            let end_point = TP::to_point(&range.end, &snapshot);
 4462                            let start_point = TP::to_point(&range.start, &snapshot);
 4463                            (start_point..end_point, text)
 4464                        })
 4465                        .sorted_by_key(|(range, _)| range.start)
 4466                        .collect::<Vec<_>>();
 4467                    buffer.edit(edits, None, cx);
 4468                })
 4469            }
 4470
 4471            this.refresh_inline_completion(true, false, cx);
 4472        });
 4473
 4474        let show_new_completions_on_confirm = completion
 4475            .confirm
 4476            .as_ref()
 4477            .map_or(false, |confirm| confirm(intent, cx));
 4478        if show_new_completions_on_confirm {
 4479            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4480        }
 4481
 4482        let provider = self.completion_provider.as_ref()?;
 4483        let apply_edits = provider.apply_additional_edits_for_completion(
 4484            buffer_handle,
 4485            completion.clone(),
 4486            true,
 4487            cx,
 4488        );
 4489
 4490        let editor_settings = EditorSettings::get_global(cx);
 4491        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4492            // After the code completion is finished, users often want to know what signatures are needed.
 4493            // so we should automatically call signature_help
 4494            self.show_signature_help(&ShowSignatureHelp, cx);
 4495        }
 4496
 4497        Some(cx.foreground_executor().spawn(async move {
 4498            apply_edits.await?;
 4499            Ok(())
 4500        }))
 4501    }
 4502
 4503    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4504        let mut context_menu = self.context_menu.write();
 4505        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4506            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4507                // Toggle if we're selecting the same one
 4508                *context_menu = None;
 4509                cx.notify();
 4510                return;
 4511            } else {
 4512                // Otherwise, clear it and start a new one
 4513                *context_menu = None;
 4514                cx.notify();
 4515            }
 4516        }
 4517        drop(context_menu);
 4518        let snapshot = self.snapshot(cx);
 4519        let deployed_from_indicator = action.deployed_from_indicator;
 4520        let mut task = self.code_actions_task.take();
 4521        let action = action.clone();
 4522        cx.spawn(|editor, mut cx| async move {
 4523            while let Some(prev_task) = task {
 4524                prev_task.await;
 4525                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4526            }
 4527
 4528            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4529                if editor.focus_handle.is_focused(cx) {
 4530                    let multibuffer_point = action
 4531                        .deployed_from_indicator
 4532                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4533                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4534                    let (buffer, buffer_row) = snapshot
 4535                        .buffer_snapshot
 4536                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4537                        .and_then(|(buffer_snapshot, range)| {
 4538                            editor
 4539                                .buffer
 4540                                .read(cx)
 4541                                .buffer(buffer_snapshot.remote_id())
 4542                                .map(|buffer| (buffer, range.start.row))
 4543                        })?;
 4544                    let (_, code_actions) = editor
 4545                        .available_code_actions
 4546                        .clone()
 4547                        .and_then(|(location, code_actions)| {
 4548                            let snapshot = location.buffer.read(cx).snapshot();
 4549                            let point_range = location.range.to_point(&snapshot);
 4550                            let point_range = point_range.start.row..=point_range.end.row;
 4551                            if point_range.contains(&buffer_row) {
 4552                                Some((location, code_actions))
 4553                            } else {
 4554                                None
 4555                            }
 4556                        })
 4557                        .unzip();
 4558                    let buffer_id = buffer.read(cx).remote_id();
 4559                    let tasks = editor
 4560                        .tasks
 4561                        .get(&(buffer_id, buffer_row))
 4562                        .map(|t| Arc::new(t.to_owned()));
 4563                    if tasks.is_none() && code_actions.is_none() {
 4564                        return None;
 4565                    }
 4566
 4567                    editor.completion_tasks.clear();
 4568                    editor.discard_inline_completion(false, cx);
 4569                    let task_context =
 4570                        tasks
 4571                            .as_ref()
 4572                            .zip(editor.project.clone())
 4573                            .map(|(tasks, project)| {
 4574                                let position = Point::new(buffer_row, tasks.column);
 4575                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4576                                let location = Location {
 4577                                    buffer: buffer.clone(),
 4578                                    range: range_start..range_start,
 4579                                };
 4580                                // Fill in the environmental variables from the tree-sitter captures
 4581                                let mut captured_task_variables = TaskVariables::default();
 4582                                for (capture_name, value) in tasks.extra_variables.clone() {
 4583                                    captured_task_variables.insert(
 4584                                        task::VariableName::Custom(capture_name.into()),
 4585                                        value.clone(),
 4586                                    );
 4587                                }
 4588                                project.update(cx, |project, cx| {
 4589                                    project.task_context_for_location(
 4590                                        captured_task_variables,
 4591                                        location,
 4592                                        cx,
 4593                                    )
 4594                                })
 4595                            });
 4596
 4597                    Some(cx.spawn(|editor, mut cx| async move {
 4598                        let task_context = match task_context {
 4599                            Some(task_context) => task_context.await,
 4600                            None => None,
 4601                        };
 4602                        let resolved_tasks =
 4603                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4604                                Arc::new(ResolvedTasks {
 4605                                    templates: tasks
 4606                                        .templates
 4607                                        .iter()
 4608                                        .filter_map(|(kind, template)| {
 4609                                            template
 4610                                                .resolve_task(&kind.to_id_base(), &task_context)
 4611                                                .map(|task| (kind.clone(), task))
 4612                                        })
 4613                                        .collect(),
 4614                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4615                                        multibuffer_point.row,
 4616                                        tasks.column,
 4617                                    )),
 4618                                })
 4619                            });
 4620                        let spawn_straight_away = resolved_tasks
 4621                            .as_ref()
 4622                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4623                            && code_actions
 4624                                .as_ref()
 4625                                .map_or(true, |actions| actions.is_empty());
 4626                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4627                            *editor.context_menu.write() =
 4628                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4629                                    buffer,
 4630                                    actions: CodeActionContents {
 4631                                        tasks: resolved_tasks,
 4632                                        actions: code_actions,
 4633                                    },
 4634                                    selected_item: Default::default(),
 4635                                    scroll_handle: UniformListScrollHandle::default(),
 4636                                    deployed_from_indicator,
 4637                                }));
 4638                            if spawn_straight_away {
 4639                                if let Some(task) = editor.confirm_code_action(
 4640                                    &ConfirmCodeAction { item_ix: Some(0) },
 4641                                    cx,
 4642                                ) {
 4643                                    cx.notify();
 4644                                    return task;
 4645                                }
 4646                            }
 4647                            cx.notify();
 4648                            Task::ready(Ok(()))
 4649                        }) {
 4650                            task.await
 4651                        } else {
 4652                            Ok(())
 4653                        }
 4654                    }))
 4655                } else {
 4656                    Some(Task::ready(Ok(())))
 4657                }
 4658            })?;
 4659            if let Some(task) = spawned_test_task {
 4660                task.await?;
 4661            }
 4662
 4663            Ok::<_, anyhow::Error>(())
 4664        })
 4665        .detach_and_log_err(cx);
 4666    }
 4667
 4668    pub fn confirm_code_action(
 4669        &mut self,
 4670        action: &ConfirmCodeAction,
 4671        cx: &mut ViewContext<Self>,
 4672    ) -> Option<Task<Result<()>>> {
 4673        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4674            menu
 4675        } else {
 4676            return None;
 4677        };
 4678        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4679        let action = actions_menu.actions.get(action_ix)?;
 4680        let title = action.label();
 4681        let buffer = actions_menu.buffer;
 4682        let workspace = self.workspace()?;
 4683
 4684        match action {
 4685            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4686                workspace.update(cx, |workspace, cx| {
 4687                    workspace::tasks::schedule_resolved_task(
 4688                        workspace,
 4689                        task_source_kind,
 4690                        resolved_task,
 4691                        false,
 4692                        cx,
 4693                    );
 4694
 4695                    Some(Task::ready(Ok(())))
 4696                })
 4697            }
 4698            CodeActionsItem::CodeAction(action) => {
 4699                let apply_code_actions = workspace
 4700                    .read(cx)
 4701                    .project()
 4702                    .clone()
 4703                    .update(cx, |project, cx| {
 4704                        project.apply_code_action(buffer, action, true, cx)
 4705                    });
 4706                let workspace = workspace.downgrade();
 4707                Some(cx.spawn(|editor, cx| async move {
 4708                    let project_transaction = apply_code_actions.await?;
 4709                    Self::open_project_transaction(
 4710                        &editor,
 4711                        workspace,
 4712                        project_transaction,
 4713                        title,
 4714                        cx,
 4715                    )
 4716                    .await
 4717                }))
 4718            }
 4719        }
 4720    }
 4721
 4722    pub async fn open_project_transaction(
 4723        this: &WeakView<Editor>,
 4724        workspace: WeakView<Workspace>,
 4725        transaction: ProjectTransaction,
 4726        title: String,
 4727        mut cx: AsyncWindowContext,
 4728    ) -> Result<()> {
 4729        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 4730
 4731        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4732        cx.update(|cx| {
 4733            entries.sort_unstable_by_key(|(buffer, _)| {
 4734                buffer.read(cx).file().map(|f| f.path().clone())
 4735            });
 4736        })?;
 4737
 4738        // If the project transaction's edits are all contained within this editor, then
 4739        // avoid opening a new editor to display them.
 4740
 4741        if let Some((buffer, transaction)) = entries.first() {
 4742            if entries.len() == 1 {
 4743                let excerpt = this.update(&mut cx, |editor, cx| {
 4744                    editor
 4745                        .buffer()
 4746                        .read(cx)
 4747                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4748                })?;
 4749                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4750                    if excerpted_buffer == *buffer {
 4751                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4752                            let excerpt_range = excerpt_range.to_offset(buffer);
 4753                            buffer
 4754                                .edited_ranges_for_transaction::<usize>(transaction)
 4755                                .all(|range| {
 4756                                    excerpt_range.start <= range.start
 4757                                        && excerpt_range.end >= range.end
 4758                                })
 4759                        })?;
 4760
 4761                        if all_edits_within_excerpt {
 4762                            return Ok(());
 4763                        }
 4764                    }
 4765                }
 4766            }
 4767        } else {
 4768            return Ok(());
 4769        }
 4770
 4771        let mut ranges_to_highlight = Vec::new();
 4772        let excerpt_buffer = cx.new_model(|cx| {
 4773            let mut multibuffer =
 4774                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 4775            for (buffer_handle, transaction) in &entries {
 4776                let buffer = buffer_handle.read(cx);
 4777                ranges_to_highlight.extend(
 4778                    multibuffer.push_excerpts_with_context_lines(
 4779                        buffer_handle.clone(),
 4780                        buffer
 4781                            .edited_ranges_for_transaction::<usize>(transaction)
 4782                            .collect(),
 4783                        DEFAULT_MULTIBUFFER_CONTEXT,
 4784                        cx,
 4785                    ),
 4786                );
 4787            }
 4788            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4789            multibuffer
 4790        })?;
 4791
 4792        workspace.update(&mut cx, |workspace, cx| {
 4793            let project = workspace.project().clone();
 4794            let editor =
 4795                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4796            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4797            editor.update(cx, |editor, cx| {
 4798                editor.highlight_background::<Self>(
 4799                    &ranges_to_highlight,
 4800                    |theme| theme.editor_highlighted_line_background,
 4801                    cx,
 4802                );
 4803            });
 4804        })?;
 4805
 4806        Ok(())
 4807    }
 4808
 4809    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4810        let project = self.project.clone()?;
 4811        let buffer = self.buffer.read(cx);
 4812        let newest_selection = self.selections.newest_anchor().clone();
 4813        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4814        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4815        if start_buffer != end_buffer {
 4816            return None;
 4817        }
 4818
 4819        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4820            cx.background_executor()
 4821                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4822                .await;
 4823
 4824            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4825                project.code_actions(&start_buffer, start..end, cx)
 4826            }) {
 4827                code_actions.await
 4828            } else {
 4829                Vec::new()
 4830            };
 4831
 4832            this.update(&mut cx, |this, cx| {
 4833                this.available_code_actions = if actions.is_empty() {
 4834                    None
 4835                } else {
 4836                    Some((
 4837                        Location {
 4838                            buffer: start_buffer,
 4839                            range: start..end,
 4840                        },
 4841                        actions.into(),
 4842                    ))
 4843                };
 4844                cx.notify();
 4845            })
 4846            .log_err();
 4847        }));
 4848        None
 4849    }
 4850
 4851    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4852        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4853            self.show_git_blame_inline = false;
 4854
 4855            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4856                cx.background_executor().timer(delay).await;
 4857
 4858                this.update(&mut cx, |this, cx| {
 4859                    this.show_git_blame_inline = true;
 4860                    cx.notify();
 4861                })
 4862                .log_err();
 4863            }));
 4864        }
 4865    }
 4866
 4867    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4868        if self.pending_rename.is_some() {
 4869            return None;
 4870        }
 4871
 4872        let project = self.project.clone()?;
 4873        let buffer = self.buffer.read(cx);
 4874        let newest_selection = self.selections.newest_anchor().clone();
 4875        let cursor_position = newest_selection.head();
 4876        let (cursor_buffer, cursor_buffer_position) =
 4877            buffer.text_anchor_for_position(cursor_position, cx)?;
 4878        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4879        if cursor_buffer != tail_buffer {
 4880            return None;
 4881        }
 4882
 4883        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4884            cx.background_executor()
 4885                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4886                .await;
 4887
 4888            let highlights = if let Some(highlights) = project
 4889                .update(&mut cx, |project, cx| {
 4890                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4891                })
 4892                .log_err()
 4893            {
 4894                highlights.await.log_err()
 4895            } else {
 4896                None
 4897            };
 4898
 4899            if let Some(highlights) = highlights {
 4900                this.update(&mut cx, |this, cx| {
 4901                    if this.pending_rename.is_some() {
 4902                        return;
 4903                    }
 4904
 4905                    let buffer_id = cursor_position.buffer_id;
 4906                    let buffer = this.buffer.read(cx);
 4907                    if !buffer
 4908                        .text_anchor_for_position(cursor_position, cx)
 4909                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4910                    {
 4911                        return;
 4912                    }
 4913
 4914                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4915                    let mut write_ranges = Vec::new();
 4916                    let mut read_ranges = Vec::new();
 4917                    for highlight in highlights {
 4918                        for (excerpt_id, excerpt_range) in
 4919                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4920                        {
 4921                            let start = highlight
 4922                                .range
 4923                                .start
 4924                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4925                            let end = highlight
 4926                                .range
 4927                                .end
 4928                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4929                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4930                                continue;
 4931                            }
 4932
 4933                            let range = Anchor {
 4934                                buffer_id,
 4935                                excerpt_id,
 4936                                text_anchor: start,
 4937                            }..Anchor {
 4938                                buffer_id,
 4939                                excerpt_id,
 4940                                text_anchor: end,
 4941                            };
 4942                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4943                                write_ranges.push(range);
 4944                            } else {
 4945                                read_ranges.push(range);
 4946                            }
 4947                        }
 4948                    }
 4949
 4950                    this.highlight_background::<DocumentHighlightRead>(
 4951                        &read_ranges,
 4952                        |theme| theme.editor_document_highlight_read_background,
 4953                        cx,
 4954                    );
 4955                    this.highlight_background::<DocumentHighlightWrite>(
 4956                        &write_ranges,
 4957                        |theme| theme.editor_document_highlight_write_background,
 4958                        cx,
 4959                    );
 4960                    cx.notify();
 4961                })
 4962                .log_err();
 4963            }
 4964        }));
 4965        None
 4966    }
 4967
 4968    pub fn refresh_inline_completion(
 4969        &mut self,
 4970        debounce: bool,
 4971        user_requested: bool,
 4972        cx: &mut ViewContext<Self>,
 4973    ) -> Option<()> {
 4974        let provider = self.inline_completion_provider()?;
 4975        let cursor = self.selections.newest_anchor().head();
 4976        let (buffer, cursor_buffer_position) =
 4977            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4978        if !user_requested
 4979            && self.enable_inline_completions
 4980            && !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4981        {
 4982            self.discard_inline_completion(false, cx);
 4983            return None;
 4984        }
 4985
 4986        self.update_visible_inline_completion(cx);
 4987        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4988        Some(())
 4989    }
 4990
 4991    fn cycle_inline_completion(
 4992        &mut self,
 4993        direction: Direction,
 4994        cx: &mut ViewContext<Self>,
 4995    ) -> Option<()> {
 4996        let provider = self.inline_completion_provider()?;
 4997        let cursor = self.selections.newest_anchor().head();
 4998        let (buffer, cursor_buffer_position) =
 4999            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5000        if !self.enable_inline_completions
 5001            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5002        {
 5003            return None;
 5004        }
 5005
 5006        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5007        self.update_visible_inline_completion(cx);
 5008
 5009        Some(())
 5010    }
 5011
 5012    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5013        if !self.has_active_inline_completion(cx) {
 5014            self.refresh_inline_completion(false, true, cx);
 5015            return;
 5016        }
 5017
 5018        self.update_visible_inline_completion(cx);
 5019    }
 5020
 5021    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5022        self.show_cursor_names(cx);
 5023    }
 5024
 5025    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5026        self.show_cursor_names = true;
 5027        cx.notify();
 5028        cx.spawn(|this, mut cx| async move {
 5029            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5030            this.update(&mut cx, |this, cx| {
 5031                this.show_cursor_names = false;
 5032                cx.notify()
 5033            })
 5034            .ok()
 5035        })
 5036        .detach();
 5037    }
 5038
 5039    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5040        if self.has_active_inline_completion(cx) {
 5041            self.cycle_inline_completion(Direction::Next, cx);
 5042        } else {
 5043            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5044            if is_copilot_disabled {
 5045                cx.propagate();
 5046            }
 5047        }
 5048    }
 5049
 5050    pub fn previous_inline_completion(
 5051        &mut self,
 5052        _: &PreviousInlineCompletion,
 5053        cx: &mut ViewContext<Self>,
 5054    ) {
 5055        if self.has_active_inline_completion(cx) {
 5056            self.cycle_inline_completion(Direction::Prev, cx);
 5057        } else {
 5058            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5059            if is_copilot_disabled {
 5060                cx.propagate();
 5061            }
 5062        }
 5063    }
 5064
 5065    pub fn accept_inline_completion(
 5066        &mut self,
 5067        _: &AcceptInlineCompletion,
 5068        cx: &mut ViewContext<Self>,
 5069    ) {
 5070        let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
 5071            return;
 5072        };
 5073        if let Some(provider) = self.inline_completion_provider() {
 5074            provider.accept(cx);
 5075        }
 5076
 5077        cx.emit(EditorEvent::InputHandled {
 5078            utf16_range_to_replace: None,
 5079            text: completion.text.to_string().into(),
 5080        });
 5081
 5082        if let Some(range) = delete_range {
 5083            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5084        }
 5085        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5086        self.refresh_inline_completion(true, true, cx);
 5087        cx.notify();
 5088    }
 5089
 5090    pub fn accept_partial_inline_completion(
 5091        &mut self,
 5092        _: &AcceptPartialInlineCompletion,
 5093        cx: &mut ViewContext<Self>,
 5094    ) {
 5095        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5096            if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
 5097                let mut partial_completion = completion
 5098                    .text
 5099                    .chars()
 5100                    .by_ref()
 5101                    .take_while(|c| c.is_alphabetic())
 5102                    .collect::<String>();
 5103                if partial_completion.is_empty() {
 5104                    partial_completion = completion
 5105                        .text
 5106                        .chars()
 5107                        .by_ref()
 5108                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5109                        .collect::<String>();
 5110                }
 5111
 5112                cx.emit(EditorEvent::InputHandled {
 5113                    utf16_range_to_replace: None,
 5114                    text: partial_completion.clone().into(),
 5115                });
 5116
 5117                if let Some(range) = delete_range {
 5118                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5119                }
 5120                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5121
 5122                self.refresh_inline_completion(true, true, cx);
 5123                cx.notify();
 5124            }
 5125        }
 5126    }
 5127
 5128    fn discard_inline_completion(
 5129        &mut self,
 5130        should_report_inline_completion_event: bool,
 5131        cx: &mut ViewContext<Self>,
 5132    ) -> bool {
 5133        if let Some(provider) = self.inline_completion_provider() {
 5134            provider.discard(should_report_inline_completion_event, cx);
 5135        }
 5136
 5137        self.take_active_inline_completion(cx).is_some()
 5138    }
 5139
 5140    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5141        if let Some(completion) = self.active_inline_completion.as_ref() {
 5142            let buffer = self.buffer.read(cx).read(cx);
 5143            completion.0.position.is_valid(&buffer)
 5144        } else {
 5145            false
 5146        }
 5147    }
 5148
 5149    fn take_active_inline_completion(
 5150        &mut self,
 5151        cx: &mut ViewContext<Self>,
 5152    ) -> Option<(Inlay, Option<Range<Anchor>>)> {
 5153        let completion = self.active_inline_completion.take()?;
 5154        self.display_map.update(cx, |map, cx| {
 5155            map.splice_inlays(vec![completion.0.id], Default::default(), cx);
 5156        });
 5157        let buffer = self.buffer.read(cx).read(cx);
 5158
 5159        if completion.0.position.is_valid(&buffer) {
 5160            Some(completion)
 5161        } else {
 5162            None
 5163        }
 5164    }
 5165
 5166    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5167        let selection = self.selections.newest_anchor();
 5168        let cursor = selection.head();
 5169
 5170        let excerpt_id = cursor.excerpt_id;
 5171
 5172        if self.context_menu.read().is_none()
 5173            && self.completion_tasks.is_empty()
 5174            && selection.start == selection.end
 5175        {
 5176            if let Some(provider) = self.inline_completion_provider() {
 5177                if let Some((buffer, cursor_buffer_position)) =
 5178                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5179                {
 5180                    if let Some((text, text_anchor_range)) =
 5181                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5182                    {
 5183                        let text = Rope::from(text);
 5184                        let mut to_remove = Vec::new();
 5185                        if let Some(completion) = self.active_inline_completion.take() {
 5186                            to_remove.push(completion.0.id);
 5187                        }
 5188
 5189                        let completion_inlay =
 5190                            Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
 5191
 5192                        let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
 5193                            let snapshot = self.buffer.read(cx).snapshot(cx);
 5194                            Some(
 5195                                snapshot.anchor_in_excerpt(excerpt_id, range.start)?
 5196                                    ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
 5197                            )
 5198                        });
 5199                        self.active_inline_completion =
 5200                            Some((completion_inlay.clone(), multibuffer_anchor_range));
 5201
 5202                        self.display_map.update(cx, move |map, cx| {
 5203                            map.splice_inlays(to_remove, vec![completion_inlay], cx)
 5204                        });
 5205                        cx.notify();
 5206                        return;
 5207                    }
 5208                }
 5209            }
 5210        }
 5211
 5212        self.discard_inline_completion(false, cx);
 5213    }
 5214
 5215    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5216        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5217    }
 5218
 5219    fn render_code_actions_indicator(
 5220        &self,
 5221        _style: &EditorStyle,
 5222        row: DisplayRow,
 5223        is_active: bool,
 5224        cx: &mut ViewContext<Self>,
 5225    ) -> Option<IconButton> {
 5226        if self.available_code_actions.is_some() {
 5227            Some(
 5228                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5229                    .shape(ui::IconButtonShape::Square)
 5230                    .icon_size(IconSize::XSmall)
 5231                    .icon_color(Color::Muted)
 5232                    .selected(is_active)
 5233                    .on_click(cx.listener(move |editor, _e, cx| {
 5234                        editor.focus(cx);
 5235                        editor.toggle_code_actions(
 5236                            &ToggleCodeActions {
 5237                                deployed_from_indicator: Some(row),
 5238                            },
 5239                            cx,
 5240                        );
 5241                    })),
 5242            )
 5243        } else {
 5244            None
 5245        }
 5246    }
 5247
 5248    fn clear_tasks(&mut self) {
 5249        self.tasks.clear()
 5250    }
 5251
 5252    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5253        if self.tasks.insert(key, value).is_some() {
 5254            // This case should hopefully be rare, but just in case...
 5255            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5256        }
 5257    }
 5258
 5259    fn render_run_indicator(
 5260        &self,
 5261        _style: &EditorStyle,
 5262        is_active: bool,
 5263        row: DisplayRow,
 5264        cx: &mut ViewContext<Self>,
 5265    ) -> IconButton {
 5266        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5267            .shape(ui::IconButtonShape::Square)
 5268            .icon_size(IconSize::XSmall)
 5269            .icon_color(Color::Muted)
 5270            .selected(is_active)
 5271            .on_click(cx.listener(move |editor, _e, cx| {
 5272                editor.focus(cx);
 5273                editor.toggle_code_actions(
 5274                    &ToggleCodeActions {
 5275                        deployed_from_indicator: Some(row),
 5276                    },
 5277                    cx,
 5278                );
 5279            }))
 5280    }
 5281
 5282    fn close_hunk_diff_button(
 5283        &self,
 5284        hunk: HoveredHunk,
 5285        row: DisplayRow,
 5286        cx: &mut ViewContext<Self>,
 5287    ) -> IconButton {
 5288        IconButton::new(
 5289            ("close_hunk_diff_indicator", row.0 as usize),
 5290            ui::IconName::Close,
 5291        )
 5292        .shape(ui::IconButtonShape::Square)
 5293        .icon_size(IconSize::XSmall)
 5294        .icon_color(Color::Muted)
 5295        .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
 5296        .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
 5297    }
 5298
 5299    pub fn context_menu_visible(&self) -> bool {
 5300        self.context_menu
 5301            .read()
 5302            .as_ref()
 5303            .map_or(false, |menu| menu.visible())
 5304    }
 5305
 5306    fn render_context_menu(
 5307        &self,
 5308        cursor_position: DisplayPoint,
 5309        style: &EditorStyle,
 5310        max_height: Pixels,
 5311        cx: &mut ViewContext<Editor>,
 5312    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5313        self.context_menu.read().as_ref().map(|menu| {
 5314            menu.render(
 5315                cursor_position,
 5316                style,
 5317                max_height,
 5318                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5319                cx,
 5320            )
 5321        })
 5322    }
 5323
 5324    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5325        cx.notify();
 5326        self.completion_tasks.clear();
 5327        let context_menu = self.context_menu.write().take();
 5328        if context_menu.is_some() {
 5329            self.update_visible_inline_completion(cx);
 5330        }
 5331        context_menu
 5332    }
 5333
 5334    pub fn insert_snippet(
 5335        &mut self,
 5336        insertion_ranges: &[Range<usize>],
 5337        snippet: Snippet,
 5338        cx: &mut ViewContext<Self>,
 5339    ) -> Result<()> {
 5340        struct Tabstop<T> {
 5341            is_end_tabstop: bool,
 5342            ranges: Vec<Range<T>>,
 5343        }
 5344
 5345        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5346            let snippet_text: Arc<str> = snippet.text.clone().into();
 5347            buffer.edit(
 5348                insertion_ranges
 5349                    .iter()
 5350                    .cloned()
 5351                    .map(|range| (range, snippet_text.clone())),
 5352                Some(AutoindentMode::EachLine),
 5353                cx,
 5354            );
 5355
 5356            let snapshot = &*buffer.read(cx);
 5357            let snippet = &snippet;
 5358            snippet
 5359                .tabstops
 5360                .iter()
 5361                .map(|tabstop| {
 5362                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5363                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5364                    });
 5365                    let mut tabstop_ranges = tabstop
 5366                        .iter()
 5367                        .flat_map(|tabstop_range| {
 5368                            let mut delta = 0_isize;
 5369                            insertion_ranges.iter().map(move |insertion_range| {
 5370                                let insertion_start = insertion_range.start as isize + delta;
 5371                                delta +=
 5372                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5373
 5374                                let start = ((insertion_start + tabstop_range.start) as usize)
 5375                                    .min(snapshot.len());
 5376                                let end = ((insertion_start + tabstop_range.end) as usize)
 5377                                    .min(snapshot.len());
 5378                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5379                            })
 5380                        })
 5381                        .collect::<Vec<_>>();
 5382                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5383
 5384                    Tabstop {
 5385                        is_end_tabstop,
 5386                        ranges: tabstop_ranges,
 5387                    }
 5388                })
 5389                .collect::<Vec<_>>()
 5390        });
 5391        if let Some(tabstop) = tabstops.first() {
 5392            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5393                s.select_ranges(tabstop.ranges.iter().cloned());
 5394            });
 5395
 5396            // If we're already at the last tabstop and it's at the end of the snippet,
 5397            // we're done, we don't need to keep the state around.
 5398            if !tabstop.is_end_tabstop {
 5399                let ranges = tabstops
 5400                    .into_iter()
 5401                    .map(|tabstop| tabstop.ranges)
 5402                    .collect::<Vec<_>>();
 5403                self.snippet_stack.push(SnippetState {
 5404                    active_index: 0,
 5405                    ranges,
 5406                });
 5407            }
 5408
 5409            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5410            if self.autoclose_regions.is_empty() {
 5411                let snapshot = self.buffer.read(cx).snapshot(cx);
 5412                for selection in &mut self.selections.all::<Point>(cx) {
 5413                    let selection_head = selection.head();
 5414                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5415                        continue;
 5416                    };
 5417
 5418                    let mut bracket_pair = None;
 5419                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5420                    let prev_chars = snapshot
 5421                        .reversed_chars_at(selection_head)
 5422                        .collect::<String>();
 5423                    for (pair, enabled) in scope.brackets() {
 5424                        if enabled
 5425                            && pair.close
 5426                            && prev_chars.starts_with(pair.start.as_str())
 5427                            && next_chars.starts_with(pair.end.as_str())
 5428                        {
 5429                            bracket_pair = Some(pair.clone());
 5430                            break;
 5431                        }
 5432                    }
 5433                    if let Some(pair) = bracket_pair {
 5434                        let start = snapshot.anchor_after(selection_head);
 5435                        let end = snapshot.anchor_after(selection_head);
 5436                        self.autoclose_regions.push(AutocloseRegion {
 5437                            selection_id: selection.id,
 5438                            range: start..end,
 5439                            pair,
 5440                        });
 5441                    }
 5442                }
 5443            }
 5444        }
 5445        Ok(())
 5446    }
 5447
 5448    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5449        self.move_to_snippet_tabstop(Bias::Right, cx)
 5450    }
 5451
 5452    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5453        self.move_to_snippet_tabstop(Bias::Left, cx)
 5454    }
 5455
 5456    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5457        if let Some(mut snippet) = self.snippet_stack.pop() {
 5458            match bias {
 5459                Bias::Left => {
 5460                    if snippet.active_index > 0 {
 5461                        snippet.active_index -= 1;
 5462                    } else {
 5463                        self.snippet_stack.push(snippet);
 5464                        return false;
 5465                    }
 5466                }
 5467                Bias::Right => {
 5468                    if snippet.active_index + 1 < snippet.ranges.len() {
 5469                        snippet.active_index += 1;
 5470                    } else {
 5471                        self.snippet_stack.push(snippet);
 5472                        return false;
 5473                    }
 5474                }
 5475            }
 5476            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5477                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5478                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5479                });
 5480                // If snippet state is not at the last tabstop, push it back on the stack
 5481                if snippet.active_index + 1 < snippet.ranges.len() {
 5482                    self.snippet_stack.push(snippet);
 5483                }
 5484                return true;
 5485            }
 5486        }
 5487
 5488        false
 5489    }
 5490
 5491    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5492        self.transact(cx, |this, cx| {
 5493            this.select_all(&SelectAll, cx);
 5494            this.insert("", cx);
 5495        });
 5496    }
 5497
 5498    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5499        self.transact(cx, |this, cx| {
 5500            this.select_autoclose_pair(cx);
 5501            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5502            if !this.linked_edit_ranges.is_empty() {
 5503                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5504                let snapshot = this.buffer.read(cx).snapshot(cx);
 5505
 5506                for selection in selections.iter() {
 5507                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5508                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5509                    if selection_start.buffer_id != selection_end.buffer_id {
 5510                        continue;
 5511                    }
 5512                    if let Some(ranges) =
 5513                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5514                    {
 5515                        for (buffer, entries) in ranges {
 5516                            linked_ranges.entry(buffer).or_default().extend(entries);
 5517                        }
 5518                    }
 5519                }
 5520            }
 5521
 5522            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5523            if !this.selections.line_mode {
 5524                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5525                for selection in &mut selections {
 5526                    if selection.is_empty() {
 5527                        let old_head = selection.head();
 5528                        let mut new_head =
 5529                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5530                                .to_point(&display_map);
 5531                        if let Some((buffer, line_buffer_range)) = display_map
 5532                            .buffer_snapshot
 5533                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5534                        {
 5535                            let indent_size =
 5536                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5537                            let indent_len = match indent_size.kind {
 5538                                IndentKind::Space => {
 5539                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5540                                }
 5541                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5542                            };
 5543                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5544                                let indent_len = indent_len.get();
 5545                                new_head = cmp::min(
 5546                                    new_head,
 5547                                    MultiBufferPoint::new(
 5548                                        old_head.row,
 5549                                        ((old_head.column - 1) / indent_len) * indent_len,
 5550                                    ),
 5551                                );
 5552                            }
 5553                        }
 5554
 5555                        selection.set_head(new_head, SelectionGoal::None);
 5556                    }
 5557                }
 5558            }
 5559
 5560            this.signature_help_state.set_backspace_pressed(true);
 5561            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5562            this.insert("", cx);
 5563            let empty_str: Arc<str> = Arc::from("");
 5564            for (buffer, edits) in linked_ranges {
 5565                let snapshot = buffer.read(cx).snapshot();
 5566                use text::ToPoint as TP;
 5567
 5568                let edits = edits
 5569                    .into_iter()
 5570                    .map(|range| {
 5571                        let end_point = TP::to_point(&range.end, &snapshot);
 5572                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5573
 5574                        if end_point == start_point {
 5575                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5576                                .saturating_sub(1);
 5577                            start_point = TP::to_point(&offset, &snapshot);
 5578                        };
 5579
 5580                        (start_point..end_point, empty_str.clone())
 5581                    })
 5582                    .sorted_by_key(|(range, _)| range.start)
 5583                    .collect::<Vec<_>>();
 5584                buffer.update(cx, |this, cx| {
 5585                    this.edit(edits, None, cx);
 5586                })
 5587            }
 5588            this.refresh_inline_completion(true, false, cx);
 5589            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5590        });
 5591    }
 5592
 5593    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5594        self.transact(cx, |this, cx| {
 5595            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5596                let line_mode = s.line_mode;
 5597                s.move_with(|map, selection| {
 5598                    if selection.is_empty() && !line_mode {
 5599                        let cursor = movement::right(map, selection.head());
 5600                        selection.end = cursor;
 5601                        selection.reversed = true;
 5602                        selection.goal = SelectionGoal::None;
 5603                    }
 5604                })
 5605            });
 5606            this.insert("", cx);
 5607            this.refresh_inline_completion(true, false, cx);
 5608        });
 5609    }
 5610
 5611    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5612        if self.move_to_prev_snippet_tabstop(cx) {
 5613            return;
 5614        }
 5615
 5616        self.outdent(&Outdent, cx);
 5617    }
 5618
 5619    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5620        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5621            return;
 5622        }
 5623
 5624        let mut selections = self.selections.all_adjusted(cx);
 5625        let buffer = self.buffer.read(cx);
 5626        let snapshot = buffer.snapshot(cx);
 5627        let rows_iter = selections.iter().map(|s| s.head().row);
 5628        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5629
 5630        let mut edits = Vec::new();
 5631        let mut prev_edited_row = 0;
 5632        let mut row_delta = 0;
 5633        for selection in &mut selections {
 5634            if selection.start.row != prev_edited_row {
 5635                row_delta = 0;
 5636            }
 5637            prev_edited_row = selection.end.row;
 5638
 5639            // If the selection is non-empty, then increase the indentation of the selected lines.
 5640            if !selection.is_empty() {
 5641                row_delta =
 5642                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5643                continue;
 5644            }
 5645
 5646            // If the selection is empty and the cursor is in the leading whitespace before the
 5647            // suggested indentation, then auto-indent the line.
 5648            let cursor = selection.head();
 5649            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5650            if let Some(suggested_indent) =
 5651                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5652            {
 5653                if cursor.column < suggested_indent.len
 5654                    && cursor.column <= current_indent.len
 5655                    && current_indent.len <= suggested_indent.len
 5656                {
 5657                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5658                    selection.end = selection.start;
 5659                    if row_delta == 0 {
 5660                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5661                            cursor.row,
 5662                            current_indent,
 5663                            suggested_indent,
 5664                        ));
 5665                        row_delta = suggested_indent.len - current_indent.len;
 5666                    }
 5667                    continue;
 5668                }
 5669            }
 5670
 5671            // Otherwise, insert a hard or soft tab.
 5672            let settings = buffer.settings_at(cursor, cx);
 5673            let tab_size = if settings.hard_tabs {
 5674                IndentSize::tab()
 5675            } else {
 5676                let tab_size = settings.tab_size.get();
 5677                let char_column = snapshot
 5678                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5679                    .flat_map(str::chars)
 5680                    .count()
 5681                    + row_delta as usize;
 5682                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5683                IndentSize::spaces(chars_to_next_tab_stop)
 5684            };
 5685            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5686            selection.end = selection.start;
 5687            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5688            row_delta += tab_size.len;
 5689        }
 5690
 5691        self.transact(cx, |this, cx| {
 5692            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5693            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5694            this.refresh_inline_completion(true, false, cx);
 5695        });
 5696    }
 5697
 5698    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5699        if self.read_only(cx) {
 5700            return;
 5701        }
 5702        let mut selections = self.selections.all::<Point>(cx);
 5703        let mut prev_edited_row = 0;
 5704        let mut row_delta = 0;
 5705        let mut edits = Vec::new();
 5706        let buffer = self.buffer.read(cx);
 5707        let snapshot = buffer.snapshot(cx);
 5708        for selection in &mut selections {
 5709            if selection.start.row != prev_edited_row {
 5710                row_delta = 0;
 5711            }
 5712            prev_edited_row = selection.end.row;
 5713
 5714            row_delta =
 5715                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5716        }
 5717
 5718        self.transact(cx, |this, cx| {
 5719            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5720            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5721        });
 5722    }
 5723
 5724    fn indent_selection(
 5725        buffer: &MultiBuffer,
 5726        snapshot: &MultiBufferSnapshot,
 5727        selection: &mut Selection<Point>,
 5728        edits: &mut Vec<(Range<Point>, String)>,
 5729        delta_for_start_row: u32,
 5730        cx: &AppContext,
 5731    ) -> u32 {
 5732        let settings = buffer.settings_at(selection.start, cx);
 5733        let tab_size = settings.tab_size.get();
 5734        let indent_kind = if settings.hard_tabs {
 5735            IndentKind::Tab
 5736        } else {
 5737            IndentKind::Space
 5738        };
 5739        let mut start_row = selection.start.row;
 5740        let mut end_row = selection.end.row + 1;
 5741
 5742        // If a selection ends at the beginning of a line, don't indent
 5743        // that last line.
 5744        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5745            end_row -= 1;
 5746        }
 5747
 5748        // Avoid re-indenting a row that has already been indented by a
 5749        // previous selection, but still update this selection's column
 5750        // to reflect that indentation.
 5751        if delta_for_start_row > 0 {
 5752            start_row += 1;
 5753            selection.start.column += delta_for_start_row;
 5754            if selection.end.row == selection.start.row {
 5755                selection.end.column += delta_for_start_row;
 5756            }
 5757        }
 5758
 5759        let mut delta_for_end_row = 0;
 5760        let has_multiple_rows = start_row + 1 != end_row;
 5761        for row in start_row..end_row {
 5762            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5763            let indent_delta = match (current_indent.kind, indent_kind) {
 5764                (IndentKind::Space, IndentKind::Space) => {
 5765                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5766                    IndentSize::spaces(columns_to_next_tab_stop)
 5767                }
 5768                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5769                (_, IndentKind::Tab) => IndentSize::tab(),
 5770            };
 5771
 5772            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5773                0
 5774            } else {
 5775                selection.start.column
 5776            };
 5777            let row_start = Point::new(row, start);
 5778            edits.push((
 5779                row_start..row_start,
 5780                indent_delta.chars().collect::<String>(),
 5781            ));
 5782
 5783            // Update this selection's endpoints to reflect the indentation.
 5784            if row == selection.start.row {
 5785                selection.start.column += indent_delta.len;
 5786            }
 5787            if row == selection.end.row {
 5788                selection.end.column += indent_delta.len;
 5789                delta_for_end_row = indent_delta.len;
 5790            }
 5791        }
 5792
 5793        if selection.start.row == selection.end.row {
 5794            delta_for_start_row + delta_for_end_row
 5795        } else {
 5796            delta_for_end_row
 5797        }
 5798    }
 5799
 5800    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5801        if self.read_only(cx) {
 5802            return;
 5803        }
 5804        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5805        let selections = self.selections.all::<Point>(cx);
 5806        let mut deletion_ranges = Vec::new();
 5807        let mut last_outdent = None;
 5808        {
 5809            let buffer = self.buffer.read(cx);
 5810            let snapshot = buffer.snapshot(cx);
 5811            for selection in &selections {
 5812                let settings = buffer.settings_at(selection.start, cx);
 5813                let tab_size = settings.tab_size.get();
 5814                let mut rows = selection.spanned_rows(false, &display_map);
 5815
 5816                // Avoid re-outdenting a row that has already been outdented by a
 5817                // previous selection.
 5818                if let Some(last_row) = last_outdent {
 5819                    if last_row == rows.start {
 5820                        rows.start = rows.start.next_row();
 5821                    }
 5822                }
 5823                let has_multiple_rows = rows.len() > 1;
 5824                for row in rows.iter_rows() {
 5825                    let indent_size = snapshot.indent_size_for_line(row);
 5826                    if indent_size.len > 0 {
 5827                        let deletion_len = match indent_size.kind {
 5828                            IndentKind::Space => {
 5829                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5830                                if columns_to_prev_tab_stop == 0 {
 5831                                    tab_size
 5832                                } else {
 5833                                    columns_to_prev_tab_stop
 5834                                }
 5835                            }
 5836                            IndentKind::Tab => 1,
 5837                        };
 5838                        let start = if has_multiple_rows
 5839                            || deletion_len > selection.start.column
 5840                            || indent_size.len < selection.start.column
 5841                        {
 5842                            0
 5843                        } else {
 5844                            selection.start.column - deletion_len
 5845                        };
 5846                        deletion_ranges.push(
 5847                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5848                        );
 5849                        last_outdent = Some(row);
 5850                    }
 5851                }
 5852            }
 5853        }
 5854
 5855        self.transact(cx, |this, cx| {
 5856            this.buffer.update(cx, |buffer, cx| {
 5857                let empty_str: Arc<str> = Arc::default();
 5858                buffer.edit(
 5859                    deletion_ranges
 5860                        .into_iter()
 5861                        .map(|range| (range, empty_str.clone())),
 5862                    None,
 5863                    cx,
 5864                );
 5865            });
 5866            let selections = this.selections.all::<usize>(cx);
 5867            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5868        });
 5869    }
 5870
 5871    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5872        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5873        let selections = self.selections.all::<Point>(cx);
 5874
 5875        let mut new_cursors = Vec::new();
 5876        let mut edit_ranges = Vec::new();
 5877        let mut selections = selections.iter().peekable();
 5878        while let Some(selection) = selections.next() {
 5879            let mut rows = selection.spanned_rows(false, &display_map);
 5880            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5881
 5882            // Accumulate contiguous regions of rows that we want to delete.
 5883            while let Some(next_selection) = selections.peek() {
 5884                let next_rows = next_selection.spanned_rows(false, &display_map);
 5885                if next_rows.start <= rows.end {
 5886                    rows.end = next_rows.end;
 5887                    selections.next().unwrap();
 5888                } else {
 5889                    break;
 5890                }
 5891            }
 5892
 5893            let buffer = &display_map.buffer_snapshot;
 5894            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5895            let edit_end;
 5896            let cursor_buffer_row;
 5897            if buffer.max_point().row >= rows.end.0 {
 5898                // If there's a line after the range, delete the \n from the end of the row range
 5899                // and position the cursor on the next line.
 5900                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5901                cursor_buffer_row = rows.end;
 5902            } else {
 5903                // If there isn't a line after the range, delete the \n from the line before the
 5904                // start of the row range and position the cursor there.
 5905                edit_start = edit_start.saturating_sub(1);
 5906                edit_end = buffer.len();
 5907                cursor_buffer_row = rows.start.previous_row();
 5908            }
 5909
 5910            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5911            *cursor.column_mut() =
 5912                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5913
 5914            new_cursors.push((
 5915                selection.id,
 5916                buffer.anchor_after(cursor.to_point(&display_map)),
 5917            ));
 5918            edit_ranges.push(edit_start..edit_end);
 5919        }
 5920
 5921        self.transact(cx, |this, cx| {
 5922            let buffer = this.buffer.update(cx, |buffer, cx| {
 5923                let empty_str: Arc<str> = Arc::default();
 5924                buffer.edit(
 5925                    edit_ranges
 5926                        .into_iter()
 5927                        .map(|range| (range, empty_str.clone())),
 5928                    None,
 5929                    cx,
 5930                );
 5931                buffer.snapshot(cx)
 5932            });
 5933            let new_selections = new_cursors
 5934                .into_iter()
 5935                .map(|(id, cursor)| {
 5936                    let cursor = cursor.to_point(&buffer);
 5937                    Selection {
 5938                        id,
 5939                        start: cursor,
 5940                        end: cursor,
 5941                        reversed: false,
 5942                        goal: SelectionGoal::None,
 5943                    }
 5944                })
 5945                .collect();
 5946
 5947            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5948                s.select(new_selections);
 5949            });
 5950        });
 5951    }
 5952
 5953    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5954        if self.read_only(cx) {
 5955            return;
 5956        }
 5957        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5958        for selection in self.selections.all::<Point>(cx) {
 5959            let start = MultiBufferRow(selection.start.row);
 5960            let end = if selection.start.row == selection.end.row {
 5961                MultiBufferRow(selection.start.row + 1)
 5962            } else {
 5963                MultiBufferRow(selection.end.row)
 5964            };
 5965
 5966            if let Some(last_row_range) = row_ranges.last_mut() {
 5967                if start <= last_row_range.end {
 5968                    last_row_range.end = end;
 5969                    continue;
 5970                }
 5971            }
 5972            row_ranges.push(start..end);
 5973        }
 5974
 5975        let snapshot = self.buffer.read(cx).snapshot(cx);
 5976        let mut cursor_positions = Vec::new();
 5977        for row_range in &row_ranges {
 5978            let anchor = snapshot.anchor_before(Point::new(
 5979                row_range.end.previous_row().0,
 5980                snapshot.line_len(row_range.end.previous_row()),
 5981            ));
 5982            cursor_positions.push(anchor..anchor);
 5983        }
 5984
 5985        self.transact(cx, |this, cx| {
 5986            for row_range in row_ranges.into_iter().rev() {
 5987                for row in row_range.iter_rows().rev() {
 5988                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5989                    let next_line_row = row.next_row();
 5990                    let indent = snapshot.indent_size_for_line(next_line_row);
 5991                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5992
 5993                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5994                        " "
 5995                    } else {
 5996                        ""
 5997                    };
 5998
 5999                    this.buffer.update(cx, |buffer, cx| {
 6000                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6001                    });
 6002                }
 6003            }
 6004
 6005            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6006                s.select_anchor_ranges(cursor_positions)
 6007            });
 6008        });
 6009    }
 6010
 6011    pub fn sort_lines_case_sensitive(
 6012        &mut self,
 6013        _: &SortLinesCaseSensitive,
 6014        cx: &mut ViewContext<Self>,
 6015    ) {
 6016        self.manipulate_lines(cx, |lines| lines.sort())
 6017    }
 6018
 6019    pub fn sort_lines_case_insensitive(
 6020        &mut self,
 6021        _: &SortLinesCaseInsensitive,
 6022        cx: &mut ViewContext<Self>,
 6023    ) {
 6024        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6025    }
 6026
 6027    pub fn unique_lines_case_insensitive(
 6028        &mut self,
 6029        _: &UniqueLinesCaseInsensitive,
 6030        cx: &mut ViewContext<Self>,
 6031    ) {
 6032        self.manipulate_lines(cx, |lines| {
 6033            let mut seen = HashSet::default();
 6034            lines.retain(|line| seen.insert(line.to_lowercase()));
 6035        })
 6036    }
 6037
 6038    pub fn unique_lines_case_sensitive(
 6039        &mut self,
 6040        _: &UniqueLinesCaseSensitive,
 6041        cx: &mut ViewContext<Self>,
 6042    ) {
 6043        self.manipulate_lines(cx, |lines| {
 6044            let mut seen = HashSet::default();
 6045            lines.retain(|line| seen.insert(*line));
 6046        })
 6047    }
 6048
 6049    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6050        let mut revert_changes = HashMap::default();
 6051        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6052        for hunk in hunks_for_rows(
 6053            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6054            &multi_buffer_snapshot,
 6055        ) {
 6056            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6057        }
 6058        if !revert_changes.is_empty() {
 6059            self.transact(cx, |editor, cx| {
 6060                editor.revert(revert_changes, cx);
 6061            });
 6062        }
 6063    }
 6064
 6065    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6066        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6067        if !revert_changes.is_empty() {
 6068            self.transact(cx, |editor, cx| {
 6069                editor.revert(revert_changes, cx);
 6070            });
 6071        }
 6072    }
 6073
 6074    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6075        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6076            let project_path = buffer.read(cx).project_path(cx)?;
 6077            let project = self.project.as_ref()?.read(cx);
 6078            let entry = project.entry_for_path(&project_path, cx)?;
 6079            let abs_path = project.absolute_path(&project_path, cx)?;
 6080            let parent = if entry.is_symlink {
 6081                abs_path.canonicalize().ok()?
 6082            } else {
 6083                abs_path
 6084            }
 6085            .parent()?
 6086            .to_path_buf();
 6087            Some(parent)
 6088        }) {
 6089            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6090        }
 6091    }
 6092
 6093    fn gather_revert_changes(
 6094        &mut self,
 6095        selections: &[Selection<Anchor>],
 6096        cx: &mut ViewContext<'_, Editor>,
 6097    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6098        let mut revert_changes = HashMap::default();
 6099        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6100        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6101            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6102        }
 6103        revert_changes
 6104    }
 6105
 6106    pub fn prepare_revert_change(
 6107        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6108        multi_buffer: &Model<MultiBuffer>,
 6109        hunk: &DiffHunk<MultiBufferRow>,
 6110        cx: &AppContext,
 6111    ) -> Option<()> {
 6112        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6113        let buffer = buffer.read(cx);
 6114        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6115        let buffer_snapshot = buffer.snapshot();
 6116        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6117        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6118            probe
 6119                .0
 6120                .start
 6121                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6122                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6123        }) {
 6124            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6125            Some(())
 6126        } else {
 6127            None
 6128        }
 6129    }
 6130
 6131    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6132        self.manipulate_lines(cx, |lines| lines.reverse())
 6133    }
 6134
 6135    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6136        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6137    }
 6138
 6139    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6140    where
 6141        Fn: FnMut(&mut Vec<&str>),
 6142    {
 6143        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6144        let buffer = self.buffer.read(cx).snapshot(cx);
 6145
 6146        let mut edits = Vec::new();
 6147
 6148        let selections = self.selections.all::<Point>(cx);
 6149        let mut selections = selections.iter().peekable();
 6150        let mut contiguous_row_selections = Vec::new();
 6151        let mut new_selections = Vec::new();
 6152        let mut added_lines = 0;
 6153        let mut removed_lines = 0;
 6154
 6155        while let Some(selection) = selections.next() {
 6156            let (start_row, end_row) = consume_contiguous_rows(
 6157                &mut contiguous_row_selections,
 6158                selection,
 6159                &display_map,
 6160                &mut selections,
 6161            );
 6162
 6163            let start_point = Point::new(start_row.0, 0);
 6164            let end_point = Point::new(
 6165                end_row.previous_row().0,
 6166                buffer.line_len(end_row.previous_row()),
 6167            );
 6168            let text = buffer
 6169                .text_for_range(start_point..end_point)
 6170                .collect::<String>();
 6171
 6172            let mut lines = text.split('\n').collect_vec();
 6173
 6174            let lines_before = lines.len();
 6175            callback(&mut lines);
 6176            let lines_after = lines.len();
 6177
 6178            edits.push((start_point..end_point, lines.join("\n")));
 6179
 6180            // Selections must change based on added and removed line count
 6181            let start_row =
 6182                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6183            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6184            new_selections.push(Selection {
 6185                id: selection.id,
 6186                start: start_row,
 6187                end: end_row,
 6188                goal: SelectionGoal::None,
 6189                reversed: selection.reversed,
 6190            });
 6191
 6192            if lines_after > lines_before {
 6193                added_lines += lines_after - lines_before;
 6194            } else if lines_before > lines_after {
 6195                removed_lines += lines_before - lines_after;
 6196            }
 6197        }
 6198
 6199        self.transact(cx, |this, cx| {
 6200            let buffer = this.buffer.update(cx, |buffer, cx| {
 6201                buffer.edit(edits, None, cx);
 6202                buffer.snapshot(cx)
 6203            });
 6204
 6205            // Recalculate offsets on newly edited buffer
 6206            let new_selections = new_selections
 6207                .iter()
 6208                .map(|s| {
 6209                    let start_point = Point::new(s.start.0, 0);
 6210                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6211                    Selection {
 6212                        id: s.id,
 6213                        start: buffer.point_to_offset(start_point),
 6214                        end: buffer.point_to_offset(end_point),
 6215                        goal: s.goal,
 6216                        reversed: s.reversed,
 6217                    }
 6218                })
 6219                .collect();
 6220
 6221            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6222                s.select(new_selections);
 6223            });
 6224
 6225            this.request_autoscroll(Autoscroll::fit(), cx);
 6226        });
 6227    }
 6228
 6229    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6230        self.manipulate_text(cx, |text| text.to_uppercase())
 6231    }
 6232
 6233    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6234        self.manipulate_text(cx, |text| text.to_lowercase())
 6235    }
 6236
 6237    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6238        self.manipulate_text(cx, |text| {
 6239            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6240            // https://github.com/rutrum/convert-case/issues/16
 6241            text.split('\n')
 6242                .map(|line| line.to_case(Case::Title))
 6243                .join("\n")
 6244        })
 6245    }
 6246
 6247    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6248        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6249    }
 6250
 6251    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6252        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6253    }
 6254
 6255    pub fn convert_to_upper_camel_case(
 6256        &mut self,
 6257        _: &ConvertToUpperCamelCase,
 6258        cx: &mut ViewContext<Self>,
 6259    ) {
 6260        self.manipulate_text(cx, |text| {
 6261            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6262            // https://github.com/rutrum/convert-case/issues/16
 6263            text.split('\n')
 6264                .map(|line| line.to_case(Case::UpperCamel))
 6265                .join("\n")
 6266        })
 6267    }
 6268
 6269    pub fn convert_to_lower_camel_case(
 6270        &mut self,
 6271        _: &ConvertToLowerCamelCase,
 6272        cx: &mut ViewContext<Self>,
 6273    ) {
 6274        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6275    }
 6276
 6277    pub fn convert_to_opposite_case(
 6278        &mut self,
 6279        _: &ConvertToOppositeCase,
 6280        cx: &mut ViewContext<Self>,
 6281    ) {
 6282        self.manipulate_text(cx, |text| {
 6283            text.chars()
 6284                .fold(String::with_capacity(text.len()), |mut t, c| {
 6285                    if c.is_uppercase() {
 6286                        t.extend(c.to_lowercase());
 6287                    } else {
 6288                        t.extend(c.to_uppercase());
 6289                    }
 6290                    t
 6291                })
 6292        })
 6293    }
 6294
 6295    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6296    where
 6297        Fn: FnMut(&str) -> String,
 6298    {
 6299        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6300        let buffer = self.buffer.read(cx).snapshot(cx);
 6301
 6302        let mut new_selections = Vec::new();
 6303        let mut edits = Vec::new();
 6304        let mut selection_adjustment = 0i32;
 6305
 6306        for selection in self.selections.all::<usize>(cx) {
 6307            let selection_is_empty = selection.is_empty();
 6308
 6309            let (start, end) = if selection_is_empty {
 6310                let word_range = movement::surrounding_word(
 6311                    &display_map,
 6312                    selection.start.to_display_point(&display_map),
 6313                );
 6314                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6315                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6316                (start, end)
 6317            } else {
 6318                (selection.start, selection.end)
 6319            };
 6320
 6321            let text = buffer.text_for_range(start..end).collect::<String>();
 6322            let old_length = text.len() as i32;
 6323            let text = callback(&text);
 6324
 6325            new_selections.push(Selection {
 6326                start: (start as i32 - selection_adjustment) as usize,
 6327                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6328                goal: SelectionGoal::None,
 6329                ..selection
 6330            });
 6331
 6332            selection_adjustment += old_length - text.len() as i32;
 6333
 6334            edits.push((start..end, text));
 6335        }
 6336
 6337        self.transact(cx, |this, cx| {
 6338            this.buffer.update(cx, |buffer, cx| {
 6339                buffer.edit(edits, None, cx);
 6340            });
 6341
 6342            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6343                s.select(new_selections);
 6344            });
 6345
 6346            this.request_autoscroll(Autoscroll::fit(), cx);
 6347        });
 6348    }
 6349
 6350    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6351        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6352        let buffer = &display_map.buffer_snapshot;
 6353        let selections = self.selections.all::<Point>(cx);
 6354
 6355        let mut edits = Vec::new();
 6356        let mut selections_iter = selections.iter().peekable();
 6357        while let Some(selection) = selections_iter.next() {
 6358            // Avoid duplicating the same lines twice.
 6359            let mut rows = selection.spanned_rows(false, &display_map);
 6360
 6361            while let Some(next_selection) = selections_iter.peek() {
 6362                let next_rows = next_selection.spanned_rows(false, &display_map);
 6363                if next_rows.start < rows.end {
 6364                    rows.end = next_rows.end;
 6365                    selections_iter.next().unwrap();
 6366                } else {
 6367                    break;
 6368                }
 6369            }
 6370
 6371            // Copy the text from the selected row region and splice it either at the start
 6372            // or end of the region.
 6373            let start = Point::new(rows.start.0, 0);
 6374            let end = Point::new(
 6375                rows.end.previous_row().0,
 6376                buffer.line_len(rows.end.previous_row()),
 6377            );
 6378            let text = buffer
 6379                .text_for_range(start..end)
 6380                .chain(Some("\n"))
 6381                .collect::<String>();
 6382            let insert_location = if upwards {
 6383                Point::new(rows.end.0, 0)
 6384            } else {
 6385                start
 6386            };
 6387            edits.push((insert_location..insert_location, text));
 6388        }
 6389
 6390        self.transact(cx, |this, cx| {
 6391            this.buffer.update(cx, |buffer, cx| {
 6392                buffer.edit(edits, None, cx);
 6393            });
 6394
 6395            this.request_autoscroll(Autoscroll::fit(), cx);
 6396        });
 6397    }
 6398
 6399    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6400        self.duplicate_line(true, cx);
 6401    }
 6402
 6403    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6404        self.duplicate_line(false, cx);
 6405    }
 6406
 6407    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6408        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6409        let buffer = self.buffer.read(cx).snapshot(cx);
 6410
 6411        let mut edits = Vec::new();
 6412        let mut unfold_ranges = Vec::new();
 6413        let mut refold_ranges = Vec::new();
 6414
 6415        let selections = self.selections.all::<Point>(cx);
 6416        let mut selections = selections.iter().peekable();
 6417        let mut contiguous_row_selections = Vec::new();
 6418        let mut new_selections = Vec::new();
 6419
 6420        while let Some(selection) = selections.next() {
 6421            // Find all the selections that span a contiguous row range
 6422            let (start_row, end_row) = consume_contiguous_rows(
 6423                &mut contiguous_row_selections,
 6424                selection,
 6425                &display_map,
 6426                &mut selections,
 6427            );
 6428
 6429            // Move the text spanned by the row range to be before the line preceding the row range
 6430            if start_row.0 > 0 {
 6431                let range_to_move = Point::new(
 6432                    start_row.previous_row().0,
 6433                    buffer.line_len(start_row.previous_row()),
 6434                )
 6435                    ..Point::new(
 6436                        end_row.previous_row().0,
 6437                        buffer.line_len(end_row.previous_row()),
 6438                    );
 6439                let insertion_point = display_map
 6440                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6441                    .0;
 6442
 6443                // Don't move lines across excerpts
 6444                if buffer
 6445                    .excerpt_boundaries_in_range((
 6446                        Bound::Excluded(insertion_point),
 6447                        Bound::Included(range_to_move.end),
 6448                    ))
 6449                    .next()
 6450                    .is_none()
 6451                {
 6452                    let text = buffer
 6453                        .text_for_range(range_to_move.clone())
 6454                        .flat_map(|s| s.chars())
 6455                        .skip(1)
 6456                        .chain(['\n'])
 6457                        .collect::<String>();
 6458
 6459                    edits.push((
 6460                        buffer.anchor_after(range_to_move.start)
 6461                            ..buffer.anchor_before(range_to_move.end),
 6462                        String::new(),
 6463                    ));
 6464                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6465                    edits.push((insertion_anchor..insertion_anchor, text));
 6466
 6467                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6468
 6469                    // Move selections up
 6470                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6471                        |mut selection| {
 6472                            selection.start.row -= row_delta;
 6473                            selection.end.row -= row_delta;
 6474                            selection
 6475                        },
 6476                    ));
 6477
 6478                    // Move folds up
 6479                    unfold_ranges.push(range_to_move.clone());
 6480                    for fold in display_map.folds_in_range(
 6481                        buffer.anchor_before(range_to_move.start)
 6482                            ..buffer.anchor_after(range_to_move.end),
 6483                    ) {
 6484                        let mut start = fold.range.start.to_point(&buffer);
 6485                        let mut end = fold.range.end.to_point(&buffer);
 6486                        start.row -= row_delta;
 6487                        end.row -= row_delta;
 6488                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6489                    }
 6490                }
 6491            }
 6492
 6493            // If we didn't move line(s), preserve the existing selections
 6494            new_selections.append(&mut contiguous_row_selections);
 6495        }
 6496
 6497        self.transact(cx, |this, cx| {
 6498            this.unfold_ranges(unfold_ranges, true, true, cx);
 6499            this.buffer.update(cx, |buffer, cx| {
 6500                for (range, text) in edits {
 6501                    buffer.edit([(range, text)], None, cx);
 6502                }
 6503            });
 6504            this.fold_ranges(refold_ranges, true, cx);
 6505            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6506                s.select(new_selections);
 6507            })
 6508        });
 6509    }
 6510
 6511    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6512        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6513        let buffer = self.buffer.read(cx).snapshot(cx);
 6514
 6515        let mut edits = Vec::new();
 6516        let mut unfold_ranges = Vec::new();
 6517        let mut refold_ranges = Vec::new();
 6518
 6519        let selections = self.selections.all::<Point>(cx);
 6520        let mut selections = selections.iter().peekable();
 6521        let mut contiguous_row_selections = Vec::new();
 6522        let mut new_selections = Vec::new();
 6523
 6524        while let Some(selection) = selections.next() {
 6525            // Find all the selections that span a contiguous row range
 6526            let (start_row, end_row) = consume_contiguous_rows(
 6527                &mut contiguous_row_selections,
 6528                selection,
 6529                &display_map,
 6530                &mut selections,
 6531            );
 6532
 6533            // Move the text spanned by the row range to be after the last line of the row range
 6534            if end_row.0 <= buffer.max_point().row {
 6535                let range_to_move =
 6536                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6537                let insertion_point = display_map
 6538                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6539                    .0;
 6540
 6541                // Don't move lines across excerpt boundaries
 6542                if buffer
 6543                    .excerpt_boundaries_in_range((
 6544                        Bound::Excluded(range_to_move.start),
 6545                        Bound::Included(insertion_point),
 6546                    ))
 6547                    .next()
 6548                    .is_none()
 6549                {
 6550                    let mut text = String::from("\n");
 6551                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6552                    text.pop(); // Drop trailing newline
 6553                    edits.push((
 6554                        buffer.anchor_after(range_to_move.start)
 6555                            ..buffer.anchor_before(range_to_move.end),
 6556                        String::new(),
 6557                    ));
 6558                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6559                    edits.push((insertion_anchor..insertion_anchor, text));
 6560
 6561                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6562
 6563                    // Move selections down
 6564                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6565                        |mut selection| {
 6566                            selection.start.row += row_delta;
 6567                            selection.end.row += row_delta;
 6568                            selection
 6569                        },
 6570                    ));
 6571
 6572                    // Move folds down
 6573                    unfold_ranges.push(range_to_move.clone());
 6574                    for fold in display_map.folds_in_range(
 6575                        buffer.anchor_before(range_to_move.start)
 6576                            ..buffer.anchor_after(range_to_move.end),
 6577                    ) {
 6578                        let mut start = fold.range.start.to_point(&buffer);
 6579                        let mut end = fold.range.end.to_point(&buffer);
 6580                        start.row += row_delta;
 6581                        end.row += row_delta;
 6582                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6583                    }
 6584                }
 6585            }
 6586
 6587            // If we didn't move line(s), preserve the existing selections
 6588            new_selections.append(&mut contiguous_row_selections);
 6589        }
 6590
 6591        self.transact(cx, |this, cx| {
 6592            this.unfold_ranges(unfold_ranges, true, true, cx);
 6593            this.buffer.update(cx, |buffer, cx| {
 6594                for (range, text) in edits {
 6595                    buffer.edit([(range, text)], None, cx);
 6596                }
 6597            });
 6598            this.fold_ranges(refold_ranges, true, cx);
 6599            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6600        });
 6601    }
 6602
 6603    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6604        let text_layout_details = &self.text_layout_details(cx);
 6605        self.transact(cx, |this, cx| {
 6606            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6607                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6608                let line_mode = s.line_mode;
 6609                s.move_with(|display_map, selection| {
 6610                    if !selection.is_empty() || line_mode {
 6611                        return;
 6612                    }
 6613
 6614                    let mut head = selection.head();
 6615                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6616                    if head.column() == display_map.line_len(head.row()) {
 6617                        transpose_offset = display_map
 6618                            .buffer_snapshot
 6619                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6620                    }
 6621
 6622                    if transpose_offset == 0 {
 6623                        return;
 6624                    }
 6625
 6626                    *head.column_mut() += 1;
 6627                    head = display_map.clip_point(head, Bias::Right);
 6628                    let goal = SelectionGoal::HorizontalPosition(
 6629                        display_map
 6630                            .x_for_display_point(head, text_layout_details)
 6631                            .into(),
 6632                    );
 6633                    selection.collapse_to(head, goal);
 6634
 6635                    let transpose_start = display_map
 6636                        .buffer_snapshot
 6637                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6638                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6639                        let transpose_end = display_map
 6640                            .buffer_snapshot
 6641                            .clip_offset(transpose_offset + 1, Bias::Right);
 6642                        if let Some(ch) =
 6643                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6644                        {
 6645                            edits.push((transpose_start..transpose_offset, String::new()));
 6646                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6647                        }
 6648                    }
 6649                });
 6650                edits
 6651            });
 6652            this.buffer
 6653                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6654            let selections = this.selections.all::<usize>(cx);
 6655            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6656                s.select(selections);
 6657            });
 6658        });
 6659    }
 6660
 6661    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6662        let mut text = String::new();
 6663        let buffer = self.buffer.read(cx).snapshot(cx);
 6664        let mut selections = self.selections.all::<Point>(cx);
 6665        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6666        {
 6667            let max_point = buffer.max_point();
 6668            let mut is_first = true;
 6669            for selection in &mut selections {
 6670                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6671                if is_entire_line {
 6672                    selection.start = Point::new(selection.start.row, 0);
 6673                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6674                    selection.goal = SelectionGoal::None;
 6675                }
 6676                if is_first {
 6677                    is_first = false;
 6678                } else {
 6679                    text += "\n";
 6680                }
 6681                let mut len = 0;
 6682                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6683                    text.push_str(chunk);
 6684                    len += chunk.len();
 6685                }
 6686                clipboard_selections.push(ClipboardSelection {
 6687                    len,
 6688                    is_entire_line,
 6689                    first_line_indent: buffer
 6690                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6691                        .len,
 6692                });
 6693            }
 6694        }
 6695
 6696        self.transact(cx, |this, cx| {
 6697            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6698                s.select(selections);
 6699            });
 6700            this.insert("", cx);
 6701            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6702                text,
 6703                clipboard_selections,
 6704            ));
 6705        });
 6706    }
 6707
 6708    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6709        let selections = self.selections.all::<Point>(cx);
 6710        let buffer = self.buffer.read(cx).read(cx);
 6711        let mut text = String::new();
 6712
 6713        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6714        {
 6715            let max_point = buffer.max_point();
 6716            let mut is_first = true;
 6717            for selection in selections.iter() {
 6718                let mut start = selection.start;
 6719                let mut end = selection.end;
 6720                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6721                if is_entire_line {
 6722                    start = Point::new(start.row, 0);
 6723                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6724                }
 6725                if is_first {
 6726                    is_first = false;
 6727                } else {
 6728                    text += "\n";
 6729                }
 6730                let mut len = 0;
 6731                for chunk in buffer.text_for_range(start..end) {
 6732                    text.push_str(chunk);
 6733                    len += chunk.len();
 6734                }
 6735                clipboard_selections.push(ClipboardSelection {
 6736                    len,
 6737                    is_entire_line,
 6738                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6739                });
 6740            }
 6741        }
 6742
 6743        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6744            text,
 6745            clipboard_selections,
 6746        ));
 6747    }
 6748
 6749    pub fn do_paste(
 6750        &mut self,
 6751        text: &String,
 6752        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6753        handle_entire_lines: bool,
 6754        cx: &mut ViewContext<Self>,
 6755    ) {
 6756        if self.read_only(cx) {
 6757            return;
 6758        }
 6759
 6760        let clipboard_text = Cow::Borrowed(text);
 6761
 6762        self.transact(cx, |this, cx| {
 6763            if let Some(mut clipboard_selections) = clipboard_selections {
 6764                let old_selections = this.selections.all::<usize>(cx);
 6765                let all_selections_were_entire_line =
 6766                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6767                let first_selection_indent_column =
 6768                    clipboard_selections.first().map(|s| s.first_line_indent);
 6769                if clipboard_selections.len() != old_selections.len() {
 6770                    clipboard_selections.drain(..);
 6771                }
 6772
 6773                this.buffer.update(cx, |buffer, cx| {
 6774                    let snapshot = buffer.read(cx);
 6775                    let mut start_offset = 0;
 6776                    let mut edits = Vec::new();
 6777                    let mut original_indent_columns = Vec::new();
 6778                    for (ix, selection) in old_selections.iter().enumerate() {
 6779                        let to_insert;
 6780                        let entire_line;
 6781                        let original_indent_column;
 6782                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6783                            let end_offset = start_offset + clipboard_selection.len;
 6784                            to_insert = &clipboard_text[start_offset..end_offset];
 6785                            entire_line = clipboard_selection.is_entire_line;
 6786                            start_offset = end_offset + 1;
 6787                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6788                        } else {
 6789                            to_insert = clipboard_text.as_str();
 6790                            entire_line = all_selections_were_entire_line;
 6791                            original_indent_column = first_selection_indent_column
 6792                        }
 6793
 6794                        // If the corresponding selection was empty when this slice of the
 6795                        // clipboard text was written, then the entire line containing the
 6796                        // selection was copied. If this selection is also currently empty,
 6797                        // then paste the line before the current line of the buffer.
 6798                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6799                            let column = selection.start.to_point(&snapshot).column as usize;
 6800                            let line_start = selection.start - column;
 6801                            line_start..line_start
 6802                        } else {
 6803                            selection.range()
 6804                        };
 6805
 6806                        edits.push((range, to_insert));
 6807                        original_indent_columns.extend(original_indent_column);
 6808                    }
 6809                    drop(snapshot);
 6810
 6811                    buffer.edit(
 6812                        edits,
 6813                        Some(AutoindentMode::Block {
 6814                            original_indent_columns,
 6815                        }),
 6816                        cx,
 6817                    );
 6818                });
 6819
 6820                let selections = this.selections.all::<usize>(cx);
 6821                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6822            } else {
 6823                this.insert(&clipboard_text, cx);
 6824            }
 6825        });
 6826    }
 6827
 6828    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6829        if let Some(item) = cx.read_from_clipboard() {
 6830            let entries = item.entries();
 6831
 6832            match entries.first() {
 6833                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 6834                // of all the pasted entries.
 6835                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 6836                    .do_paste(
 6837                        clipboard_string.text(),
 6838                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 6839                        true,
 6840                        cx,
 6841                    ),
 6842                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 6843            }
 6844        }
 6845    }
 6846
 6847    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6848        if self.read_only(cx) {
 6849            return;
 6850        }
 6851
 6852        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6853            if let Some((selections, _)) =
 6854                self.selection_history.transaction(transaction_id).cloned()
 6855            {
 6856                self.change_selections(None, cx, |s| {
 6857                    s.select_anchors(selections.to_vec());
 6858                });
 6859            }
 6860            self.request_autoscroll(Autoscroll::fit(), cx);
 6861            self.unmark_text(cx);
 6862            self.refresh_inline_completion(true, false, cx);
 6863            cx.emit(EditorEvent::Edited { transaction_id });
 6864            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6865        }
 6866    }
 6867
 6868    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6869        if self.read_only(cx) {
 6870            return;
 6871        }
 6872
 6873        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6874            if let Some((_, Some(selections))) =
 6875                self.selection_history.transaction(transaction_id).cloned()
 6876            {
 6877                self.change_selections(None, cx, |s| {
 6878                    s.select_anchors(selections.to_vec());
 6879                });
 6880            }
 6881            self.request_autoscroll(Autoscroll::fit(), cx);
 6882            self.unmark_text(cx);
 6883            self.refresh_inline_completion(true, false, cx);
 6884            cx.emit(EditorEvent::Edited { transaction_id });
 6885        }
 6886    }
 6887
 6888    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6889        self.buffer
 6890            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6891    }
 6892
 6893    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6894        self.buffer
 6895            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6896    }
 6897
 6898    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6899        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6900            let line_mode = s.line_mode;
 6901            s.move_with(|map, selection| {
 6902                let cursor = if selection.is_empty() && !line_mode {
 6903                    movement::left(map, selection.start)
 6904                } else {
 6905                    selection.start
 6906                };
 6907                selection.collapse_to(cursor, SelectionGoal::None);
 6908            });
 6909        })
 6910    }
 6911
 6912    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6913        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6914            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6915        })
 6916    }
 6917
 6918    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6919        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6920            let line_mode = s.line_mode;
 6921            s.move_with(|map, selection| {
 6922                let cursor = if selection.is_empty() && !line_mode {
 6923                    movement::right(map, selection.end)
 6924                } else {
 6925                    selection.end
 6926                };
 6927                selection.collapse_to(cursor, SelectionGoal::None)
 6928            });
 6929        })
 6930    }
 6931
 6932    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6933        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6934            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6935        })
 6936    }
 6937
 6938    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6939        if self.take_rename(true, cx).is_some() {
 6940            return;
 6941        }
 6942
 6943        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6944            cx.propagate();
 6945            return;
 6946        }
 6947
 6948        let text_layout_details = &self.text_layout_details(cx);
 6949        let selection_count = self.selections.count();
 6950        let first_selection = self.selections.first_anchor();
 6951
 6952        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6953            let line_mode = s.line_mode;
 6954            s.move_with(|map, selection| {
 6955                if !selection.is_empty() && !line_mode {
 6956                    selection.goal = SelectionGoal::None;
 6957                }
 6958                let (cursor, goal) = movement::up(
 6959                    map,
 6960                    selection.start,
 6961                    selection.goal,
 6962                    false,
 6963                    text_layout_details,
 6964                );
 6965                selection.collapse_to(cursor, goal);
 6966            });
 6967        });
 6968
 6969        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6970        {
 6971            cx.propagate();
 6972        }
 6973    }
 6974
 6975    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6976        if self.take_rename(true, cx).is_some() {
 6977            return;
 6978        }
 6979
 6980        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6981            cx.propagate();
 6982            return;
 6983        }
 6984
 6985        let text_layout_details = &self.text_layout_details(cx);
 6986
 6987        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6988            let line_mode = s.line_mode;
 6989            s.move_with(|map, selection| {
 6990                if !selection.is_empty() && !line_mode {
 6991                    selection.goal = SelectionGoal::None;
 6992                }
 6993                let (cursor, goal) = movement::up_by_rows(
 6994                    map,
 6995                    selection.start,
 6996                    action.lines,
 6997                    selection.goal,
 6998                    false,
 6999                    text_layout_details,
 7000                );
 7001                selection.collapse_to(cursor, goal);
 7002            });
 7003        })
 7004    }
 7005
 7006    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7007        if self.take_rename(true, cx).is_some() {
 7008            return;
 7009        }
 7010
 7011        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7012            cx.propagate();
 7013            return;
 7014        }
 7015
 7016        let text_layout_details = &self.text_layout_details(cx);
 7017
 7018        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7019            let line_mode = s.line_mode;
 7020            s.move_with(|map, selection| {
 7021                if !selection.is_empty() && !line_mode {
 7022                    selection.goal = SelectionGoal::None;
 7023                }
 7024                let (cursor, goal) = movement::down_by_rows(
 7025                    map,
 7026                    selection.start,
 7027                    action.lines,
 7028                    selection.goal,
 7029                    false,
 7030                    text_layout_details,
 7031                );
 7032                selection.collapse_to(cursor, goal);
 7033            });
 7034        })
 7035    }
 7036
 7037    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7038        let text_layout_details = &self.text_layout_details(cx);
 7039        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7040            s.move_heads_with(|map, head, goal| {
 7041                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7042            })
 7043        })
 7044    }
 7045
 7046    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7047        let text_layout_details = &self.text_layout_details(cx);
 7048        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7049            s.move_heads_with(|map, head, goal| {
 7050                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7051            })
 7052        })
 7053    }
 7054
 7055    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7056        let Some(row_count) = self.visible_row_count() else {
 7057            return;
 7058        };
 7059
 7060        let text_layout_details = &self.text_layout_details(cx);
 7061
 7062        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7063            s.move_heads_with(|map, head, goal| {
 7064                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7065            })
 7066        })
 7067    }
 7068
 7069    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7070        if self.take_rename(true, cx).is_some() {
 7071            return;
 7072        }
 7073
 7074        if self
 7075            .context_menu
 7076            .write()
 7077            .as_mut()
 7078            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 7079            .unwrap_or(false)
 7080        {
 7081            return;
 7082        }
 7083
 7084        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7085            cx.propagate();
 7086            return;
 7087        }
 7088
 7089        let Some(row_count) = self.visible_row_count() else {
 7090            return;
 7091        };
 7092
 7093        let autoscroll = if action.center_cursor {
 7094            Autoscroll::center()
 7095        } else {
 7096            Autoscroll::fit()
 7097        };
 7098
 7099        let text_layout_details = &self.text_layout_details(cx);
 7100
 7101        self.change_selections(Some(autoscroll), cx, |s| {
 7102            let line_mode = s.line_mode;
 7103            s.move_with(|map, selection| {
 7104                if !selection.is_empty() && !line_mode {
 7105                    selection.goal = SelectionGoal::None;
 7106                }
 7107                let (cursor, goal) = movement::up_by_rows(
 7108                    map,
 7109                    selection.end,
 7110                    row_count,
 7111                    selection.goal,
 7112                    false,
 7113                    text_layout_details,
 7114                );
 7115                selection.collapse_to(cursor, goal);
 7116            });
 7117        });
 7118    }
 7119
 7120    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7121        let text_layout_details = &self.text_layout_details(cx);
 7122        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7123            s.move_heads_with(|map, head, goal| {
 7124                movement::up(map, head, goal, false, text_layout_details)
 7125            })
 7126        })
 7127    }
 7128
 7129    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7130        self.take_rename(true, cx);
 7131
 7132        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7133            cx.propagate();
 7134            return;
 7135        }
 7136
 7137        let text_layout_details = &self.text_layout_details(cx);
 7138        let selection_count = self.selections.count();
 7139        let first_selection = self.selections.first_anchor();
 7140
 7141        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7142            let line_mode = s.line_mode;
 7143            s.move_with(|map, selection| {
 7144                if !selection.is_empty() && !line_mode {
 7145                    selection.goal = SelectionGoal::None;
 7146                }
 7147                let (cursor, goal) = movement::down(
 7148                    map,
 7149                    selection.end,
 7150                    selection.goal,
 7151                    false,
 7152                    text_layout_details,
 7153                );
 7154                selection.collapse_to(cursor, goal);
 7155            });
 7156        });
 7157
 7158        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7159        {
 7160            cx.propagate();
 7161        }
 7162    }
 7163
 7164    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7165        let Some(row_count) = self.visible_row_count() else {
 7166            return;
 7167        };
 7168
 7169        let text_layout_details = &self.text_layout_details(cx);
 7170
 7171        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7172            s.move_heads_with(|map, head, goal| {
 7173                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7174            })
 7175        })
 7176    }
 7177
 7178    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7179        if self.take_rename(true, cx).is_some() {
 7180            return;
 7181        }
 7182
 7183        if self
 7184            .context_menu
 7185            .write()
 7186            .as_mut()
 7187            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 7188            .unwrap_or(false)
 7189        {
 7190            return;
 7191        }
 7192
 7193        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7194            cx.propagate();
 7195            return;
 7196        }
 7197
 7198        let Some(row_count) = self.visible_row_count() else {
 7199            return;
 7200        };
 7201
 7202        let autoscroll = if action.center_cursor {
 7203            Autoscroll::center()
 7204        } else {
 7205            Autoscroll::fit()
 7206        };
 7207
 7208        let text_layout_details = &self.text_layout_details(cx);
 7209        self.change_selections(Some(autoscroll), cx, |s| {
 7210            let line_mode = s.line_mode;
 7211            s.move_with(|map, selection| {
 7212                if !selection.is_empty() && !line_mode {
 7213                    selection.goal = SelectionGoal::None;
 7214                }
 7215                let (cursor, goal) = movement::down_by_rows(
 7216                    map,
 7217                    selection.end,
 7218                    row_count,
 7219                    selection.goal,
 7220                    false,
 7221                    text_layout_details,
 7222                );
 7223                selection.collapse_to(cursor, goal);
 7224            });
 7225        });
 7226    }
 7227
 7228    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7229        let text_layout_details = &self.text_layout_details(cx);
 7230        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7231            s.move_heads_with(|map, head, goal| {
 7232                movement::down(map, head, goal, false, text_layout_details)
 7233            })
 7234        });
 7235    }
 7236
 7237    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7238        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7239            context_menu.select_first(self.project.as_ref(), cx);
 7240        }
 7241    }
 7242
 7243    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7244        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7245            context_menu.select_prev(self.project.as_ref(), cx);
 7246        }
 7247    }
 7248
 7249    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7250        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7251            context_menu.select_next(self.project.as_ref(), cx);
 7252        }
 7253    }
 7254
 7255    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7256        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7257            context_menu.select_last(self.project.as_ref(), cx);
 7258        }
 7259    }
 7260
 7261    pub fn move_to_previous_word_start(
 7262        &mut self,
 7263        _: &MoveToPreviousWordStart,
 7264        cx: &mut ViewContext<Self>,
 7265    ) {
 7266        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7267            s.move_cursors_with(|map, head, _| {
 7268                (
 7269                    movement::previous_word_start(map, head),
 7270                    SelectionGoal::None,
 7271                )
 7272            });
 7273        })
 7274    }
 7275
 7276    pub fn move_to_previous_subword_start(
 7277        &mut self,
 7278        _: &MoveToPreviousSubwordStart,
 7279        cx: &mut ViewContext<Self>,
 7280    ) {
 7281        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7282            s.move_cursors_with(|map, head, _| {
 7283                (
 7284                    movement::previous_subword_start(map, head),
 7285                    SelectionGoal::None,
 7286                )
 7287            });
 7288        })
 7289    }
 7290
 7291    pub fn select_to_previous_word_start(
 7292        &mut self,
 7293        _: &SelectToPreviousWordStart,
 7294        cx: &mut ViewContext<Self>,
 7295    ) {
 7296        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7297            s.move_heads_with(|map, head, _| {
 7298                (
 7299                    movement::previous_word_start(map, head),
 7300                    SelectionGoal::None,
 7301                )
 7302            });
 7303        })
 7304    }
 7305
 7306    pub fn select_to_previous_subword_start(
 7307        &mut self,
 7308        _: &SelectToPreviousSubwordStart,
 7309        cx: &mut ViewContext<Self>,
 7310    ) {
 7311        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7312            s.move_heads_with(|map, head, _| {
 7313                (
 7314                    movement::previous_subword_start(map, head),
 7315                    SelectionGoal::None,
 7316                )
 7317            });
 7318        })
 7319    }
 7320
 7321    pub fn delete_to_previous_word_start(
 7322        &mut self,
 7323        action: &DeleteToPreviousWordStart,
 7324        cx: &mut ViewContext<Self>,
 7325    ) {
 7326        self.transact(cx, |this, cx| {
 7327            this.select_autoclose_pair(cx);
 7328            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7329                let line_mode = s.line_mode;
 7330                s.move_with(|map, selection| {
 7331                    if selection.is_empty() && !line_mode {
 7332                        let cursor = if action.ignore_newlines {
 7333                            movement::previous_word_start(map, selection.head())
 7334                        } else {
 7335                            movement::previous_word_start_or_newline(map, selection.head())
 7336                        };
 7337                        selection.set_head(cursor, SelectionGoal::None);
 7338                    }
 7339                });
 7340            });
 7341            this.insert("", cx);
 7342        });
 7343    }
 7344
 7345    pub fn delete_to_previous_subword_start(
 7346        &mut self,
 7347        _: &DeleteToPreviousSubwordStart,
 7348        cx: &mut ViewContext<Self>,
 7349    ) {
 7350        self.transact(cx, |this, cx| {
 7351            this.select_autoclose_pair(cx);
 7352            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7353                let line_mode = s.line_mode;
 7354                s.move_with(|map, selection| {
 7355                    if selection.is_empty() && !line_mode {
 7356                        let cursor = movement::previous_subword_start(map, selection.head());
 7357                        selection.set_head(cursor, SelectionGoal::None);
 7358                    }
 7359                });
 7360            });
 7361            this.insert("", cx);
 7362        });
 7363    }
 7364
 7365    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7366        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7367            s.move_cursors_with(|map, head, _| {
 7368                (movement::next_word_end(map, head), SelectionGoal::None)
 7369            });
 7370        })
 7371    }
 7372
 7373    pub fn move_to_next_subword_end(
 7374        &mut self,
 7375        _: &MoveToNextSubwordEnd,
 7376        cx: &mut ViewContext<Self>,
 7377    ) {
 7378        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7379            s.move_cursors_with(|map, head, _| {
 7380                (movement::next_subword_end(map, head), SelectionGoal::None)
 7381            });
 7382        })
 7383    }
 7384
 7385    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7386        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7387            s.move_heads_with(|map, head, _| {
 7388                (movement::next_word_end(map, head), SelectionGoal::None)
 7389            });
 7390        })
 7391    }
 7392
 7393    pub fn select_to_next_subword_end(
 7394        &mut self,
 7395        _: &SelectToNextSubwordEnd,
 7396        cx: &mut ViewContext<Self>,
 7397    ) {
 7398        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7399            s.move_heads_with(|map, head, _| {
 7400                (movement::next_subword_end(map, head), SelectionGoal::None)
 7401            });
 7402        })
 7403    }
 7404
 7405    pub fn delete_to_next_word_end(
 7406        &mut self,
 7407        action: &DeleteToNextWordEnd,
 7408        cx: &mut ViewContext<Self>,
 7409    ) {
 7410        self.transact(cx, |this, cx| {
 7411            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7412                let line_mode = s.line_mode;
 7413                s.move_with(|map, selection| {
 7414                    if selection.is_empty() && !line_mode {
 7415                        let cursor = if action.ignore_newlines {
 7416                            movement::next_word_end(map, selection.head())
 7417                        } else {
 7418                            movement::next_word_end_or_newline(map, selection.head())
 7419                        };
 7420                        selection.set_head(cursor, SelectionGoal::None);
 7421                    }
 7422                });
 7423            });
 7424            this.insert("", cx);
 7425        });
 7426    }
 7427
 7428    pub fn delete_to_next_subword_end(
 7429        &mut self,
 7430        _: &DeleteToNextSubwordEnd,
 7431        cx: &mut ViewContext<Self>,
 7432    ) {
 7433        self.transact(cx, |this, cx| {
 7434            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7435                s.move_with(|map, selection| {
 7436                    if selection.is_empty() {
 7437                        let cursor = movement::next_subword_end(map, selection.head());
 7438                        selection.set_head(cursor, SelectionGoal::None);
 7439                    }
 7440                });
 7441            });
 7442            this.insert("", cx);
 7443        });
 7444    }
 7445
 7446    pub fn move_to_beginning_of_line(
 7447        &mut self,
 7448        action: &MoveToBeginningOfLine,
 7449        cx: &mut ViewContext<Self>,
 7450    ) {
 7451        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7452            s.move_cursors_with(|map, head, _| {
 7453                (
 7454                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7455                    SelectionGoal::None,
 7456                )
 7457            });
 7458        })
 7459    }
 7460
 7461    pub fn select_to_beginning_of_line(
 7462        &mut self,
 7463        action: &SelectToBeginningOfLine,
 7464        cx: &mut ViewContext<Self>,
 7465    ) {
 7466        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7467            s.move_heads_with(|map, head, _| {
 7468                (
 7469                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7470                    SelectionGoal::None,
 7471                )
 7472            });
 7473        });
 7474    }
 7475
 7476    pub fn delete_to_beginning_of_line(
 7477        &mut self,
 7478        _: &DeleteToBeginningOfLine,
 7479        cx: &mut ViewContext<Self>,
 7480    ) {
 7481        self.transact(cx, |this, cx| {
 7482            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7483                s.move_with(|_, selection| {
 7484                    selection.reversed = true;
 7485                });
 7486            });
 7487
 7488            this.select_to_beginning_of_line(
 7489                &SelectToBeginningOfLine {
 7490                    stop_at_soft_wraps: false,
 7491                },
 7492                cx,
 7493            );
 7494            this.backspace(&Backspace, cx);
 7495        });
 7496    }
 7497
 7498    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7499        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7500            s.move_cursors_with(|map, head, _| {
 7501                (
 7502                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7503                    SelectionGoal::None,
 7504                )
 7505            });
 7506        })
 7507    }
 7508
 7509    pub fn select_to_end_of_line(
 7510        &mut self,
 7511        action: &SelectToEndOfLine,
 7512        cx: &mut ViewContext<Self>,
 7513    ) {
 7514        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7515            s.move_heads_with(|map, head, _| {
 7516                (
 7517                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7518                    SelectionGoal::None,
 7519                )
 7520            });
 7521        })
 7522    }
 7523
 7524    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7525        self.transact(cx, |this, cx| {
 7526            this.select_to_end_of_line(
 7527                &SelectToEndOfLine {
 7528                    stop_at_soft_wraps: false,
 7529                },
 7530                cx,
 7531            );
 7532            this.delete(&Delete, cx);
 7533        });
 7534    }
 7535
 7536    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7537        self.transact(cx, |this, cx| {
 7538            this.select_to_end_of_line(
 7539                &SelectToEndOfLine {
 7540                    stop_at_soft_wraps: false,
 7541                },
 7542                cx,
 7543            );
 7544            this.cut(&Cut, cx);
 7545        });
 7546    }
 7547
 7548    pub fn move_to_start_of_paragraph(
 7549        &mut self,
 7550        _: &MoveToStartOfParagraph,
 7551        cx: &mut ViewContext<Self>,
 7552    ) {
 7553        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7554            cx.propagate();
 7555            return;
 7556        }
 7557
 7558        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7559            s.move_with(|map, selection| {
 7560                selection.collapse_to(
 7561                    movement::start_of_paragraph(map, selection.head(), 1),
 7562                    SelectionGoal::None,
 7563                )
 7564            });
 7565        })
 7566    }
 7567
 7568    pub fn move_to_end_of_paragraph(
 7569        &mut self,
 7570        _: &MoveToEndOfParagraph,
 7571        cx: &mut ViewContext<Self>,
 7572    ) {
 7573        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7574            cx.propagate();
 7575            return;
 7576        }
 7577
 7578        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7579            s.move_with(|map, selection| {
 7580                selection.collapse_to(
 7581                    movement::end_of_paragraph(map, selection.head(), 1),
 7582                    SelectionGoal::None,
 7583                )
 7584            });
 7585        })
 7586    }
 7587
 7588    pub fn select_to_start_of_paragraph(
 7589        &mut self,
 7590        _: &SelectToStartOfParagraph,
 7591        cx: &mut ViewContext<Self>,
 7592    ) {
 7593        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7594            cx.propagate();
 7595            return;
 7596        }
 7597
 7598        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7599            s.move_heads_with(|map, head, _| {
 7600                (
 7601                    movement::start_of_paragraph(map, head, 1),
 7602                    SelectionGoal::None,
 7603                )
 7604            });
 7605        })
 7606    }
 7607
 7608    pub fn select_to_end_of_paragraph(
 7609        &mut self,
 7610        _: &SelectToEndOfParagraph,
 7611        cx: &mut ViewContext<Self>,
 7612    ) {
 7613        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7614            cx.propagate();
 7615            return;
 7616        }
 7617
 7618        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7619            s.move_heads_with(|map, head, _| {
 7620                (
 7621                    movement::end_of_paragraph(map, head, 1),
 7622                    SelectionGoal::None,
 7623                )
 7624            });
 7625        })
 7626    }
 7627
 7628    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7629        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7630            cx.propagate();
 7631            return;
 7632        }
 7633
 7634        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7635            s.select_ranges(vec![0..0]);
 7636        });
 7637    }
 7638
 7639    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7640        let mut selection = self.selections.last::<Point>(cx);
 7641        selection.set_head(Point::zero(), SelectionGoal::None);
 7642
 7643        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7644            s.select(vec![selection]);
 7645        });
 7646    }
 7647
 7648    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7649        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7650            cx.propagate();
 7651            return;
 7652        }
 7653
 7654        let cursor = self.buffer.read(cx).read(cx).len();
 7655        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7656            s.select_ranges(vec![cursor..cursor])
 7657        });
 7658    }
 7659
 7660    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7661        self.nav_history = nav_history;
 7662    }
 7663
 7664    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7665        self.nav_history.as_ref()
 7666    }
 7667
 7668    fn push_to_nav_history(
 7669        &mut self,
 7670        cursor_anchor: Anchor,
 7671        new_position: Option<Point>,
 7672        cx: &mut ViewContext<Self>,
 7673    ) {
 7674        if let Some(nav_history) = self.nav_history.as_mut() {
 7675            let buffer = self.buffer.read(cx).read(cx);
 7676            let cursor_position = cursor_anchor.to_point(&buffer);
 7677            let scroll_state = self.scroll_manager.anchor();
 7678            let scroll_top_row = scroll_state.top_row(&buffer);
 7679            drop(buffer);
 7680
 7681            if let Some(new_position) = new_position {
 7682                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7683                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7684                    return;
 7685                }
 7686            }
 7687
 7688            nav_history.push(
 7689                Some(NavigationData {
 7690                    cursor_anchor,
 7691                    cursor_position,
 7692                    scroll_anchor: scroll_state,
 7693                    scroll_top_row,
 7694                }),
 7695                cx,
 7696            );
 7697        }
 7698    }
 7699
 7700    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7701        let buffer = self.buffer.read(cx).snapshot(cx);
 7702        let mut selection = self.selections.first::<usize>(cx);
 7703        selection.set_head(buffer.len(), SelectionGoal::None);
 7704        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7705            s.select(vec![selection]);
 7706        });
 7707    }
 7708
 7709    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7710        let end = self.buffer.read(cx).read(cx).len();
 7711        self.change_selections(None, cx, |s| {
 7712            s.select_ranges(vec![0..end]);
 7713        });
 7714    }
 7715
 7716    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7717        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7718        let mut selections = self.selections.all::<Point>(cx);
 7719        let max_point = display_map.buffer_snapshot.max_point();
 7720        for selection in &mut selections {
 7721            let rows = selection.spanned_rows(true, &display_map);
 7722            selection.start = Point::new(rows.start.0, 0);
 7723            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7724            selection.reversed = false;
 7725        }
 7726        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7727            s.select(selections);
 7728        });
 7729    }
 7730
 7731    pub fn split_selection_into_lines(
 7732        &mut self,
 7733        _: &SplitSelectionIntoLines,
 7734        cx: &mut ViewContext<Self>,
 7735    ) {
 7736        let mut to_unfold = Vec::new();
 7737        let mut new_selection_ranges = Vec::new();
 7738        {
 7739            let selections = self.selections.all::<Point>(cx);
 7740            let buffer = self.buffer.read(cx).read(cx);
 7741            for selection in selections {
 7742                for row in selection.start.row..selection.end.row {
 7743                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7744                    new_selection_ranges.push(cursor..cursor);
 7745                }
 7746                new_selection_ranges.push(selection.end..selection.end);
 7747                to_unfold.push(selection.start..selection.end);
 7748            }
 7749        }
 7750        self.unfold_ranges(to_unfold, true, true, cx);
 7751        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7752            s.select_ranges(new_selection_ranges);
 7753        });
 7754    }
 7755
 7756    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7757        self.add_selection(true, cx);
 7758    }
 7759
 7760    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7761        self.add_selection(false, cx);
 7762    }
 7763
 7764    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7765        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7766        let mut selections = self.selections.all::<Point>(cx);
 7767        let text_layout_details = self.text_layout_details(cx);
 7768        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7769            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7770            let range = oldest_selection.display_range(&display_map).sorted();
 7771
 7772            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7773            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7774            let positions = start_x.min(end_x)..start_x.max(end_x);
 7775
 7776            selections.clear();
 7777            let mut stack = Vec::new();
 7778            for row in range.start.row().0..=range.end.row().0 {
 7779                if let Some(selection) = self.selections.build_columnar_selection(
 7780                    &display_map,
 7781                    DisplayRow(row),
 7782                    &positions,
 7783                    oldest_selection.reversed,
 7784                    &text_layout_details,
 7785                ) {
 7786                    stack.push(selection.id);
 7787                    selections.push(selection);
 7788                }
 7789            }
 7790
 7791            if above {
 7792                stack.reverse();
 7793            }
 7794
 7795            AddSelectionsState { above, stack }
 7796        });
 7797
 7798        let last_added_selection = *state.stack.last().unwrap();
 7799        let mut new_selections = Vec::new();
 7800        if above == state.above {
 7801            let end_row = if above {
 7802                DisplayRow(0)
 7803            } else {
 7804                display_map.max_point().row()
 7805            };
 7806
 7807            'outer: for selection in selections {
 7808                if selection.id == last_added_selection {
 7809                    let range = selection.display_range(&display_map).sorted();
 7810                    debug_assert_eq!(range.start.row(), range.end.row());
 7811                    let mut row = range.start.row();
 7812                    let positions =
 7813                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7814                            px(start)..px(end)
 7815                        } else {
 7816                            let start_x =
 7817                                display_map.x_for_display_point(range.start, &text_layout_details);
 7818                            let end_x =
 7819                                display_map.x_for_display_point(range.end, &text_layout_details);
 7820                            start_x.min(end_x)..start_x.max(end_x)
 7821                        };
 7822
 7823                    while row != end_row {
 7824                        if above {
 7825                            row.0 -= 1;
 7826                        } else {
 7827                            row.0 += 1;
 7828                        }
 7829
 7830                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7831                            &display_map,
 7832                            row,
 7833                            &positions,
 7834                            selection.reversed,
 7835                            &text_layout_details,
 7836                        ) {
 7837                            state.stack.push(new_selection.id);
 7838                            if above {
 7839                                new_selections.push(new_selection);
 7840                                new_selections.push(selection);
 7841                            } else {
 7842                                new_selections.push(selection);
 7843                                new_selections.push(new_selection);
 7844                            }
 7845
 7846                            continue 'outer;
 7847                        }
 7848                    }
 7849                }
 7850
 7851                new_selections.push(selection);
 7852            }
 7853        } else {
 7854            new_selections = selections;
 7855            new_selections.retain(|s| s.id != last_added_selection);
 7856            state.stack.pop();
 7857        }
 7858
 7859        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7860            s.select(new_selections);
 7861        });
 7862        if state.stack.len() > 1 {
 7863            self.add_selections_state = Some(state);
 7864        }
 7865    }
 7866
 7867    pub fn select_next_match_internal(
 7868        &mut self,
 7869        display_map: &DisplaySnapshot,
 7870        replace_newest: bool,
 7871        autoscroll: Option<Autoscroll>,
 7872        cx: &mut ViewContext<Self>,
 7873    ) -> Result<()> {
 7874        fn select_next_match_ranges(
 7875            this: &mut Editor,
 7876            range: Range<usize>,
 7877            replace_newest: bool,
 7878            auto_scroll: Option<Autoscroll>,
 7879            cx: &mut ViewContext<Editor>,
 7880        ) {
 7881            this.unfold_ranges([range.clone()], false, true, cx);
 7882            this.change_selections(auto_scroll, cx, |s| {
 7883                if replace_newest {
 7884                    s.delete(s.newest_anchor().id);
 7885                }
 7886                s.insert_range(range.clone());
 7887            });
 7888        }
 7889
 7890        let buffer = &display_map.buffer_snapshot;
 7891        let mut selections = self.selections.all::<usize>(cx);
 7892        if let Some(mut select_next_state) = self.select_next_state.take() {
 7893            let query = &select_next_state.query;
 7894            if !select_next_state.done {
 7895                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7896                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7897                let mut next_selected_range = None;
 7898
 7899                let bytes_after_last_selection =
 7900                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7901                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7902                let query_matches = query
 7903                    .stream_find_iter(bytes_after_last_selection)
 7904                    .map(|result| (last_selection.end, result))
 7905                    .chain(
 7906                        query
 7907                            .stream_find_iter(bytes_before_first_selection)
 7908                            .map(|result| (0, result)),
 7909                    );
 7910
 7911                for (start_offset, query_match) in query_matches {
 7912                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7913                    let offset_range =
 7914                        start_offset + query_match.start()..start_offset + query_match.end();
 7915                    let display_range = offset_range.start.to_display_point(display_map)
 7916                        ..offset_range.end.to_display_point(display_map);
 7917
 7918                    if !select_next_state.wordwise
 7919                        || (!movement::is_inside_word(display_map, display_range.start)
 7920                            && !movement::is_inside_word(display_map, display_range.end))
 7921                    {
 7922                        // TODO: This is n^2, because we might check all the selections
 7923                        if !selections
 7924                            .iter()
 7925                            .any(|selection| selection.range().overlaps(&offset_range))
 7926                        {
 7927                            next_selected_range = Some(offset_range);
 7928                            break;
 7929                        }
 7930                    }
 7931                }
 7932
 7933                if let Some(next_selected_range) = next_selected_range {
 7934                    select_next_match_ranges(
 7935                        self,
 7936                        next_selected_range,
 7937                        replace_newest,
 7938                        autoscroll,
 7939                        cx,
 7940                    );
 7941                } else {
 7942                    select_next_state.done = true;
 7943                }
 7944            }
 7945
 7946            self.select_next_state = Some(select_next_state);
 7947        } else {
 7948            let mut only_carets = true;
 7949            let mut same_text_selected = true;
 7950            let mut selected_text = None;
 7951
 7952            let mut selections_iter = selections.iter().peekable();
 7953            while let Some(selection) = selections_iter.next() {
 7954                if selection.start != selection.end {
 7955                    only_carets = false;
 7956                }
 7957
 7958                if same_text_selected {
 7959                    if selected_text.is_none() {
 7960                        selected_text =
 7961                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7962                    }
 7963
 7964                    if let Some(next_selection) = selections_iter.peek() {
 7965                        if next_selection.range().len() == selection.range().len() {
 7966                            let next_selected_text = buffer
 7967                                .text_for_range(next_selection.range())
 7968                                .collect::<String>();
 7969                            if Some(next_selected_text) != selected_text {
 7970                                same_text_selected = false;
 7971                                selected_text = None;
 7972                            }
 7973                        } else {
 7974                            same_text_selected = false;
 7975                            selected_text = None;
 7976                        }
 7977                    }
 7978                }
 7979            }
 7980
 7981            if only_carets {
 7982                for selection in &mut selections {
 7983                    let word_range = movement::surrounding_word(
 7984                        display_map,
 7985                        selection.start.to_display_point(display_map),
 7986                    );
 7987                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 7988                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 7989                    selection.goal = SelectionGoal::None;
 7990                    selection.reversed = false;
 7991                    select_next_match_ranges(
 7992                        self,
 7993                        selection.start..selection.end,
 7994                        replace_newest,
 7995                        autoscroll,
 7996                        cx,
 7997                    );
 7998                }
 7999
 8000                if selections.len() == 1 {
 8001                    let selection = selections
 8002                        .last()
 8003                        .expect("ensured that there's only one selection");
 8004                    let query = buffer
 8005                        .text_for_range(selection.start..selection.end)
 8006                        .collect::<String>();
 8007                    let is_empty = query.is_empty();
 8008                    let select_state = SelectNextState {
 8009                        query: AhoCorasick::new(&[query])?,
 8010                        wordwise: true,
 8011                        done: is_empty,
 8012                    };
 8013                    self.select_next_state = Some(select_state);
 8014                } else {
 8015                    self.select_next_state = None;
 8016                }
 8017            } else if let Some(selected_text) = selected_text {
 8018                self.select_next_state = Some(SelectNextState {
 8019                    query: AhoCorasick::new(&[selected_text])?,
 8020                    wordwise: false,
 8021                    done: false,
 8022                });
 8023                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8024            }
 8025        }
 8026        Ok(())
 8027    }
 8028
 8029    pub fn select_all_matches(
 8030        &mut self,
 8031        _action: &SelectAllMatches,
 8032        cx: &mut ViewContext<Self>,
 8033    ) -> Result<()> {
 8034        self.push_to_selection_history();
 8035        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8036
 8037        self.select_next_match_internal(&display_map, false, None, cx)?;
 8038        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8039            return Ok(());
 8040        };
 8041        if select_next_state.done {
 8042            return Ok(());
 8043        }
 8044
 8045        let mut new_selections = self.selections.all::<usize>(cx);
 8046
 8047        let buffer = &display_map.buffer_snapshot;
 8048        let query_matches = select_next_state
 8049            .query
 8050            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8051
 8052        for query_match in query_matches {
 8053            let query_match = query_match.unwrap(); // can only fail due to I/O
 8054            let offset_range = query_match.start()..query_match.end();
 8055            let display_range = offset_range.start.to_display_point(&display_map)
 8056                ..offset_range.end.to_display_point(&display_map);
 8057
 8058            if !select_next_state.wordwise
 8059                || (!movement::is_inside_word(&display_map, display_range.start)
 8060                    && !movement::is_inside_word(&display_map, display_range.end))
 8061            {
 8062                self.selections.change_with(cx, |selections| {
 8063                    new_selections.push(Selection {
 8064                        id: selections.new_selection_id(),
 8065                        start: offset_range.start,
 8066                        end: offset_range.end,
 8067                        reversed: false,
 8068                        goal: SelectionGoal::None,
 8069                    });
 8070                });
 8071            }
 8072        }
 8073
 8074        new_selections.sort_by_key(|selection| selection.start);
 8075        let mut ix = 0;
 8076        while ix + 1 < new_selections.len() {
 8077            let current_selection = &new_selections[ix];
 8078            let next_selection = &new_selections[ix + 1];
 8079            if current_selection.range().overlaps(&next_selection.range()) {
 8080                if current_selection.id < next_selection.id {
 8081                    new_selections.remove(ix + 1);
 8082                } else {
 8083                    new_selections.remove(ix);
 8084                }
 8085            } else {
 8086                ix += 1;
 8087            }
 8088        }
 8089
 8090        select_next_state.done = true;
 8091        self.unfold_ranges(
 8092            new_selections.iter().map(|selection| selection.range()),
 8093            false,
 8094            false,
 8095            cx,
 8096        );
 8097        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8098            selections.select(new_selections)
 8099        });
 8100
 8101        Ok(())
 8102    }
 8103
 8104    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8105        self.push_to_selection_history();
 8106        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8107        self.select_next_match_internal(
 8108            &display_map,
 8109            action.replace_newest,
 8110            Some(Autoscroll::newest()),
 8111            cx,
 8112        )?;
 8113        Ok(())
 8114    }
 8115
 8116    pub fn select_previous(
 8117        &mut self,
 8118        action: &SelectPrevious,
 8119        cx: &mut ViewContext<Self>,
 8120    ) -> Result<()> {
 8121        self.push_to_selection_history();
 8122        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8123        let buffer = &display_map.buffer_snapshot;
 8124        let mut selections = self.selections.all::<usize>(cx);
 8125        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8126            let query = &select_prev_state.query;
 8127            if !select_prev_state.done {
 8128                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8129                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8130                let mut next_selected_range = None;
 8131                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8132                let bytes_before_last_selection =
 8133                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8134                let bytes_after_first_selection =
 8135                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8136                let query_matches = query
 8137                    .stream_find_iter(bytes_before_last_selection)
 8138                    .map(|result| (last_selection.start, result))
 8139                    .chain(
 8140                        query
 8141                            .stream_find_iter(bytes_after_first_selection)
 8142                            .map(|result| (buffer.len(), result)),
 8143                    );
 8144                for (end_offset, query_match) in query_matches {
 8145                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8146                    let offset_range =
 8147                        end_offset - query_match.end()..end_offset - query_match.start();
 8148                    let display_range = offset_range.start.to_display_point(&display_map)
 8149                        ..offset_range.end.to_display_point(&display_map);
 8150
 8151                    if !select_prev_state.wordwise
 8152                        || (!movement::is_inside_word(&display_map, display_range.start)
 8153                            && !movement::is_inside_word(&display_map, display_range.end))
 8154                    {
 8155                        next_selected_range = Some(offset_range);
 8156                        break;
 8157                    }
 8158                }
 8159
 8160                if let Some(next_selected_range) = next_selected_range {
 8161                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8162                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8163                        if action.replace_newest {
 8164                            s.delete(s.newest_anchor().id);
 8165                        }
 8166                        s.insert_range(next_selected_range);
 8167                    });
 8168                } else {
 8169                    select_prev_state.done = true;
 8170                }
 8171            }
 8172
 8173            self.select_prev_state = Some(select_prev_state);
 8174        } else {
 8175            let mut only_carets = true;
 8176            let mut same_text_selected = true;
 8177            let mut selected_text = None;
 8178
 8179            let mut selections_iter = selections.iter().peekable();
 8180            while let Some(selection) = selections_iter.next() {
 8181                if selection.start != selection.end {
 8182                    only_carets = false;
 8183                }
 8184
 8185                if same_text_selected {
 8186                    if selected_text.is_none() {
 8187                        selected_text =
 8188                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8189                    }
 8190
 8191                    if let Some(next_selection) = selections_iter.peek() {
 8192                        if next_selection.range().len() == selection.range().len() {
 8193                            let next_selected_text = buffer
 8194                                .text_for_range(next_selection.range())
 8195                                .collect::<String>();
 8196                            if Some(next_selected_text) != selected_text {
 8197                                same_text_selected = false;
 8198                                selected_text = None;
 8199                            }
 8200                        } else {
 8201                            same_text_selected = false;
 8202                            selected_text = None;
 8203                        }
 8204                    }
 8205                }
 8206            }
 8207
 8208            if only_carets {
 8209                for selection in &mut selections {
 8210                    let word_range = movement::surrounding_word(
 8211                        &display_map,
 8212                        selection.start.to_display_point(&display_map),
 8213                    );
 8214                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8215                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8216                    selection.goal = SelectionGoal::None;
 8217                    selection.reversed = false;
 8218                }
 8219                if selections.len() == 1 {
 8220                    let selection = selections
 8221                        .last()
 8222                        .expect("ensured that there's only one selection");
 8223                    let query = buffer
 8224                        .text_for_range(selection.start..selection.end)
 8225                        .collect::<String>();
 8226                    let is_empty = query.is_empty();
 8227                    let select_state = SelectNextState {
 8228                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8229                        wordwise: true,
 8230                        done: is_empty,
 8231                    };
 8232                    self.select_prev_state = Some(select_state);
 8233                } else {
 8234                    self.select_prev_state = None;
 8235                }
 8236
 8237                self.unfold_ranges(
 8238                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8239                    false,
 8240                    true,
 8241                    cx,
 8242                );
 8243                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8244                    s.select(selections);
 8245                });
 8246            } else if let Some(selected_text) = selected_text {
 8247                self.select_prev_state = Some(SelectNextState {
 8248                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8249                    wordwise: false,
 8250                    done: false,
 8251                });
 8252                self.select_previous(action, cx)?;
 8253            }
 8254        }
 8255        Ok(())
 8256    }
 8257
 8258    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8259        let text_layout_details = &self.text_layout_details(cx);
 8260        self.transact(cx, |this, cx| {
 8261            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8262            let mut edits = Vec::new();
 8263            let mut selection_edit_ranges = Vec::new();
 8264            let mut last_toggled_row = None;
 8265            let snapshot = this.buffer.read(cx).read(cx);
 8266            let empty_str: Arc<str> = Arc::default();
 8267            let mut suffixes_inserted = Vec::new();
 8268
 8269            fn comment_prefix_range(
 8270                snapshot: &MultiBufferSnapshot,
 8271                row: MultiBufferRow,
 8272                comment_prefix: &str,
 8273                comment_prefix_whitespace: &str,
 8274            ) -> Range<Point> {
 8275                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8276
 8277                let mut line_bytes = snapshot
 8278                    .bytes_in_range(start..snapshot.max_point())
 8279                    .flatten()
 8280                    .copied();
 8281
 8282                // If this line currently begins with the line comment prefix, then record
 8283                // the range containing the prefix.
 8284                if line_bytes
 8285                    .by_ref()
 8286                    .take(comment_prefix.len())
 8287                    .eq(comment_prefix.bytes())
 8288                {
 8289                    // Include any whitespace that matches the comment prefix.
 8290                    let matching_whitespace_len = line_bytes
 8291                        .zip(comment_prefix_whitespace.bytes())
 8292                        .take_while(|(a, b)| a == b)
 8293                        .count() as u32;
 8294                    let end = Point::new(
 8295                        start.row,
 8296                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8297                    );
 8298                    start..end
 8299                } else {
 8300                    start..start
 8301                }
 8302            }
 8303
 8304            fn comment_suffix_range(
 8305                snapshot: &MultiBufferSnapshot,
 8306                row: MultiBufferRow,
 8307                comment_suffix: &str,
 8308                comment_suffix_has_leading_space: bool,
 8309            ) -> Range<Point> {
 8310                let end = Point::new(row.0, snapshot.line_len(row));
 8311                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8312
 8313                let mut line_end_bytes = snapshot
 8314                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8315                    .flatten()
 8316                    .copied();
 8317
 8318                let leading_space_len = if suffix_start_column > 0
 8319                    && line_end_bytes.next() == Some(b' ')
 8320                    && comment_suffix_has_leading_space
 8321                {
 8322                    1
 8323                } else {
 8324                    0
 8325                };
 8326
 8327                // If this line currently begins with the line comment prefix, then record
 8328                // the range containing the prefix.
 8329                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8330                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8331                    start..end
 8332                } else {
 8333                    end..end
 8334                }
 8335            }
 8336
 8337            // TODO: Handle selections that cross excerpts
 8338            for selection in &mut selections {
 8339                let start_column = snapshot
 8340                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8341                    .len;
 8342                let language = if let Some(language) =
 8343                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8344                {
 8345                    language
 8346                } else {
 8347                    continue;
 8348                };
 8349
 8350                selection_edit_ranges.clear();
 8351
 8352                // If multiple selections contain a given row, avoid processing that
 8353                // row more than once.
 8354                let mut start_row = MultiBufferRow(selection.start.row);
 8355                if last_toggled_row == Some(start_row) {
 8356                    start_row = start_row.next_row();
 8357                }
 8358                let end_row =
 8359                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8360                        MultiBufferRow(selection.end.row - 1)
 8361                    } else {
 8362                        MultiBufferRow(selection.end.row)
 8363                    };
 8364                last_toggled_row = Some(end_row);
 8365
 8366                if start_row > end_row {
 8367                    continue;
 8368                }
 8369
 8370                // If the language has line comments, toggle those.
 8371                let full_comment_prefixes = language.line_comment_prefixes();
 8372                if !full_comment_prefixes.is_empty() {
 8373                    let first_prefix = full_comment_prefixes
 8374                        .first()
 8375                        .expect("prefixes is non-empty");
 8376                    let prefix_trimmed_lengths = full_comment_prefixes
 8377                        .iter()
 8378                        .map(|p| p.trim_end_matches(' ').len())
 8379                        .collect::<SmallVec<[usize; 4]>>();
 8380
 8381                    let mut all_selection_lines_are_comments = true;
 8382
 8383                    for row in start_row.0..=end_row.0 {
 8384                        let row = MultiBufferRow(row);
 8385                        if start_row < end_row && snapshot.is_line_blank(row) {
 8386                            continue;
 8387                        }
 8388
 8389                        let prefix_range = full_comment_prefixes
 8390                            .iter()
 8391                            .zip(prefix_trimmed_lengths.iter().copied())
 8392                            .map(|(prefix, trimmed_prefix_len)| {
 8393                                comment_prefix_range(
 8394                                    snapshot.deref(),
 8395                                    row,
 8396                                    &prefix[..trimmed_prefix_len],
 8397                                    &prefix[trimmed_prefix_len..],
 8398                                )
 8399                            })
 8400                            .max_by_key(|range| range.end.column - range.start.column)
 8401                            .expect("prefixes is non-empty");
 8402
 8403                        if prefix_range.is_empty() {
 8404                            all_selection_lines_are_comments = false;
 8405                        }
 8406
 8407                        selection_edit_ranges.push(prefix_range);
 8408                    }
 8409
 8410                    if all_selection_lines_are_comments {
 8411                        edits.extend(
 8412                            selection_edit_ranges
 8413                                .iter()
 8414                                .cloned()
 8415                                .map(|range| (range, empty_str.clone())),
 8416                        );
 8417                    } else {
 8418                        let min_column = selection_edit_ranges
 8419                            .iter()
 8420                            .map(|range| range.start.column)
 8421                            .min()
 8422                            .unwrap_or(0);
 8423                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8424                            let position = Point::new(range.start.row, min_column);
 8425                            (position..position, first_prefix.clone())
 8426                        }));
 8427                    }
 8428                } else if let Some((full_comment_prefix, comment_suffix)) =
 8429                    language.block_comment_delimiters()
 8430                {
 8431                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8432                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8433                    let prefix_range = comment_prefix_range(
 8434                        snapshot.deref(),
 8435                        start_row,
 8436                        comment_prefix,
 8437                        comment_prefix_whitespace,
 8438                    );
 8439                    let suffix_range = comment_suffix_range(
 8440                        snapshot.deref(),
 8441                        end_row,
 8442                        comment_suffix.trim_start_matches(' '),
 8443                        comment_suffix.starts_with(' '),
 8444                    );
 8445
 8446                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8447                        edits.push((
 8448                            prefix_range.start..prefix_range.start,
 8449                            full_comment_prefix.clone(),
 8450                        ));
 8451                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8452                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8453                    } else {
 8454                        edits.push((prefix_range, empty_str.clone()));
 8455                        edits.push((suffix_range, empty_str.clone()));
 8456                    }
 8457                } else {
 8458                    continue;
 8459                }
 8460            }
 8461
 8462            drop(snapshot);
 8463            this.buffer.update(cx, |buffer, cx| {
 8464                buffer.edit(edits, None, cx);
 8465            });
 8466
 8467            // Adjust selections so that they end before any comment suffixes that
 8468            // were inserted.
 8469            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8470            let mut selections = this.selections.all::<Point>(cx);
 8471            let snapshot = this.buffer.read(cx).read(cx);
 8472            for selection in &mut selections {
 8473                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8474                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8475                        Ordering::Less => {
 8476                            suffixes_inserted.next();
 8477                            continue;
 8478                        }
 8479                        Ordering::Greater => break,
 8480                        Ordering::Equal => {
 8481                            if selection.end.column == snapshot.line_len(row) {
 8482                                if selection.is_empty() {
 8483                                    selection.start.column -= suffix_len as u32;
 8484                                }
 8485                                selection.end.column -= suffix_len as u32;
 8486                            }
 8487                            break;
 8488                        }
 8489                    }
 8490                }
 8491            }
 8492
 8493            drop(snapshot);
 8494            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8495
 8496            let selections = this.selections.all::<Point>(cx);
 8497            let selections_on_single_row = selections.windows(2).all(|selections| {
 8498                selections[0].start.row == selections[1].start.row
 8499                    && selections[0].end.row == selections[1].end.row
 8500                    && selections[0].start.row == selections[0].end.row
 8501            });
 8502            let selections_selecting = selections
 8503                .iter()
 8504                .any(|selection| selection.start != selection.end);
 8505            let advance_downwards = action.advance_downwards
 8506                && selections_on_single_row
 8507                && !selections_selecting
 8508                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8509
 8510            if advance_downwards {
 8511                let snapshot = this.buffer.read(cx).snapshot(cx);
 8512
 8513                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8514                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8515                        let mut point = display_point.to_point(display_snapshot);
 8516                        point.row += 1;
 8517                        point = snapshot.clip_point(point, Bias::Left);
 8518                        let display_point = point.to_display_point(display_snapshot);
 8519                        let goal = SelectionGoal::HorizontalPosition(
 8520                            display_snapshot
 8521                                .x_for_display_point(display_point, text_layout_details)
 8522                                .into(),
 8523                        );
 8524                        (display_point, goal)
 8525                    })
 8526                });
 8527            }
 8528        });
 8529    }
 8530
 8531    pub fn select_enclosing_symbol(
 8532        &mut self,
 8533        _: &SelectEnclosingSymbol,
 8534        cx: &mut ViewContext<Self>,
 8535    ) {
 8536        let buffer = self.buffer.read(cx).snapshot(cx);
 8537        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8538
 8539        fn update_selection(
 8540            selection: &Selection<usize>,
 8541            buffer_snap: &MultiBufferSnapshot,
 8542        ) -> Option<Selection<usize>> {
 8543            let cursor = selection.head();
 8544            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8545            for symbol in symbols.iter().rev() {
 8546                let start = symbol.range.start.to_offset(buffer_snap);
 8547                let end = symbol.range.end.to_offset(buffer_snap);
 8548                let new_range = start..end;
 8549                if start < selection.start || end > selection.end {
 8550                    return Some(Selection {
 8551                        id: selection.id,
 8552                        start: new_range.start,
 8553                        end: new_range.end,
 8554                        goal: SelectionGoal::None,
 8555                        reversed: selection.reversed,
 8556                    });
 8557                }
 8558            }
 8559            None
 8560        }
 8561
 8562        let mut selected_larger_symbol = false;
 8563        let new_selections = old_selections
 8564            .iter()
 8565            .map(|selection| match update_selection(selection, &buffer) {
 8566                Some(new_selection) => {
 8567                    if new_selection.range() != selection.range() {
 8568                        selected_larger_symbol = true;
 8569                    }
 8570                    new_selection
 8571                }
 8572                None => selection.clone(),
 8573            })
 8574            .collect::<Vec<_>>();
 8575
 8576        if selected_larger_symbol {
 8577            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8578                s.select(new_selections);
 8579            });
 8580        }
 8581    }
 8582
 8583    pub fn select_larger_syntax_node(
 8584        &mut self,
 8585        _: &SelectLargerSyntaxNode,
 8586        cx: &mut ViewContext<Self>,
 8587    ) {
 8588        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8589        let buffer = self.buffer.read(cx).snapshot(cx);
 8590        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8591
 8592        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8593        let mut selected_larger_node = false;
 8594        let new_selections = old_selections
 8595            .iter()
 8596            .map(|selection| {
 8597                let old_range = selection.start..selection.end;
 8598                let mut new_range = old_range.clone();
 8599                while let Some(containing_range) =
 8600                    buffer.range_for_syntax_ancestor(new_range.clone())
 8601                {
 8602                    new_range = containing_range;
 8603                    if !display_map.intersects_fold(new_range.start)
 8604                        && !display_map.intersects_fold(new_range.end)
 8605                    {
 8606                        break;
 8607                    }
 8608                }
 8609
 8610                selected_larger_node |= new_range != old_range;
 8611                Selection {
 8612                    id: selection.id,
 8613                    start: new_range.start,
 8614                    end: new_range.end,
 8615                    goal: SelectionGoal::None,
 8616                    reversed: selection.reversed,
 8617                }
 8618            })
 8619            .collect::<Vec<_>>();
 8620
 8621        if selected_larger_node {
 8622            stack.push(old_selections);
 8623            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8624                s.select(new_selections);
 8625            });
 8626        }
 8627        self.select_larger_syntax_node_stack = stack;
 8628    }
 8629
 8630    pub fn select_smaller_syntax_node(
 8631        &mut self,
 8632        _: &SelectSmallerSyntaxNode,
 8633        cx: &mut ViewContext<Self>,
 8634    ) {
 8635        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8636        if let Some(selections) = stack.pop() {
 8637            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8638                s.select(selections.to_vec());
 8639            });
 8640        }
 8641        self.select_larger_syntax_node_stack = stack;
 8642    }
 8643
 8644    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8645        if !EditorSettings::get_global(cx).gutter.runnables {
 8646            self.clear_tasks();
 8647            return Task::ready(());
 8648        }
 8649        let project = self.project.clone();
 8650        cx.spawn(|this, mut cx| async move {
 8651            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8652                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8653            }) else {
 8654                return;
 8655            };
 8656
 8657            let Some(project) = project else {
 8658                return;
 8659            };
 8660
 8661            let hide_runnables = project
 8662                .update(&mut cx, |project, cx| {
 8663                    // Do not display any test indicators in non-dev server remote projects.
 8664                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8665                })
 8666                .unwrap_or(true);
 8667            if hide_runnables {
 8668                return;
 8669            }
 8670            let new_rows =
 8671                cx.background_executor()
 8672                    .spawn({
 8673                        let snapshot = display_snapshot.clone();
 8674                        async move {
 8675                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8676                        }
 8677                    })
 8678                    .await;
 8679            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8680
 8681            this.update(&mut cx, |this, _| {
 8682                this.clear_tasks();
 8683                for (key, value) in rows {
 8684                    this.insert_tasks(key, value);
 8685                }
 8686            })
 8687            .ok();
 8688        })
 8689    }
 8690    fn fetch_runnable_ranges(
 8691        snapshot: &DisplaySnapshot,
 8692        range: Range<Anchor>,
 8693    ) -> Vec<language::RunnableRange> {
 8694        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8695    }
 8696
 8697    fn runnable_rows(
 8698        project: Model<Project>,
 8699        snapshot: DisplaySnapshot,
 8700        runnable_ranges: Vec<RunnableRange>,
 8701        mut cx: AsyncWindowContext,
 8702    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8703        runnable_ranges
 8704            .into_iter()
 8705            .filter_map(|mut runnable| {
 8706                let tasks = cx
 8707                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8708                    .ok()?;
 8709                if tasks.is_empty() {
 8710                    return None;
 8711                }
 8712
 8713                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8714
 8715                let row = snapshot
 8716                    .buffer_snapshot
 8717                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8718                    .1
 8719                    .start
 8720                    .row;
 8721
 8722                let context_range =
 8723                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8724                Some((
 8725                    (runnable.buffer_id, row),
 8726                    RunnableTasks {
 8727                        templates: tasks,
 8728                        offset: MultiBufferOffset(runnable.run_range.start),
 8729                        context_range,
 8730                        column: point.column,
 8731                        extra_variables: runnable.extra_captures,
 8732                    },
 8733                ))
 8734            })
 8735            .collect()
 8736    }
 8737
 8738    fn templates_with_tags(
 8739        project: &Model<Project>,
 8740        runnable: &mut Runnable,
 8741        cx: &WindowContext<'_>,
 8742    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8743        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8744            let (worktree_id, file) = project
 8745                .buffer_for_id(runnable.buffer, cx)
 8746                .and_then(|buffer| buffer.read(cx).file())
 8747                .map(|file| (file.worktree_id(cx), file.clone()))
 8748                .unzip();
 8749
 8750            (project.task_inventory().clone(), worktree_id, file)
 8751        });
 8752
 8753        let inventory = inventory.read(cx);
 8754        let tags = mem::take(&mut runnable.tags);
 8755        let mut tags: Vec<_> = tags
 8756            .into_iter()
 8757            .flat_map(|tag| {
 8758                let tag = tag.0.clone();
 8759                inventory
 8760                    .list_tasks(
 8761                        file.clone(),
 8762                        Some(runnable.language.clone()),
 8763                        worktree_id,
 8764                        cx,
 8765                    )
 8766                    .into_iter()
 8767                    .filter(move |(_, template)| {
 8768                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8769                    })
 8770            })
 8771            .sorted_by_key(|(kind, _)| kind.to_owned())
 8772            .collect();
 8773        if let Some((leading_tag_source, _)) = tags.first() {
 8774            // Strongest source wins; if we have worktree tag binding, prefer that to
 8775            // global and language bindings;
 8776            // if we have a global binding, prefer that to language binding.
 8777            let first_mismatch = tags
 8778                .iter()
 8779                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8780            if let Some(index) = first_mismatch {
 8781                tags.truncate(index);
 8782            }
 8783        }
 8784
 8785        tags
 8786    }
 8787
 8788    pub fn move_to_enclosing_bracket(
 8789        &mut self,
 8790        _: &MoveToEnclosingBracket,
 8791        cx: &mut ViewContext<Self>,
 8792    ) {
 8793        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8794            s.move_offsets_with(|snapshot, selection| {
 8795                let Some(enclosing_bracket_ranges) =
 8796                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8797                else {
 8798                    return;
 8799                };
 8800
 8801                let mut best_length = usize::MAX;
 8802                let mut best_inside = false;
 8803                let mut best_in_bracket_range = false;
 8804                let mut best_destination = None;
 8805                for (open, close) in enclosing_bracket_ranges {
 8806                    let close = close.to_inclusive();
 8807                    let length = close.end() - open.start;
 8808                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8809                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8810                        || close.contains(&selection.head());
 8811
 8812                    // If best is next to a bracket and current isn't, skip
 8813                    if !in_bracket_range && best_in_bracket_range {
 8814                        continue;
 8815                    }
 8816
 8817                    // Prefer smaller lengths unless best is inside and current isn't
 8818                    if length > best_length && (best_inside || !inside) {
 8819                        continue;
 8820                    }
 8821
 8822                    best_length = length;
 8823                    best_inside = inside;
 8824                    best_in_bracket_range = in_bracket_range;
 8825                    best_destination = Some(
 8826                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8827                            if inside {
 8828                                open.end
 8829                            } else {
 8830                                open.start
 8831                            }
 8832                        } else if inside {
 8833                            *close.start()
 8834                        } else {
 8835                            *close.end()
 8836                        },
 8837                    );
 8838                }
 8839
 8840                if let Some(destination) = best_destination {
 8841                    selection.collapse_to(destination, SelectionGoal::None);
 8842                }
 8843            })
 8844        });
 8845    }
 8846
 8847    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8848        self.end_selection(cx);
 8849        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8850        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8851            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8852            self.select_next_state = entry.select_next_state;
 8853            self.select_prev_state = entry.select_prev_state;
 8854            self.add_selections_state = entry.add_selections_state;
 8855            self.request_autoscroll(Autoscroll::newest(), cx);
 8856        }
 8857        self.selection_history.mode = SelectionHistoryMode::Normal;
 8858    }
 8859
 8860    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8861        self.end_selection(cx);
 8862        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8863        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8864            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8865            self.select_next_state = entry.select_next_state;
 8866            self.select_prev_state = entry.select_prev_state;
 8867            self.add_selections_state = entry.add_selections_state;
 8868            self.request_autoscroll(Autoscroll::newest(), cx);
 8869        }
 8870        self.selection_history.mode = SelectionHistoryMode::Normal;
 8871    }
 8872
 8873    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8874        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8875    }
 8876
 8877    pub fn expand_excerpts_down(
 8878        &mut self,
 8879        action: &ExpandExcerptsDown,
 8880        cx: &mut ViewContext<Self>,
 8881    ) {
 8882        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8883    }
 8884
 8885    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8886        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8887    }
 8888
 8889    pub fn expand_excerpts_for_direction(
 8890        &mut self,
 8891        lines: u32,
 8892        direction: ExpandExcerptDirection,
 8893        cx: &mut ViewContext<Self>,
 8894    ) {
 8895        let selections = self.selections.disjoint_anchors();
 8896
 8897        let lines = if lines == 0 {
 8898            EditorSettings::get_global(cx).expand_excerpt_lines
 8899        } else {
 8900            lines
 8901        };
 8902
 8903        self.buffer.update(cx, |buffer, cx| {
 8904            buffer.expand_excerpts(
 8905                selections
 8906                    .iter()
 8907                    .map(|selection| selection.head().excerpt_id)
 8908                    .dedup(),
 8909                lines,
 8910                direction,
 8911                cx,
 8912            )
 8913        })
 8914    }
 8915
 8916    pub fn expand_excerpt(
 8917        &mut self,
 8918        excerpt: ExcerptId,
 8919        direction: ExpandExcerptDirection,
 8920        cx: &mut ViewContext<Self>,
 8921    ) {
 8922        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8923        self.buffer.update(cx, |buffer, cx| {
 8924            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8925        })
 8926    }
 8927
 8928    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8929        self.go_to_diagnostic_impl(Direction::Next, cx)
 8930    }
 8931
 8932    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8933        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8934    }
 8935
 8936    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8937        let buffer = self.buffer.read(cx).snapshot(cx);
 8938        let selection = self.selections.newest::<usize>(cx);
 8939
 8940        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8941        if direction == Direction::Next {
 8942            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8943                let (group_id, jump_to) = popover.activation_info();
 8944                if self.activate_diagnostics(group_id, cx) {
 8945                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8946                        let mut new_selection = s.newest_anchor().clone();
 8947                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8948                        s.select_anchors(vec![new_selection.clone()]);
 8949                    });
 8950                }
 8951                return;
 8952            }
 8953        }
 8954
 8955        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8956            active_diagnostics
 8957                .primary_range
 8958                .to_offset(&buffer)
 8959                .to_inclusive()
 8960        });
 8961        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8962            if active_primary_range.contains(&selection.head()) {
 8963                *active_primary_range.start()
 8964            } else {
 8965                selection.head()
 8966            }
 8967        } else {
 8968            selection.head()
 8969        };
 8970        let snapshot = self.snapshot(cx);
 8971        loop {
 8972            let diagnostics = if direction == Direction::Prev {
 8973                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8974            } else {
 8975                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8976            }
 8977            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8978            let group = diagnostics
 8979                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8980                // be sorted in a stable way
 8981                // skip until we are at current active diagnostic, if it exists
 8982                .skip_while(|entry| {
 8983                    (match direction {
 8984                        Direction::Prev => entry.range.start >= search_start,
 8985                        Direction::Next => entry.range.start <= search_start,
 8986                    }) && self
 8987                        .active_diagnostics
 8988                        .as_ref()
 8989                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8990                })
 8991                .find_map(|entry| {
 8992                    if entry.diagnostic.is_primary
 8993                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8994                        && !entry.range.is_empty()
 8995                        // if we match with the active diagnostic, skip it
 8996                        && Some(entry.diagnostic.group_id)
 8997                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8998                    {
 8999                        Some((entry.range, entry.diagnostic.group_id))
 9000                    } else {
 9001                        None
 9002                    }
 9003                });
 9004
 9005            if let Some((primary_range, group_id)) = group {
 9006                if self.activate_diagnostics(group_id, cx) {
 9007                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9008                        s.select(vec![Selection {
 9009                            id: selection.id,
 9010                            start: primary_range.start,
 9011                            end: primary_range.start,
 9012                            reversed: false,
 9013                            goal: SelectionGoal::None,
 9014                        }]);
 9015                    });
 9016                }
 9017                break;
 9018            } else {
 9019                // Cycle around to the start of the buffer, potentially moving back to the start of
 9020                // the currently active diagnostic.
 9021                active_primary_range.take();
 9022                if direction == Direction::Prev {
 9023                    if search_start == buffer.len() {
 9024                        break;
 9025                    } else {
 9026                        search_start = buffer.len();
 9027                    }
 9028                } else if search_start == 0 {
 9029                    break;
 9030                } else {
 9031                    search_start = 0;
 9032                }
 9033            }
 9034        }
 9035    }
 9036
 9037    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9038        let snapshot = self
 9039            .display_map
 9040            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9041        let selection = self.selections.newest::<Point>(cx);
 9042
 9043        if !self.seek_in_direction(
 9044            &snapshot,
 9045            selection.head(),
 9046            false,
 9047            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9048                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 9049            ),
 9050            cx,
 9051        ) {
 9052            let wrapped_point = Point::zero();
 9053            self.seek_in_direction(
 9054                &snapshot,
 9055                wrapped_point,
 9056                true,
 9057                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9058                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9059                ),
 9060                cx,
 9061            );
 9062        }
 9063    }
 9064
 9065    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9066        let snapshot = self
 9067            .display_map
 9068            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9069        let selection = self.selections.newest::<Point>(cx);
 9070
 9071        if !self.seek_in_direction(
 9072            &snapshot,
 9073            selection.head(),
 9074            false,
 9075            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 9076                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 9077            ),
 9078            cx,
 9079        ) {
 9080            let wrapped_point = snapshot.buffer_snapshot.max_point();
 9081            self.seek_in_direction(
 9082                &snapshot,
 9083                wrapped_point,
 9084                true,
 9085                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 9086                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 9087                ),
 9088                cx,
 9089            );
 9090        }
 9091    }
 9092
 9093    fn seek_in_direction(
 9094        &mut self,
 9095        snapshot: &DisplaySnapshot,
 9096        initial_point: Point,
 9097        is_wrapped: bool,
 9098        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 9099        cx: &mut ViewContext<Editor>,
 9100    ) -> bool {
 9101        let display_point = initial_point.to_display_point(snapshot);
 9102        let mut hunks = hunks
 9103            .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
 9104            .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
 9105            .dedup();
 9106
 9107        if let Some(hunk) = hunks.next() {
 9108            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9109                let row = hunk.start_display_row();
 9110                let point = DisplayPoint::new(row, 0);
 9111                s.select_display_ranges([point..point]);
 9112            });
 9113
 9114            true
 9115        } else {
 9116            false
 9117        }
 9118    }
 9119
 9120    pub fn go_to_definition(
 9121        &mut self,
 9122        _: &GoToDefinition,
 9123        cx: &mut ViewContext<Self>,
 9124    ) -> Task<Result<Navigated>> {
 9125        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9126        cx.spawn(|editor, mut cx| async move {
 9127            if definition.await? == Navigated::Yes {
 9128                return Ok(Navigated::Yes);
 9129            }
 9130            match editor.update(&mut cx, |editor, cx| {
 9131                editor.find_all_references(&FindAllReferences, cx)
 9132            })? {
 9133                Some(references) => references.await,
 9134                None => Ok(Navigated::No),
 9135            }
 9136        })
 9137    }
 9138
 9139    pub fn go_to_declaration(
 9140        &mut self,
 9141        _: &GoToDeclaration,
 9142        cx: &mut ViewContext<Self>,
 9143    ) -> Task<Result<Navigated>> {
 9144        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9145    }
 9146
 9147    pub fn go_to_declaration_split(
 9148        &mut self,
 9149        _: &GoToDeclaration,
 9150        cx: &mut ViewContext<Self>,
 9151    ) -> Task<Result<Navigated>> {
 9152        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9153    }
 9154
 9155    pub fn go_to_implementation(
 9156        &mut self,
 9157        _: &GoToImplementation,
 9158        cx: &mut ViewContext<Self>,
 9159    ) -> Task<Result<Navigated>> {
 9160        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9161    }
 9162
 9163    pub fn go_to_implementation_split(
 9164        &mut self,
 9165        _: &GoToImplementationSplit,
 9166        cx: &mut ViewContext<Self>,
 9167    ) -> Task<Result<Navigated>> {
 9168        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9169    }
 9170
 9171    pub fn go_to_type_definition(
 9172        &mut self,
 9173        _: &GoToTypeDefinition,
 9174        cx: &mut ViewContext<Self>,
 9175    ) -> Task<Result<Navigated>> {
 9176        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9177    }
 9178
 9179    pub fn go_to_definition_split(
 9180        &mut self,
 9181        _: &GoToDefinitionSplit,
 9182        cx: &mut ViewContext<Self>,
 9183    ) -> Task<Result<Navigated>> {
 9184        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9185    }
 9186
 9187    pub fn go_to_type_definition_split(
 9188        &mut self,
 9189        _: &GoToTypeDefinitionSplit,
 9190        cx: &mut ViewContext<Self>,
 9191    ) -> Task<Result<Navigated>> {
 9192        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9193    }
 9194
 9195    fn go_to_definition_of_kind(
 9196        &mut self,
 9197        kind: GotoDefinitionKind,
 9198        split: bool,
 9199        cx: &mut ViewContext<Self>,
 9200    ) -> Task<Result<Navigated>> {
 9201        let Some(workspace) = self.workspace() else {
 9202            return Task::ready(Ok(Navigated::No));
 9203        };
 9204        let buffer = self.buffer.read(cx);
 9205        let head = self.selections.newest::<usize>(cx).head();
 9206        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9207            text_anchor
 9208        } else {
 9209            return Task::ready(Ok(Navigated::No));
 9210        };
 9211
 9212        let project = workspace.read(cx).project().clone();
 9213        let definitions = project.update(cx, |project, cx| match kind {
 9214            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 9215            GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
 9216            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 9217            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 9218        });
 9219
 9220        cx.spawn(|editor, mut cx| async move {
 9221            let definitions = definitions.await?;
 9222            let navigated = editor
 9223                .update(&mut cx, |editor, cx| {
 9224                    editor.navigate_to_hover_links(
 9225                        Some(kind),
 9226                        definitions
 9227                            .into_iter()
 9228                            .filter(|location| {
 9229                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9230                            })
 9231                            .map(HoverLink::Text)
 9232                            .collect::<Vec<_>>(),
 9233                        split,
 9234                        cx,
 9235                    )
 9236                })?
 9237                .await?;
 9238            anyhow::Ok(navigated)
 9239        })
 9240    }
 9241
 9242    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9243        let position = self.selections.newest_anchor().head();
 9244        let Some((buffer, buffer_position)) =
 9245            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9246        else {
 9247            return;
 9248        };
 9249
 9250        cx.spawn(|editor, mut cx| async move {
 9251            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9252                editor.update(&mut cx, |_, cx| {
 9253                    cx.open_url(&url);
 9254                })
 9255            } else {
 9256                Ok(())
 9257            }
 9258        })
 9259        .detach();
 9260    }
 9261
 9262    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9263        let Some(workspace) = self.workspace() else {
 9264            return;
 9265        };
 9266
 9267        let position = self.selections.newest_anchor().head();
 9268
 9269        let Some((buffer, buffer_position)) =
 9270            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9271        else {
 9272            return;
 9273        };
 9274
 9275        let Some(project) = self.project.clone() else {
 9276            return;
 9277        };
 9278
 9279        cx.spawn(|_, mut cx| async move {
 9280            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9281
 9282            if let Some((_, path)) = result {
 9283                workspace
 9284                    .update(&mut cx, |workspace, cx| {
 9285                        workspace.open_resolved_path(path, cx)
 9286                    })?
 9287                    .await?;
 9288            }
 9289            anyhow::Ok(())
 9290        })
 9291        .detach();
 9292    }
 9293
 9294    pub(crate) fn navigate_to_hover_links(
 9295        &mut self,
 9296        kind: Option<GotoDefinitionKind>,
 9297        mut definitions: Vec<HoverLink>,
 9298        split: bool,
 9299        cx: &mut ViewContext<Editor>,
 9300    ) -> Task<Result<Navigated>> {
 9301        // If there is one definition, just open it directly
 9302        if definitions.len() == 1 {
 9303            let definition = definitions.pop().unwrap();
 9304
 9305            enum TargetTaskResult {
 9306                Location(Option<Location>),
 9307                AlreadyNavigated,
 9308            }
 9309
 9310            let target_task = match definition {
 9311                HoverLink::Text(link) => {
 9312                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9313                }
 9314                HoverLink::InlayHint(lsp_location, server_id) => {
 9315                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9316                    cx.background_executor().spawn(async move {
 9317                        let location = computation.await?;
 9318                        Ok(TargetTaskResult::Location(location))
 9319                    })
 9320                }
 9321                HoverLink::Url(url) => {
 9322                    cx.open_url(&url);
 9323                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9324                }
 9325                HoverLink::File(path) => {
 9326                    if let Some(workspace) = self.workspace() {
 9327                        cx.spawn(|_, mut cx| async move {
 9328                            workspace
 9329                                .update(&mut cx, |workspace, cx| {
 9330                                    workspace.open_resolved_path(path, cx)
 9331                                })?
 9332                                .await
 9333                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9334                        })
 9335                    } else {
 9336                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9337                    }
 9338                }
 9339            };
 9340            cx.spawn(|editor, mut cx| async move {
 9341                let target = match target_task.await.context("target resolution task")? {
 9342                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9343                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9344                    TargetTaskResult::Location(Some(target)) => target,
 9345                };
 9346
 9347                editor.update(&mut cx, |editor, cx| {
 9348                    let Some(workspace) = editor.workspace() else {
 9349                        return Navigated::No;
 9350                    };
 9351                    let pane = workspace.read(cx).active_pane().clone();
 9352
 9353                    let range = target.range.to_offset(target.buffer.read(cx));
 9354                    let range = editor.range_for_match(&range);
 9355
 9356                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9357                        let buffer = target.buffer.read(cx);
 9358                        let range = check_multiline_range(buffer, range);
 9359                        editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 9360                            s.select_ranges([range]);
 9361                        });
 9362                    } else {
 9363                        cx.window_context().defer(move |cx| {
 9364                            let target_editor: View<Self> =
 9365                                workspace.update(cx, |workspace, cx| {
 9366                                    let pane = if split {
 9367                                        workspace.adjacent_pane(cx)
 9368                                    } else {
 9369                                        workspace.active_pane().clone()
 9370                                    };
 9371
 9372                                    workspace.open_project_item(
 9373                                        pane,
 9374                                        target.buffer.clone(),
 9375                                        true,
 9376                                        true,
 9377                                        cx,
 9378                                    )
 9379                                });
 9380                            target_editor.update(cx, |target_editor, cx| {
 9381                                // When selecting a definition in a different buffer, disable the nav history
 9382                                // to avoid creating a history entry at the previous cursor location.
 9383                                pane.update(cx, |pane, _| pane.disable_history());
 9384                                let buffer = target.buffer.read(cx);
 9385                                let range = check_multiline_range(buffer, range);
 9386                                target_editor.change_selections(
 9387                                    Some(Autoscroll::focused()),
 9388                                    cx,
 9389                                    |s| {
 9390                                        s.select_ranges([range]);
 9391                                    },
 9392                                );
 9393                                pane.update(cx, |pane, _| pane.enable_history());
 9394                            });
 9395                        });
 9396                    }
 9397                    Navigated::Yes
 9398                })
 9399            })
 9400        } else if !definitions.is_empty() {
 9401            let replica_id = self.replica_id(cx);
 9402            cx.spawn(|editor, mut cx| async move {
 9403                let (title, location_tasks, workspace) = editor
 9404                    .update(&mut cx, |editor, cx| {
 9405                        let tab_kind = match kind {
 9406                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9407                            _ => "Definitions",
 9408                        };
 9409                        let title = definitions
 9410                            .iter()
 9411                            .find_map(|definition| match definition {
 9412                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9413                                    let buffer = origin.buffer.read(cx);
 9414                                    format!(
 9415                                        "{} for {}",
 9416                                        tab_kind,
 9417                                        buffer
 9418                                            .text_for_range(origin.range.clone())
 9419                                            .collect::<String>()
 9420                                    )
 9421                                }),
 9422                                HoverLink::InlayHint(_, _) => None,
 9423                                HoverLink::Url(_) => None,
 9424                                HoverLink::File(_) => None,
 9425                            })
 9426                            .unwrap_or(tab_kind.to_string());
 9427                        let location_tasks = definitions
 9428                            .into_iter()
 9429                            .map(|definition| match definition {
 9430                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9431                                HoverLink::InlayHint(lsp_location, server_id) => {
 9432                                    editor.compute_target_location(lsp_location, server_id, cx)
 9433                                }
 9434                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9435                                HoverLink::File(_) => Task::ready(Ok(None)),
 9436                            })
 9437                            .collect::<Vec<_>>();
 9438                        (title, location_tasks, editor.workspace().clone())
 9439                    })
 9440                    .context("location tasks preparation")?;
 9441
 9442                let locations = futures::future::join_all(location_tasks)
 9443                    .await
 9444                    .into_iter()
 9445                    .filter_map(|location| location.transpose())
 9446                    .collect::<Result<_>>()
 9447                    .context("location tasks")?;
 9448
 9449                let Some(workspace) = workspace else {
 9450                    return Ok(Navigated::No);
 9451                };
 9452                let opened = workspace
 9453                    .update(&mut cx, |workspace, cx| {
 9454                        Self::open_locations_in_multibuffer(
 9455                            workspace, locations, replica_id, title, split, cx,
 9456                        )
 9457                    })
 9458                    .ok();
 9459
 9460                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9461            })
 9462        } else {
 9463            Task::ready(Ok(Navigated::No))
 9464        }
 9465    }
 9466
 9467    fn compute_target_location(
 9468        &self,
 9469        lsp_location: lsp::Location,
 9470        server_id: LanguageServerId,
 9471        cx: &mut ViewContext<Editor>,
 9472    ) -> Task<anyhow::Result<Option<Location>>> {
 9473        let Some(project) = self.project.clone() else {
 9474            return Task::Ready(Some(Ok(None)));
 9475        };
 9476
 9477        cx.spawn(move |editor, mut cx| async move {
 9478            let location_task = editor.update(&mut cx, |editor, cx| {
 9479                project.update(cx, |project, cx| {
 9480                    let language_server_name =
 9481                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9482                            project
 9483                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9484                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9485                        });
 9486                    language_server_name.map(|language_server_name| {
 9487                        project.open_local_buffer_via_lsp(
 9488                            lsp_location.uri.clone(),
 9489                            server_id,
 9490                            language_server_name,
 9491                            cx,
 9492                        )
 9493                    })
 9494                })
 9495            })?;
 9496            let location = match location_task {
 9497                Some(task) => Some({
 9498                    let target_buffer_handle = task.await.context("open local buffer")?;
 9499                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9500                        let target_start = target_buffer
 9501                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9502                        let target_end = target_buffer
 9503                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9504                        target_buffer.anchor_after(target_start)
 9505                            ..target_buffer.anchor_before(target_end)
 9506                    })?;
 9507                    Location {
 9508                        buffer: target_buffer_handle,
 9509                        range,
 9510                    }
 9511                }),
 9512                None => None,
 9513            };
 9514            Ok(location)
 9515        })
 9516    }
 9517
 9518    pub fn find_all_references(
 9519        &mut self,
 9520        _: &FindAllReferences,
 9521        cx: &mut ViewContext<Self>,
 9522    ) -> Option<Task<Result<Navigated>>> {
 9523        let multi_buffer = self.buffer.read(cx);
 9524        let selection = self.selections.newest::<usize>(cx);
 9525        let head = selection.head();
 9526
 9527        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9528        let head_anchor = multi_buffer_snapshot.anchor_at(
 9529            head,
 9530            if head < selection.tail() {
 9531                Bias::Right
 9532            } else {
 9533                Bias::Left
 9534            },
 9535        );
 9536
 9537        match self
 9538            .find_all_references_task_sources
 9539            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9540        {
 9541            Ok(_) => {
 9542                log::info!(
 9543                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9544                );
 9545                return None;
 9546            }
 9547            Err(i) => {
 9548                self.find_all_references_task_sources.insert(i, head_anchor);
 9549            }
 9550        }
 9551
 9552        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9553        let replica_id = self.replica_id(cx);
 9554        let workspace = self.workspace()?;
 9555        let project = workspace.read(cx).project().clone();
 9556        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9557        Some(cx.spawn(|editor, mut cx| async move {
 9558            let _cleanup = defer({
 9559                let mut cx = cx.clone();
 9560                move || {
 9561                    let _ = editor.update(&mut cx, |editor, _| {
 9562                        if let Ok(i) =
 9563                            editor
 9564                                .find_all_references_task_sources
 9565                                .binary_search_by(|anchor| {
 9566                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9567                                })
 9568                        {
 9569                            editor.find_all_references_task_sources.remove(i);
 9570                        }
 9571                    });
 9572                }
 9573            });
 9574
 9575            let locations = references.await?;
 9576            if locations.is_empty() {
 9577                return anyhow::Ok(Navigated::No);
 9578            }
 9579
 9580            workspace.update(&mut cx, |workspace, cx| {
 9581                let title = locations
 9582                    .first()
 9583                    .as_ref()
 9584                    .map(|location| {
 9585                        let buffer = location.buffer.read(cx);
 9586                        format!(
 9587                            "References to `{}`",
 9588                            buffer
 9589                                .text_for_range(location.range.clone())
 9590                                .collect::<String>()
 9591                        )
 9592                    })
 9593                    .unwrap();
 9594                Self::open_locations_in_multibuffer(
 9595                    workspace, locations, replica_id, title, false, cx,
 9596                );
 9597                Navigated::Yes
 9598            })
 9599        }))
 9600    }
 9601
 9602    /// Opens a multibuffer with the given project locations in it
 9603    pub fn open_locations_in_multibuffer(
 9604        workspace: &mut Workspace,
 9605        mut locations: Vec<Location>,
 9606        replica_id: ReplicaId,
 9607        title: String,
 9608        split: bool,
 9609        cx: &mut ViewContext<Workspace>,
 9610    ) {
 9611        // If there are multiple definitions, open them in a multibuffer
 9612        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9613        let mut locations = locations.into_iter().peekable();
 9614        let mut ranges_to_highlight = Vec::new();
 9615        let capability = workspace.project().read(cx).capability();
 9616
 9617        let excerpt_buffer = cx.new_model(|cx| {
 9618            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 9619            while let Some(location) = locations.next() {
 9620                let buffer = location.buffer.read(cx);
 9621                let mut ranges_for_buffer = Vec::new();
 9622                let range = location.range.to_offset(buffer);
 9623                ranges_for_buffer.push(range.clone());
 9624
 9625                while let Some(next_location) = locations.peek() {
 9626                    if next_location.buffer == location.buffer {
 9627                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9628                        locations.next();
 9629                    } else {
 9630                        break;
 9631                    }
 9632                }
 9633
 9634                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9635                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9636                    location.buffer.clone(),
 9637                    ranges_for_buffer,
 9638                    DEFAULT_MULTIBUFFER_CONTEXT,
 9639                    cx,
 9640                ))
 9641            }
 9642
 9643            multibuffer.with_title(title)
 9644        });
 9645
 9646        let editor = cx.new_view(|cx| {
 9647            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9648        });
 9649        editor.update(cx, |editor, cx| {
 9650            if let Some(first_range) = ranges_to_highlight.first() {
 9651                editor.change_selections(None, cx, |selections| {
 9652                    selections.clear_disjoint();
 9653                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9654                });
 9655            }
 9656            editor.highlight_background::<Self>(
 9657                &ranges_to_highlight,
 9658                |theme| theme.editor_highlighted_line_background,
 9659                cx,
 9660            );
 9661        });
 9662
 9663        let item = Box::new(editor);
 9664        let item_id = item.item_id();
 9665
 9666        if split {
 9667            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9668        } else {
 9669            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9670                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9671                    pane.close_current_preview_item(cx)
 9672                } else {
 9673                    None
 9674                }
 9675            });
 9676            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9677        }
 9678        workspace.active_pane().update(cx, |pane, cx| {
 9679            pane.set_preview_item_id(Some(item_id), cx);
 9680        });
 9681    }
 9682
 9683    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9684        use language::ToOffset as _;
 9685
 9686        let project = self.project.clone()?;
 9687        let selection = self.selections.newest_anchor().clone();
 9688        let (cursor_buffer, cursor_buffer_position) = self
 9689            .buffer
 9690            .read(cx)
 9691            .text_anchor_for_position(selection.head(), cx)?;
 9692        let (tail_buffer, cursor_buffer_position_end) = self
 9693            .buffer
 9694            .read(cx)
 9695            .text_anchor_for_position(selection.tail(), cx)?;
 9696        if tail_buffer != cursor_buffer {
 9697            return None;
 9698        }
 9699
 9700        let snapshot = cursor_buffer.read(cx).snapshot();
 9701        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9702        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9703        let prepare_rename = project.update(cx, |project, cx| {
 9704            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 9705        });
 9706        drop(snapshot);
 9707
 9708        Some(cx.spawn(|this, mut cx| async move {
 9709            let rename_range = if let Some(range) = prepare_rename.await? {
 9710                Some(range)
 9711            } else {
 9712                this.update(&mut cx, |this, cx| {
 9713                    let buffer = this.buffer.read(cx).snapshot(cx);
 9714                    let mut buffer_highlights = this
 9715                        .document_highlights_for_position(selection.head(), &buffer)
 9716                        .filter(|highlight| {
 9717                            highlight.start.excerpt_id == selection.head().excerpt_id
 9718                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9719                        });
 9720                    buffer_highlights
 9721                        .next()
 9722                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9723                })?
 9724            };
 9725            if let Some(rename_range) = rename_range {
 9726                this.update(&mut cx, |this, cx| {
 9727                    let snapshot = cursor_buffer.read(cx).snapshot();
 9728                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9729                    let cursor_offset_in_rename_range =
 9730                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9731                    let cursor_offset_in_rename_range_end =
 9732                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9733
 9734                    this.take_rename(false, cx);
 9735                    let buffer = this.buffer.read(cx).read(cx);
 9736                    let cursor_offset = selection.head().to_offset(&buffer);
 9737                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9738                    let rename_end = rename_start + rename_buffer_range.len();
 9739                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9740                    let mut old_highlight_id = None;
 9741                    let old_name: Arc<str> = buffer
 9742                        .chunks(rename_start..rename_end, true)
 9743                        .map(|chunk| {
 9744                            if old_highlight_id.is_none() {
 9745                                old_highlight_id = chunk.syntax_highlight_id;
 9746                            }
 9747                            chunk.text
 9748                        })
 9749                        .collect::<String>()
 9750                        .into();
 9751
 9752                    drop(buffer);
 9753
 9754                    // Position the selection in the rename editor so that it matches the current selection.
 9755                    this.show_local_selections = false;
 9756                    let rename_editor = cx.new_view(|cx| {
 9757                        let mut editor = Editor::single_line(cx);
 9758                        editor.buffer.update(cx, |buffer, cx| {
 9759                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9760                        });
 9761                        let rename_selection_range = match cursor_offset_in_rename_range
 9762                            .cmp(&cursor_offset_in_rename_range_end)
 9763                        {
 9764                            Ordering::Equal => {
 9765                                editor.select_all(&SelectAll, cx);
 9766                                return editor;
 9767                            }
 9768                            Ordering::Less => {
 9769                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9770                            }
 9771                            Ordering::Greater => {
 9772                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9773                            }
 9774                        };
 9775                        if rename_selection_range.end > old_name.len() {
 9776                            editor.select_all(&SelectAll, cx);
 9777                        } else {
 9778                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9779                                s.select_ranges([rename_selection_range]);
 9780                            });
 9781                        }
 9782                        editor
 9783                    });
 9784                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
 9785                        if e == &EditorEvent::Focused {
 9786                            cx.emit(EditorEvent::FocusedIn)
 9787                        }
 9788                    })
 9789                    .detach();
 9790
 9791                    let write_highlights =
 9792                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9793                    let read_highlights =
 9794                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9795                    let ranges = write_highlights
 9796                        .iter()
 9797                        .flat_map(|(_, ranges)| ranges.iter())
 9798                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9799                        .cloned()
 9800                        .collect();
 9801
 9802                    this.highlight_text::<Rename>(
 9803                        ranges,
 9804                        HighlightStyle {
 9805                            fade_out: Some(0.6),
 9806                            ..Default::default()
 9807                        },
 9808                        cx,
 9809                    );
 9810                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9811                    cx.focus(&rename_focus_handle);
 9812                    let block_id = this.insert_blocks(
 9813                        [BlockProperties {
 9814                            style: BlockStyle::Flex,
 9815                            position: range.start,
 9816                            height: 1,
 9817                            render: Box::new({
 9818                                let rename_editor = rename_editor.clone();
 9819                                move |cx: &mut BlockContext| {
 9820                                    let mut text_style = cx.editor_style.text.clone();
 9821                                    if let Some(highlight_style) = old_highlight_id
 9822                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9823                                    {
 9824                                        text_style = text_style.highlight(highlight_style);
 9825                                    }
 9826                                    div()
 9827                                        .pl(cx.anchor_x)
 9828                                        .child(EditorElement::new(
 9829                                            &rename_editor,
 9830                                            EditorStyle {
 9831                                                background: cx.theme().system().transparent,
 9832                                                local_player: cx.editor_style.local_player,
 9833                                                text: text_style,
 9834                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9835                                                syntax: cx.editor_style.syntax.clone(),
 9836                                                status: cx.editor_style.status.clone(),
 9837                                                inlay_hints_style: HighlightStyle {
 9838                                                    color: Some(cx.theme().status().hint),
 9839                                                    font_weight: Some(FontWeight::BOLD),
 9840                                                    ..HighlightStyle::default()
 9841                                                },
 9842                                                suggestions_style: HighlightStyle {
 9843                                                    color: Some(cx.theme().status().predictive),
 9844                                                    ..HighlightStyle::default()
 9845                                                },
 9846                                                ..EditorStyle::default()
 9847                                            },
 9848                                        ))
 9849                                        .into_any_element()
 9850                                }
 9851                            }),
 9852                            disposition: BlockDisposition::Below,
 9853                            priority: 0,
 9854                        }],
 9855                        Some(Autoscroll::fit()),
 9856                        cx,
 9857                    )[0];
 9858                    this.pending_rename = Some(RenameState {
 9859                        range,
 9860                        old_name,
 9861                        editor: rename_editor,
 9862                        block_id,
 9863                    });
 9864                })?;
 9865            }
 9866
 9867            Ok(())
 9868        }))
 9869    }
 9870
 9871    pub fn confirm_rename(
 9872        &mut self,
 9873        _: &ConfirmRename,
 9874        cx: &mut ViewContext<Self>,
 9875    ) -> Option<Task<Result<()>>> {
 9876        let rename = self.take_rename(false, cx)?;
 9877        let workspace = self.workspace()?;
 9878        let (start_buffer, start) = self
 9879            .buffer
 9880            .read(cx)
 9881            .text_anchor_for_position(rename.range.start, cx)?;
 9882        let (end_buffer, end) = self
 9883            .buffer
 9884            .read(cx)
 9885            .text_anchor_for_position(rename.range.end, cx)?;
 9886        if start_buffer != end_buffer {
 9887            return None;
 9888        }
 9889
 9890        let buffer = start_buffer;
 9891        let range = start..end;
 9892        let old_name = rename.old_name;
 9893        let new_name = rename.editor.read(cx).text(cx);
 9894
 9895        let rename = workspace
 9896            .read(cx)
 9897            .project()
 9898            .clone()
 9899            .update(cx, |project, cx| {
 9900                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 9901            });
 9902        let workspace = workspace.downgrade();
 9903
 9904        Some(cx.spawn(|editor, mut cx| async move {
 9905            let project_transaction = rename.await?;
 9906            Self::open_project_transaction(
 9907                &editor,
 9908                workspace,
 9909                project_transaction,
 9910                format!("Rename: {}{}", old_name, new_name),
 9911                cx.clone(),
 9912            )
 9913            .await?;
 9914
 9915            editor.update(&mut cx, |editor, cx| {
 9916                editor.refresh_document_highlights(cx);
 9917            })?;
 9918            Ok(())
 9919        }))
 9920    }
 9921
 9922    fn take_rename(
 9923        &mut self,
 9924        moving_cursor: bool,
 9925        cx: &mut ViewContext<Self>,
 9926    ) -> Option<RenameState> {
 9927        let rename = self.pending_rename.take()?;
 9928        if rename.editor.focus_handle(cx).is_focused(cx) {
 9929            cx.focus(&self.focus_handle);
 9930        }
 9931
 9932        self.remove_blocks(
 9933            [rename.block_id].into_iter().collect(),
 9934            Some(Autoscroll::fit()),
 9935            cx,
 9936        );
 9937        self.clear_highlights::<Rename>(cx);
 9938        self.show_local_selections = true;
 9939
 9940        if moving_cursor {
 9941            let rename_editor = rename.editor.read(cx);
 9942            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 9943
 9944            // Update the selection to match the position of the selection inside
 9945            // the rename editor.
 9946            let snapshot = self.buffer.read(cx).read(cx);
 9947            let rename_range = rename.range.to_offset(&snapshot);
 9948            let cursor_in_editor = snapshot
 9949                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9950                .min(rename_range.end);
 9951            drop(snapshot);
 9952
 9953            self.change_selections(None, cx, |s| {
 9954                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9955            });
 9956        } else {
 9957            self.refresh_document_highlights(cx);
 9958        }
 9959
 9960        Some(rename)
 9961    }
 9962
 9963    pub fn pending_rename(&self) -> Option<&RenameState> {
 9964        self.pending_rename.as_ref()
 9965    }
 9966
 9967    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9968        let project = match &self.project {
 9969            Some(project) => project.clone(),
 9970            None => return None,
 9971        };
 9972
 9973        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 9974    }
 9975
 9976    fn perform_format(
 9977        &mut self,
 9978        project: Model<Project>,
 9979        trigger: FormatTrigger,
 9980        cx: &mut ViewContext<Self>,
 9981    ) -> Task<Result<()>> {
 9982        let buffer = self.buffer().clone();
 9983        let mut buffers = buffer.read(cx).all_buffers();
 9984        if trigger == FormatTrigger::Save {
 9985            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 9986        }
 9987
 9988        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 9989        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 9990
 9991        cx.spawn(|_, mut cx| async move {
 9992            let transaction = futures::select_biased! {
 9993                () = timeout => {
 9994                    log::warn!("timed out waiting for formatting");
 9995                    None
 9996                }
 9997                transaction = format.log_err().fuse() => transaction,
 9998            };
 9999
10000            buffer
10001                .update(&mut cx, |buffer, cx| {
10002                    if let Some(transaction) = transaction {
10003                        if !buffer.is_singleton() {
10004                            buffer.push_transaction(&transaction.0, cx);
10005                        }
10006                    }
10007
10008                    cx.notify();
10009                })
10010                .ok();
10011
10012            Ok(())
10013        })
10014    }
10015
10016    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10017        if let Some(project) = self.project.clone() {
10018            self.buffer.update(cx, |multi_buffer, cx| {
10019                project.update(cx, |project, cx| {
10020                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10021                });
10022            })
10023        }
10024    }
10025
10026    fn cancel_language_server_work(
10027        &mut self,
10028        _: &CancelLanguageServerWork,
10029        cx: &mut ViewContext<Self>,
10030    ) {
10031        if let Some(project) = self.project.clone() {
10032            self.buffer.update(cx, |multi_buffer, cx| {
10033                project.update(cx, |project, cx| {
10034                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10035                });
10036            })
10037        }
10038    }
10039
10040    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10041        cx.show_character_palette();
10042    }
10043
10044    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10045        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10046            let buffer = self.buffer.read(cx).snapshot(cx);
10047            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10048            let is_valid = buffer
10049                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10050                .any(|entry| {
10051                    entry.diagnostic.is_primary
10052                        && !entry.range.is_empty()
10053                        && entry.range.start == primary_range_start
10054                        && entry.diagnostic.message == active_diagnostics.primary_message
10055                });
10056
10057            if is_valid != active_diagnostics.is_valid {
10058                active_diagnostics.is_valid = is_valid;
10059                let mut new_styles = HashMap::default();
10060                for (block_id, diagnostic) in &active_diagnostics.blocks {
10061                    new_styles.insert(
10062                        *block_id,
10063                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10064                    );
10065                }
10066                self.display_map.update(cx, |display_map, _cx| {
10067                    display_map.replace_blocks(new_styles)
10068                });
10069            }
10070        }
10071    }
10072
10073    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10074        self.dismiss_diagnostics(cx);
10075        let snapshot = self.snapshot(cx);
10076        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10077            let buffer = self.buffer.read(cx).snapshot(cx);
10078
10079            let mut primary_range = None;
10080            let mut primary_message = None;
10081            let mut group_end = Point::zero();
10082            let diagnostic_group = buffer
10083                .diagnostic_group::<MultiBufferPoint>(group_id)
10084                .filter_map(|entry| {
10085                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10086                        && (entry.range.start.row == entry.range.end.row
10087                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10088                    {
10089                        return None;
10090                    }
10091                    if entry.range.end > group_end {
10092                        group_end = entry.range.end;
10093                    }
10094                    if entry.diagnostic.is_primary {
10095                        primary_range = Some(entry.range.clone());
10096                        primary_message = Some(entry.diagnostic.message.clone());
10097                    }
10098                    Some(entry)
10099                })
10100                .collect::<Vec<_>>();
10101            let primary_range = primary_range?;
10102            let primary_message = primary_message?;
10103            let primary_range =
10104                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10105
10106            let blocks = display_map
10107                .insert_blocks(
10108                    diagnostic_group.iter().map(|entry| {
10109                        let diagnostic = entry.diagnostic.clone();
10110                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10111                        BlockProperties {
10112                            style: BlockStyle::Fixed,
10113                            position: buffer.anchor_after(entry.range.start),
10114                            height: message_height,
10115                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10116                            disposition: BlockDisposition::Below,
10117                            priority: 0,
10118                        }
10119                    }),
10120                    cx,
10121                )
10122                .into_iter()
10123                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10124                .collect();
10125
10126            Some(ActiveDiagnosticGroup {
10127                primary_range,
10128                primary_message,
10129                group_id,
10130                blocks,
10131                is_valid: true,
10132            })
10133        });
10134        self.active_diagnostics.is_some()
10135    }
10136
10137    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10138        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10139            self.display_map.update(cx, |display_map, cx| {
10140                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10141            });
10142            cx.notify();
10143        }
10144    }
10145
10146    pub fn set_selections_from_remote(
10147        &mut self,
10148        selections: Vec<Selection<Anchor>>,
10149        pending_selection: Option<Selection<Anchor>>,
10150        cx: &mut ViewContext<Self>,
10151    ) {
10152        let old_cursor_position = self.selections.newest_anchor().head();
10153        self.selections.change_with(cx, |s| {
10154            s.select_anchors(selections);
10155            if let Some(pending_selection) = pending_selection {
10156                s.set_pending(pending_selection, SelectMode::Character);
10157            } else {
10158                s.clear_pending();
10159            }
10160        });
10161        self.selections_did_change(false, &old_cursor_position, true, cx);
10162    }
10163
10164    fn push_to_selection_history(&mut self) {
10165        self.selection_history.push(SelectionHistoryEntry {
10166            selections: self.selections.disjoint_anchors(),
10167            select_next_state: self.select_next_state.clone(),
10168            select_prev_state: self.select_prev_state.clone(),
10169            add_selections_state: self.add_selections_state.clone(),
10170        });
10171    }
10172
10173    pub fn transact(
10174        &mut self,
10175        cx: &mut ViewContext<Self>,
10176        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10177    ) -> Option<TransactionId> {
10178        self.start_transaction_at(Instant::now(), cx);
10179        update(self, cx);
10180        self.end_transaction_at(Instant::now(), cx)
10181    }
10182
10183    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10184        self.end_selection(cx);
10185        if let Some(tx_id) = self
10186            .buffer
10187            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10188        {
10189            self.selection_history
10190                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10191            cx.emit(EditorEvent::TransactionBegun {
10192                transaction_id: tx_id,
10193            })
10194        }
10195    }
10196
10197    fn end_transaction_at(
10198        &mut self,
10199        now: Instant,
10200        cx: &mut ViewContext<Self>,
10201    ) -> Option<TransactionId> {
10202        if let Some(transaction_id) = self
10203            .buffer
10204            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10205        {
10206            if let Some((_, end_selections)) =
10207                self.selection_history.transaction_mut(transaction_id)
10208            {
10209                *end_selections = Some(self.selections.disjoint_anchors());
10210            } else {
10211                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10212            }
10213
10214            cx.emit(EditorEvent::Edited { transaction_id });
10215            Some(transaction_id)
10216        } else {
10217            None
10218        }
10219    }
10220
10221    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10222        let mut fold_ranges = Vec::new();
10223
10224        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10225
10226        let selections = self.selections.all_adjusted(cx);
10227        for selection in selections {
10228            let range = selection.range().sorted();
10229            let buffer_start_row = range.start.row;
10230
10231            for row in (0..=range.end.row).rev() {
10232                if let Some((foldable_range, fold_text)) =
10233                    display_map.foldable_range(MultiBufferRow(row))
10234                {
10235                    if foldable_range.end.row >= buffer_start_row {
10236                        fold_ranges.push((foldable_range, fold_text));
10237                        if row <= range.start.row {
10238                            break;
10239                        }
10240                    }
10241                }
10242            }
10243        }
10244
10245        self.fold_ranges(fold_ranges, true, cx);
10246    }
10247
10248    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10249        let buffer_row = fold_at.buffer_row;
10250        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10251
10252        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10253            let autoscroll = self
10254                .selections
10255                .all::<Point>(cx)
10256                .iter()
10257                .any(|selection| fold_range.overlaps(&selection.range()));
10258
10259            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10260        }
10261    }
10262
10263    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10264        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10265        let buffer = &display_map.buffer_snapshot;
10266        let selections = self.selections.all::<Point>(cx);
10267        let ranges = selections
10268            .iter()
10269            .map(|s| {
10270                let range = s.display_range(&display_map).sorted();
10271                let mut start = range.start.to_point(&display_map);
10272                let mut end = range.end.to_point(&display_map);
10273                start.column = 0;
10274                end.column = buffer.line_len(MultiBufferRow(end.row));
10275                start..end
10276            })
10277            .collect::<Vec<_>>();
10278
10279        self.unfold_ranges(ranges, true, true, cx);
10280    }
10281
10282    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10283        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10284
10285        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10286            ..Point::new(
10287                unfold_at.buffer_row.0,
10288                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10289            );
10290
10291        let autoscroll = self
10292            .selections
10293            .all::<Point>(cx)
10294            .iter()
10295            .any(|selection| selection.range().overlaps(&intersection_range));
10296
10297        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10298    }
10299
10300    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10301        let selections = self.selections.all::<Point>(cx);
10302        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10303        let line_mode = self.selections.line_mode;
10304        let ranges = selections.into_iter().map(|s| {
10305            if line_mode {
10306                let start = Point::new(s.start.row, 0);
10307                let end = Point::new(
10308                    s.end.row,
10309                    display_map
10310                        .buffer_snapshot
10311                        .line_len(MultiBufferRow(s.end.row)),
10312                );
10313                (start..end, display_map.fold_placeholder.clone())
10314            } else {
10315                (s.start..s.end, display_map.fold_placeholder.clone())
10316            }
10317        });
10318        self.fold_ranges(ranges, true, cx);
10319    }
10320
10321    pub fn fold_ranges<T: ToOffset + Clone>(
10322        &mut self,
10323        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10324        auto_scroll: bool,
10325        cx: &mut ViewContext<Self>,
10326    ) {
10327        let mut fold_ranges = Vec::new();
10328        let mut buffers_affected = HashMap::default();
10329        let multi_buffer = self.buffer().read(cx);
10330        for (fold_range, fold_text) in ranges {
10331            if let Some((_, buffer, _)) =
10332                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10333            {
10334                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10335            };
10336            fold_ranges.push((fold_range, fold_text));
10337        }
10338
10339        let mut ranges = fold_ranges.into_iter().peekable();
10340        if ranges.peek().is_some() {
10341            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10342
10343            if auto_scroll {
10344                self.request_autoscroll(Autoscroll::fit(), cx);
10345            }
10346
10347            for buffer in buffers_affected.into_values() {
10348                self.sync_expanded_diff_hunks(buffer, cx);
10349            }
10350
10351            cx.notify();
10352
10353            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10354                // Clear diagnostics block when folding a range that contains it.
10355                let snapshot = self.snapshot(cx);
10356                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10357                    drop(snapshot);
10358                    self.active_diagnostics = Some(active_diagnostics);
10359                    self.dismiss_diagnostics(cx);
10360                } else {
10361                    self.active_diagnostics = Some(active_diagnostics);
10362                }
10363            }
10364
10365            self.scrollbar_marker_state.dirty = true;
10366        }
10367    }
10368
10369    pub fn unfold_ranges<T: ToOffset + Clone>(
10370        &mut self,
10371        ranges: impl IntoIterator<Item = Range<T>>,
10372        inclusive: bool,
10373        auto_scroll: bool,
10374        cx: &mut ViewContext<Self>,
10375    ) {
10376        let mut unfold_ranges = Vec::new();
10377        let mut buffers_affected = HashMap::default();
10378        let multi_buffer = self.buffer().read(cx);
10379        for range in ranges {
10380            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10381                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10382            };
10383            unfold_ranges.push(range);
10384        }
10385
10386        let mut ranges = unfold_ranges.into_iter().peekable();
10387        if ranges.peek().is_some() {
10388            self.display_map
10389                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10390            if auto_scroll {
10391                self.request_autoscroll(Autoscroll::fit(), cx);
10392            }
10393
10394            for buffer in buffers_affected.into_values() {
10395                self.sync_expanded_diff_hunks(buffer, cx);
10396            }
10397
10398            cx.notify();
10399            self.scrollbar_marker_state.dirty = true;
10400            self.active_indent_guides_state.dirty = true;
10401        }
10402    }
10403
10404    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10405        self.display_map.read(cx).fold_placeholder.clone()
10406    }
10407
10408    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10409        if hovered != self.gutter_hovered {
10410            self.gutter_hovered = hovered;
10411            cx.notify();
10412        }
10413    }
10414
10415    pub fn insert_blocks(
10416        &mut self,
10417        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10418        autoscroll: Option<Autoscroll>,
10419        cx: &mut ViewContext<Self>,
10420    ) -> Vec<CustomBlockId> {
10421        let blocks = self
10422            .display_map
10423            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10424        if let Some(autoscroll) = autoscroll {
10425            self.request_autoscroll(autoscroll, cx);
10426        }
10427        cx.notify();
10428        blocks
10429    }
10430
10431    pub fn resize_blocks(
10432        &mut self,
10433        heights: HashMap<CustomBlockId, u32>,
10434        autoscroll: Option<Autoscroll>,
10435        cx: &mut ViewContext<Self>,
10436    ) {
10437        self.display_map
10438            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10439        if let Some(autoscroll) = autoscroll {
10440            self.request_autoscroll(autoscroll, cx);
10441        }
10442        cx.notify();
10443    }
10444
10445    pub fn replace_blocks(
10446        &mut self,
10447        renderers: HashMap<CustomBlockId, RenderBlock>,
10448        autoscroll: Option<Autoscroll>,
10449        cx: &mut ViewContext<Self>,
10450    ) {
10451        self.display_map
10452            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10453        if let Some(autoscroll) = autoscroll {
10454            self.request_autoscroll(autoscroll, cx);
10455        }
10456        cx.notify();
10457    }
10458
10459    pub fn remove_blocks(
10460        &mut self,
10461        block_ids: HashSet<CustomBlockId>,
10462        autoscroll: Option<Autoscroll>,
10463        cx: &mut ViewContext<Self>,
10464    ) {
10465        self.display_map.update(cx, |display_map, cx| {
10466            display_map.remove_blocks(block_ids, cx)
10467        });
10468        if let Some(autoscroll) = autoscroll {
10469            self.request_autoscroll(autoscroll, cx);
10470        }
10471        cx.notify();
10472    }
10473
10474    pub fn row_for_block(
10475        &self,
10476        block_id: CustomBlockId,
10477        cx: &mut ViewContext<Self>,
10478    ) -> Option<DisplayRow> {
10479        self.display_map
10480            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10481    }
10482
10483    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10484        self.focused_block = Some(focused_block);
10485    }
10486
10487    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10488        self.focused_block.take()
10489    }
10490
10491    pub fn insert_creases(
10492        &mut self,
10493        creases: impl IntoIterator<Item = Crease>,
10494        cx: &mut ViewContext<Self>,
10495    ) -> Vec<CreaseId> {
10496        self.display_map
10497            .update(cx, |map, cx| map.insert_creases(creases, cx))
10498    }
10499
10500    pub fn remove_creases(
10501        &mut self,
10502        ids: impl IntoIterator<Item = CreaseId>,
10503        cx: &mut ViewContext<Self>,
10504    ) {
10505        self.display_map
10506            .update(cx, |map, cx| map.remove_creases(ids, cx));
10507    }
10508
10509    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10510        self.display_map
10511            .update(cx, |map, cx| map.snapshot(cx))
10512            .longest_row()
10513    }
10514
10515    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10516        self.display_map
10517            .update(cx, |map, cx| map.snapshot(cx))
10518            .max_point()
10519    }
10520
10521    pub fn text(&self, cx: &AppContext) -> String {
10522        self.buffer.read(cx).read(cx).text()
10523    }
10524
10525    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10526        let text = self.text(cx);
10527        let text = text.trim();
10528
10529        if text.is_empty() {
10530            return None;
10531        }
10532
10533        Some(text.to_string())
10534    }
10535
10536    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10537        self.transact(cx, |this, cx| {
10538            this.buffer
10539                .read(cx)
10540                .as_singleton()
10541                .expect("you can only call set_text on editors for singleton buffers")
10542                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10543        });
10544    }
10545
10546    pub fn display_text(&self, cx: &mut AppContext) -> String {
10547        self.display_map
10548            .update(cx, |map, cx| map.snapshot(cx))
10549            .text()
10550    }
10551
10552    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10553        let mut wrap_guides = smallvec::smallvec![];
10554
10555        if self.show_wrap_guides == Some(false) {
10556            return wrap_guides;
10557        }
10558
10559        let settings = self.buffer.read(cx).settings_at(0, cx);
10560        if settings.show_wrap_guides {
10561            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10562                wrap_guides.push((soft_wrap as usize, true));
10563            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10564                wrap_guides.push((soft_wrap as usize, true));
10565            }
10566            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10567        }
10568
10569        wrap_guides
10570    }
10571
10572    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10573        let settings = self.buffer.read(cx).settings_at(0, cx);
10574        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10575        match mode {
10576            language_settings::SoftWrap::None => SoftWrap::None,
10577            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10578            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10579            language_settings::SoftWrap::PreferredLineLength => {
10580                SoftWrap::Column(settings.preferred_line_length)
10581            }
10582            language_settings::SoftWrap::Bounded => {
10583                SoftWrap::Bounded(settings.preferred_line_length)
10584            }
10585        }
10586    }
10587
10588    pub fn set_soft_wrap_mode(
10589        &mut self,
10590        mode: language_settings::SoftWrap,
10591        cx: &mut ViewContext<Self>,
10592    ) {
10593        self.soft_wrap_mode_override = Some(mode);
10594        cx.notify();
10595    }
10596
10597    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10598        let rem_size = cx.rem_size();
10599        self.display_map.update(cx, |map, cx| {
10600            map.set_font(
10601                style.text.font(),
10602                style.text.font_size.to_pixels(rem_size),
10603                cx,
10604            )
10605        });
10606        self.style = Some(style);
10607    }
10608
10609    pub fn style(&self) -> Option<&EditorStyle> {
10610        self.style.as_ref()
10611    }
10612
10613    // Called by the element. This method is not designed to be called outside of the editor
10614    // element's layout code because it does not notify when rewrapping is computed synchronously.
10615    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10616        self.display_map
10617            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10618    }
10619
10620    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10621        if self.soft_wrap_mode_override.is_some() {
10622            self.soft_wrap_mode_override.take();
10623        } else {
10624            let soft_wrap = match self.soft_wrap_mode(cx) {
10625                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10626                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10627                    language_settings::SoftWrap::PreferLine
10628                }
10629            };
10630            self.soft_wrap_mode_override = Some(soft_wrap);
10631        }
10632        cx.notify();
10633    }
10634
10635    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10636        let Some(workspace) = self.workspace() else {
10637            return;
10638        };
10639        let fs = workspace.read(cx).app_state().fs.clone();
10640        let current_show = TabBarSettings::get_global(cx).show;
10641        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10642            setting.show = Some(!current_show);
10643        });
10644    }
10645
10646    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10647        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10648            self.buffer
10649                .read(cx)
10650                .settings_at(0, cx)
10651                .indent_guides
10652                .enabled
10653        });
10654        self.show_indent_guides = Some(!currently_enabled);
10655        cx.notify();
10656    }
10657
10658    fn should_show_indent_guides(&self) -> Option<bool> {
10659        self.show_indent_guides
10660    }
10661
10662    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10663        let mut editor_settings = EditorSettings::get_global(cx).clone();
10664        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10665        EditorSettings::override_global(editor_settings, cx);
10666    }
10667
10668    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10669        self.use_relative_line_numbers
10670            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10671    }
10672
10673    pub fn toggle_relative_line_numbers(
10674        &mut self,
10675        _: &ToggleRelativeLineNumbers,
10676        cx: &mut ViewContext<Self>,
10677    ) {
10678        let is_relative = self.should_use_relative_line_numbers(cx);
10679        self.set_relative_line_number(Some(!is_relative), cx)
10680    }
10681
10682    pub fn set_relative_line_number(
10683        &mut self,
10684        is_relative: Option<bool>,
10685        cx: &mut ViewContext<Self>,
10686    ) {
10687        self.use_relative_line_numbers = is_relative;
10688        cx.notify();
10689    }
10690
10691    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10692        self.show_gutter = show_gutter;
10693        cx.notify();
10694    }
10695
10696    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10697        self.show_line_numbers = Some(show_line_numbers);
10698        cx.notify();
10699    }
10700
10701    pub fn set_show_git_diff_gutter(
10702        &mut self,
10703        show_git_diff_gutter: bool,
10704        cx: &mut ViewContext<Self>,
10705    ) {
10706        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10707        cx.notify();
10708    }
10709
10710    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10711        self.show_code_actions = Some(show_code_actions);
10712        cx.notify();
10713    }
10714
10715    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10716        self.show_runnables = Some(show_runnables);
10717        cx.notify();
10718    }
10719
10720    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10721        if self.display_map.read(cx).masked != masked {
10722            self.display_map.update(cx, |map, _| map.masked = masked);
10723        }
10724        cx.notify()
10725    }
10726
10727    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10728        self.show_wrap_guides = Some(show_wrap_guides);
10729        cx.notify();
10730    }
10731
10732    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10733        self.show_indent_guides = Some(show_indent_guides);
10734        cx.notify();
10735    }
10736
10737    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10738        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10739            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10740                if let Some(dir) = file.abs_path(cx).parent() {
10741                    return Some(dir.to_owned());
10742                }
10743            }
10744
10745            if let Some(project_path) = buffer.read(cx).project_path(cx) {
10746                return Some(project_path.path.to_path_buf());
10747            }
10748        }
10749
10750        None
10751    }
10752
10753    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10754        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10755            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10756                cx.reveal_path(&file.abs_path(cx));
10757            }
10758        }
10759    }
10760
10761    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10762        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10763            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10764                if let Some(path) = file.abs_path(cx).to_str() {
10765                    cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10766                }
10767            }
10768        }
10769    }
10770
10771    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10772        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10773            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10774                if let Some(path) = file.path().to_str() {
10775                    cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10776                }
10777            }
10778        }
10779    }
10780
10781    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10782        self.show_git_blame_gutter = !self.show_git_blame_gutter;
10783
10784        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10785            self.start_git_blame(true, cx);
10786        }
10787
10788        cx.notify();
10789    }
10790
10791    pub fn toggle_git_blame_inline(
10792        &mut self,
10793        _: &ToggleGitBlameInline,
10794        cx: &mut ViewContext<Self>,
10795    ) {
10796        self.toggle_git_blame_inline_internal(true, cx);
10797        cx.notify();
10798    }
10799
10800    pub fn git_blame_inline_enabled(&self) -> bool {
10801        self.git_blame_inline_enabled
10802    }
10803
10804    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10805        self.show_selection_menu = self
10806            .show_selection_menu
10807            .map(|show_selections_menu| !show_selections_menu)
10808            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10809
10810        cx.notify();
10811    }
10812
10813    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10814        self.show_selection_menu
10815            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10816    }
10817
10818    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10819        if let Some(project) = self.project.as_ref() {
10820            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10821                return;
10822            };
10823
10824            if buffer.read(cx).file().is_none() {
10825                return;
10826            }
10827
10828            let focused = self.focus_handle(cx).contains_focused(cx);
10829
10830            let project = project.clone();
10831            let blame =
10832                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10833            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10834            self.blame = Some(blame);
10835        }
10836    }
10837
10838    fn toggle_git_blame_inline_internal(
10839        &mut self,
10840        user_triggered: bool,
10841        cx: &mut ViewContext<Self>,
10842    ) {
10843        if self.git_blame_inline_enabled {
10844            self.git_blame_inline_enabled = false;
10845            self.show_git_blame_inline = false;
10846            self.show_git_blame_inline_delay_task.take();
10847        } else {
10848            self.git_blame_inline_enabled = true;
10849            self.start_git_blame_inline(user_triggered, cx);
10850        }
10851
10852        cx.notify();
10853    }
10854
10855    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10856        self.start_git_blame(user_triggered, cx);
10857
10858        if ProjectSettings::get_global(cx)
10859            .git
10860            .inline_blame_delay()
10861            .is_some()
10862        {
10863            self.start_inline_blame_timer(cx);
10864        } else {
10865            self.show_git_blame_inline = true
10866        }
10867    }
10868
10869    pub fn blame(&self) -> Option<&Model<GitBlame>> {
10870        self.blame.as_ref()
10871    }
10872
10873    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10874        self.show_git_blame_gutter && self.has_blame_entries(cx)
10875    }
10876
10877    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10878        self.show_git_blame_inline
10879            && self.focus_handle.is_focused(cx)
10880            && !self.newest_selection_head_on_empty_line(cx)
10881            && self.has_blame_entries(cx)
10882    }
10883
10884    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10885        self.blame()
10886            .map_or(false, |blame| blame.read(cx).has_generated_entries())
10887    }
10888
10889    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10890        let cursor_anchor = self.selections.newest_anchor().head();
10891
10892        let snapshot = self.buffer.read(cx).snapshot(cx);
10893        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10894
10895        snapshot.line_len(buffer_row) == 0
10896    }
10897
10898    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10899        let (path, selection, repo) = maybe!({
10900            let project_handle = self.project.as_ref()?.clone();
10901            let project = project_handle.read(cx);
10902
10903            let selection = self.selections.newest::<Point>(cx);
10904            let selection_range = selection.range();
10905
10906            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10907                (buffer, selection_range.start.row..selection_range.end.row)
10908            } else {
10909                let buffer_ranges = self
10910                    .buffer()
10911                    .read(cx)
10912                    .range_to_buffer_ranges(selection_range, cx);
10913
10914                let (buffer, range, _) = if selection.reversed {
10915                    buffer_ranges.first()
10916                } else {
10917                    buffer_ranges.last()
10918                }?;
10919
10920                let snapshot = buffer.read(cx).snapshot();
10921                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10922                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
10923                (buffer.clone(), selection)
10924            };
10925
10926            let path = buffer
10927                .read(cx)
10928                .file()?
10929                .as_local()?
10930                .path()
10931                .to_str()?
10932                .to_string();
10933            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10934            Some((path, selection, repo))
10935        })
10936        .ok_or_else(|| anyhow!("unable to open git repository"))?;
10937
10938        const REMOTE_NAME: &str = "origin";
10939        let origin_url = repo
10940            .remote_url(REMOTE_NAME)
10941            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10942        let sha = repo
10943            .head_sha()
10944            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10945
10946        let (provider, remote) =
10947            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10948                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10949
10950        Ok(provider.build_permalink(
10951            remote,
10952            BuildPermalinkParams {
10953                sha: &sha,
10954                path: &path,
10955                selection: Some(selection),
10956            },
10957        ))
10958    }
10959
10960    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10961        let permalink = self.get_permalink_to_line(cx);
10962
10963        match permalink {
10964            Ok(permalink) => {
10965                cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10966            }
10967            Err(err) => {
10968                let message = format!("Failed to copy permalink: {err}");
10969
10970                Err::<(), anyhow::Error>(err).log_err();
10971
10972                if let Some(workspace) = self.workspace() {
10973                    workspace.update(cx, |workspace, cx| {
10974                        struct CopyPermalinkToLine;
10975
10976                        workspace.show_toast(
10977                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10978                            cx,
10979                        )
10980                    })
10981                }
10982            }
10983        }
10984    }
10985
10986    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
10987        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10988            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10989                if let Some(path) = file.path().to_str() {
10990                    let selection = self.selections.newest::<Point>(cx).start.row + 1;
10991                    cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
10992                }
10993            }
10994        }
10995    }
10996
10997    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10998        let permalink = self.get_permalink_to_line(cx);
10999
11000        match permalink {
11001            Ok(permalink) => {
11002                cx.open_url(permalink.as_ref());
11003            }
11004            Err(err) => {
11005                let message = format!("Failed to open permalink: {err}");
11006
11007                Err::<(), anyhow::Error>(err).log_err();
11008
11009                if let Some(workspace) = self.workspace() {
11010                    workspace.update(cx, |workspace, cx| {
11011                        struct OpenPermalinkToLine;
11012
11013                        workspace.show_toast(
11014                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11015                            cx,
11016                        )
11017                    })
11018                }
11019            }
11020        }
11021    }
11022
11023    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11024    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11025    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11026    pub fn highlight_rows<T: 'static>(
11027        &mut self,
11028        rows: RangeInclusive<Anchor>,
11029        color: Option<Hsla>,
11030        should_autoscroll: bool,
11031        cx: &mut ViewContext<Self>,
11032    ) {
11033        let snapshot = self.buffer().read(cx).snapshot(cx);
11034        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11035        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11036            highlight
11037                .range
11038                .start()
11039                .cmp(rows.start(), &snapshot)
11040                .then(highlight.range.end().cmp(rows.end(), &snapshot))
11041        });
11042        match (color, existing_highlight_index) {
11043            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11044                ix,
11045                RowHighlight {
11046                    index: post_inc(&mut self.highlight_order),
11047                    range: rows,
11048                    should_autoscroll,
11049                    color,
11050                },
11051            ),
11052            (None, Ok(i)) => {
11053                row_highlights.remove(i);
11054            }
11055        }
11056    }
11057
11058    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11059    pub fn clear_row_highlights<T: 'static>(&mut self) {
11060        self.highlighted_rows.remove(&TypeId::of::<T>());
11061    }
11062
11063    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11064    pub fn highlighted_rows<T: 'static>(
11065        &self,
11066    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11067        Some(
11068            self.highlighted_rows
11069                .get(&TypeId::of::<T>())?
11070                .iter()
11071                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11072        )
11073    }
11074
11075    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11076    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11077    /// Allows to ignore certain kinds of highlights.
11078    pub fn highlighted_display_rows(
11079        &mut self,
11080        cx: &mut WindowContext,
11081    ) -> BTreeMap<DisplayRow, Hsla> {
11082        let snapshot = self.snapshot(cx);
11083        let mut used_highlight_orders = HashMap::default();
11084        self.highlighted_rows
11085            .iter()
11086            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11087            .fold(
11088                BTreeMap::<DisplayRow, Hsla>::new(),
11089                |mut unique_rows, highlight| {
11090                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
11091                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
11092                    for row in start_row.0..=end_row.0 {
11093                        let used_index =
11094                            used_highlight_orders.entry(row).or_insert(highlight.index);
11095                        if highlight.index >= *used_index {
11096                            *used_index = highlight.index;
11097                            match highlight.color {
11098                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11099                                None => unique_rows.remove(&DisplayRow(row)),
11100                            };
11101                        }
11102                    }
11103                    unique_rows
11104                },
11105            )
11106    }
11107
11108    pub fn highlighted_display_row_for_autoscroll(
11109        &self,
11110        snapshot: &DisplaySnapshot,
11111    ) -> Option<DisplayRow> {
11112        self.highlighted_rows
11113            .values()
11114            .flat_map(|highlighted_rows| highlighted_rows.iter())
11115            .filter_map(|highlight| {
11116                if highlight.color.is_none() || !highlight.should_autoscroll {
11117                    return None;
11118                }
11119                Some(highlight.range.start().to_display_point(snapshot).row())
11120            })
11121            .min()
11122    }
11123
11124    pub fn set_search_within_ranges(
11125        &mut self,
11126        ranges: &[Range<Anchor>],
11127        cx: &mut ViewContext<Self>,
11128    ) {
11129        self.highlight_background::<SearchWithinRange>(
11130            ranges,
11131            |colors| colors.editor_document_highlight_read_background,
11132            cx,
11133        )
11134    }
11135
11136    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11137        self.breadcrumb_header = Some(new_header);
11138    }
11139
11140    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11141        self.clear_background_highlights::<SearchWithinRange>(cx);
11142    }
11143
11144    pub fn highlight_background<T: 'static>(
11145        &mut self,
11146        ranges: &[Range<Anchor>],
11147        color_fetcher: fn(&ThemeColors) -> Hsla,
11148        cx: &mut ViewContext<Self>,
11149    ) {
11150        self.background_highlights
11151            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11152        self.scrollbar_marker_state.dirty = true;
11153        cx.notify();
11154    }
11155
11156    pub fn clear_background_highlights<T: 'static>(
11157        &mut self,
11158        cx: &mut ViewContext<Self>,
11159    ) -> Option<BackgroundHighlight> {
11160        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11161        if !text_highlights.1.is_empty() {
11162            self.scrollbar_marker_state.dirty = true;
11163            cx.notify();
11164        }
11165        Some(text_highlights)
11166    }
11167
11168    pub fn highlight_gutter<T: 'static>(
11169        &mut self,
11170        ranges: &[Range<Anchor>],
11171        color_fetcher: fn(&AppContext) -> Hsla,
11172        cx: &mut ViewContext<Self>,
11173    ) {
11174        self.gutter_highlights
11175            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11176        cx.notify();
11177    }
11178
11179    pub fn clear_gutter_highlights<T: 'static>(
11180        &mut self,
11181        cx: &mut ViewContext<Self>,
11182    ) -> Option<GutterHighlight> {
11183        cx.notify();
11184        self.gutter_highlights.remove(&TypeId::of::<T>())
11185    }
11186
11187    #[cfg(feature = "test-support")]
11188    pub fn all_text_background_highlights(
11189        &mut self,
11190        cx: &mut ViewContext<Self>,
11191    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11192        let snapshot = self.snapshot(cx);
11193        let buffer = &snapshot.buffer_snapshot;
11194        let start = buffer.anchor_before(0);
11195        let end = buffer.anchor_after(buffer.len());
11196        let theme = cx.theme().colors();
11197        self.background_highlights_in_range(start..end, &snapshot, theme)
11198    }
11199
11200    #[cfg(feature = "test-support")]
11201    pub fn search_background_highlights(
11202        &mut self,
11203        cx: &mut ViewContext<Self>,
11204    ) -> Vec<Range<Point>> {
11205        let snapshot = self.buffer().read(cx).snapshot(cx);
11206
11207        let highlights = self
11208            .background_highlights
11209            .get(&TypeId::of::<items::BufferSearchHighlights>());
11210
11211        if let Some((_color, ranges)) = highlights {
11212            ranges
11213                .iter()
11214                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11215                .collect_vec()
11216        } else {
11217            vec![]
11218        }
11219    }
11220
11221    fn document_highlights_for_position<'a>(
11222        &'a self,
11223        position: Anchor,
11224        buffer: &'a MultiBufferSnapshot,
11225    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11226        let read_highlights = self
11227            .background_highlights
11228            .get(&TypeId::of::<DocumentHighlightRead>())
11229            .map(|h| &h.1);
11230        let write_highlights = self
11231            .background_highlights
11232            .get(&TypeId::of::<DocumentHighlightWrite>())
11233            .map(|h| &h.1);
11234        let left_position = position.bias_left(buffer);
11235        let right_position = position.bias_right(buffer);
11236        read_highlights
11237            .into_iter()
11238            .chain(write_highlights)
11239            .flat_map(move |ranges| {
11240                let start_ix = match ranges.binary_search_by(|probe| {
11241                    let cmp = probe.end.cmp(&left_position, buffer);
11242                    if cmp.is_ge() {
11243                        Ordering::Greater
11244                    } else {
11245                        Ordering::Less
11246                    }
11247                }) {
11248                    Ok(i) | Err(i) => i,
11249                };
11250
11251                ranges[start_ix..]
11252                    .iter()
11253                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11254            })
11255    }
11256
11257    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11258        self.background_highlights
11259            .get(&TypeId::of::<T>())
11260            .map_or(false, |(_, highlights)| !highlights.is_empty())
11261    }
11262
11263    pub fn background_highlights_in_range(
11264        &self,
11265        search_range: Range<Anchor>,
11266        display_snapshot: &DisplaySnapshot,
11267        theme: &ThemeColors,
11268    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11269        let mut results = Vec::new();
11270        for (color_fetcher, ranges) in self.background_highlights.values() {
11271            let color = color_fetcher(theme);
11272            let start_ix = match ranges.binary_search_by(|probe| {
11273                let cmp = probe
11274                    .end
11275                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11276                if cmp.is_gt() {
11277                    Ordering::Greater
11278                } else {
11279                    Ordering::Less
11280                }
11281            }) {
11282                Ok(i) | Err(i) => i,
11283            };
11284            for range in &ranges[start_ix..] {
11285                if range
11286                    .start
11287                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11288                    .is_ge()
11289                {
11290                    break;
11291                }
11292
11293                let start = range.start.to_display_point(display_snapshot);
11294                let end = range.end.to_display_point(display_snapshot);
11295                results.push((start..end, color))
11296            }
11297        }
11298        results
11299    }
11300
11301    pub fn background_highlight_row_ranges<T: 'static>(
11302        &self,
11303        search_range: Range<Anchor>,
11304        display_snapshot: &DisplaySnapshot,
11305        count: usize,
11306    ) -> Vec<RangeInclusive<DisplayPoint>> {
11307        let mut results = Vec::new();
11308        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11309            return vec![];
11310        };
11311
11312        let start_ix = match ranges.binary_search_by(|probe| {
11313            let cmp = probe
11314                .end
11315                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11316            if cmp.is_gt() {
11317                Ordering::Greater
11318            } else {
11319                Ordering::Less
11320            }
11321        }) {
11322            Ok(i) | Err(i) => i,
11323        };
11324        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11325            if let (Some(start_display), Some(end_display)) = (start, end) {
11326                results.push(
11327                    start_display.to_display_point(display_snapshot)
11328                        ..=end_display.to_display_point(display_snapshot),
11329                );
11330            }
11331        };
11332        let mut start_row: Option<Point> = None;
11333        let mut end_row: Option<Point> = None;
11334        if ranges.len() > count {
11335            return Vec::new();
11336        }
11337        for range in &ranges[start_ix..] {
11338            if range
11339                .start
11340                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11341                .is_ge()
11342            {
11343                break;
11344            }
11345            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11346            if let Some(current_row) = &end_row {
11347                if end.row == current_row.row {
11348                    continue;
11349                }
11350            }
11351            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11352            if start_row.is_none() {
11353                assert_eq!(end_row, None);
11354                start_row = Some(start);
11355                end_row = Some(end);
11356                continue;
11357            }
11358            if let Some(current_end) = end_row.as_mut() {
11359                if start.row > current_end.row + 1 {
11360                    push_region(start_row, end_row);
11361                    start_row = Some(start);
11362                    end_row = Some(end);
11363                } else {
11364                    // Merge two hunks.
11365                    *current_end = end;
11366                }
11367            } else {
11368                unreachable!();
11369            }
11370        }
11371        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11372        push_region(start_row, end_row);
11373        results
11374    }
11375
11376    pub fn gutter_highlights_in_range(
11377        &self,
11378        search_range: Range<Anchor>,
11379        display_snapshot: &DisplaySnapshot,
11380        cx: &AppContext,
11381    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11382        let mut results = Vec::new();
11383        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11384            let color = color_fetcher(cx);
11385            let start_ix = match ranges.binary_search_by(|probe| {
11386                let cmp = probe
11387                    .end
11388                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11389                if cmp.is_gt() {
11390                    Ordering::Greater
11391                } else {
11392                    Ordering::Less
11393                }
11394            }) {
11395                Ok(i) | Err(i) => i,
11396            };
11397            for range in &ranges[start_ix..] {
11398                if range
11399                    .start
11400                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11401                    .is_ge()
11402                {
11403                    break;
11404                }
11405
11406                let start = range.start.to_display_point(display_snapshot);
11407                let end = range.end.to_display_point(display_snapshot);
11408                results.push((start..end, color))
11409            }
11410        }
11411        results
11412    }
11413
11414    /// Get the text ranges corresponding to the redaction query
11415    pub fn redacted_ranges(
11416        &self,
11417        search_range: Range<Anchor>,
11418        display_snapshot: &DisplaySnapshot,
11419        cx: &WindowContext,
11420    ) -> Vec<Range<DisplayPoint>> {
11421        display_snapshot
11422            .buffer_snapshot
11423            .redacted_ranges(search_range, |file| {
11424                if let Some(file) = file {
11425                    file.is_private()
11426                        && EditorSettings::get(
11427                            Some(SettingsLocation {
11428                                worktree_id: file.worktree_id(cx),
11429                                path: file.path().as_ref(),
11430                            }),
11431                            cx,
11432                        )
11433                        .redact_private_values
11434                } else {
11435                    false
11436                }
11437            })
11438            .map(|range| {
11439                range.start.to_display_point(display_snapshot)
11440                    ..range.end.to_display_point(display_snapshot)
11441            })
11442            .collect()
11443    }
11444
11445    pub fn highlight_text<T: 'static>(
11446        &mut self,
11447        ranges: Vec<Range<Anchor>>,
11448        style: HighlightStyle,
11449        cx: &mut ViewContext<Self>,
11450    ) {
11451        self.display_map.update(cx, |map, _| {
11452            map.highlight_text(TypeId::of::<T>(), ranges, style)
11453        });
11454        cx.notify();
11455    }
11456
11457    pub(crate) fn highlight_inlays<T: 'static>(
11458        &mut self,
11459        highlights: Vec<InlayHighlight>,
11460        style: HighlightStyle,
11461        cx: &mut ViewContext<Self>,
11462    ) {
11463        self.display_map.update(cx, |map, _| {
11464            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11465        });
11466        cx.notify();
11467    }
11468
11469    pub fn text_highlights<'a, T: 'static>(
11470        &'a self,
11471        cx: &'a AppContext,
11472    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11473        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11474    }
11475
11476    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11477        let cleared = self
11478            .display_map
11479            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11480        if cleared {
11481            cx.notify();
11482        }
11483    }
11484
11485    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11486        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11487            && self.focus_handle.is_focused(cx)
11488    }
11489
11490    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11491        self.show_cursor_when_unfocused = is_enabled;
11492        cx.notify();
11493    }
11494
11495    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11496        cx.notify();
11497    }
11498
11499    fn on_buffer_event(
11500        &mut self,
11501        multibuffer: Model<MultiBuffer>,
11502        event: &multi_buffer::Event,
11503        cx: &mut ViewContext<Self>,
11504    ) {
11505        match event {
11506            multi_buffer::Event::Edited {
11507                singleton_buffer_edited,
11508            } => {
11509                self.scrollbar_marker_state.dirty = true;
11510                self.active_indent_guides_state.dirty = true;
11511                self.refresh_active_diagnostics(cx);
11512                self.refresh_code_actions(cx);
11513                if self.has_active_inline_completion(cx) {
11514                    self.update_visible_inline_completion(cx);
11515                }
11516                cx.emit(EditorEvent::BufferEdited);
11517                cx.emit(SearchEvent::MatchesInvalidated);
11518                if *singleton_buffer_edited {
11519                    if let Some(project) = &self.project {
11520                        let project = project.read(cx);
11521                        #[allow(clippy::mutable_key_type)]
11522                        let languages_affected = multibuffer
11523                            .read(cx)
11524                            .all_buffers()
11525                            .into_iter()
11526                            .filter_map(|buffer| {
11527                                let buffer = buffer.read(cx);
11528                                let language = buffer.language()?;
11529                                if project.is_local_or_ssh()
11530                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
11531                                {
11532                                    None
11533                                } else {
11534                                    Some(language)
11535                                }
11536                            })
11537                            .cloned()
11538                            .collect::<HashSet<_>>();
11539                        if !languages_affected.is_empty() {
11540                            self.refresh_inlay_hints(
11541                                InlayHintRefreshReason::BufferEdited(languages_affected),
11542                                cx,
11543                            );
11544                        }
11545                    }
11546                }
11547
11548                let Some(project) = &self.project else { return };
11549                let telemetry = project.read(cx).client().telemetry().clone();
11550                refresh_linked_ranges(self, cx);
11551                telemetry.log_edit_event("editor");
11552            }
11553            multi_buffer::Event::ExcerptsAdded {
11554                buffer,
11555                predecessor,
11556                excerpts,
11557            } => {
11558                self.tasks_update_task = Some(self.refresh_runnables(cx));
11559                cx.emit(EditorEvent::ExcerptsAdded {
11560                    buffer: buffer.clone(),
11561                    predecessor: *predecessor,
11562                    excerpts: excerpts.clone(),
11563                });
11564                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11565            }
11566            multi_buffer::Event::ExcerptsRemoved { ids } => {
11567                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11568                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11569            }
11570            multi_buffer::Event::ExcerptsEdited { ids } => {
11571                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11572            }
11573            multi_buffer::Event::ExcerptsExpanded { ids } => {
11574                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11575            }
11576            multi_buffer::Event::Reparsed(buffer_id) => {
11577                self.tasks_update_task = Some(self.refresh_runnables(cx));
11578
11579                cx.emit(EditorEvent::Reparsed(*buffer_id));
11580            }
11581            multi_buffer::Event::LanguageChanged(buffer_id) => {
11582                linked_editing_ranges::refresh_linked_ranges(self, cx);
11583                cx.emit(EditorEvent::Reparsed(*buffer_id));
11584                cx.notify();
11585            }
11586            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11587            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11588            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11589                cx.emit(EditorEvent::TitleChanged)
11590            }
11591            multi_buffer::Event::DiffBaseChanged => {
11592                self.scrollbar_marker_state.dirty = true;
11593                cx.emit(EditorEvent::DiffBaseChanged);
11594                cx.notify();
11595            }
11596            multi_buffer::Event::DiffUpdated { buffer } => {
11597                self.sync_expanded_diff_hunks(buffer.clone(), cx);
11598                cx.notify();
11599            }
11600            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11601            multi_buffer::Event::DiagnosticsUpdated => {
11602                self.refresh_active_diagnostics(cx);
11603                self.scrollbar_marker_state.dirty = true;
11604                cx.notify();
11605            }
11606            _ => {}
11607        };
11608    }
11609
11610    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11611        cx.notify();
11612    }
11613
11614    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11615        self.tasks_update_task = Some(self.refresh_runnables(cx));
11616        self.refresh_inline_completion(true, false, cx);
11617        self.refresh_inlay_hints(
11618            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11619                self.selections.newest_anchor().head(),
11620                &self.buffer.read(cx).snapshot(cx),
11621                cx,
11622            )),
11623            cx,
11624        );
11625        let editor_settings = EditorSettings::get_global(cx);
11626        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11627        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11628
11629        let project_settings = ProjectSettings::get_global(cx);
11630        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11631
11632        if self.mode == EditorMode::Full {
11633            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11634            if self.git_blame_inline_enabled != inline_blame_enabled {
11635                self.toggle_git_blame_inline_internal(false, cx);
11636            }
11637        }
11638
11639        cx.notify();
11640    }
11641
11642    pub fn set_searchable(&mut self, searchable: bool) {
11643        self.searchable = searchable;
11644    }
11645
11646    pub fn searchable(&self) -> bool {
11647        self.searchable
11648    }
11649
11650    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11651        self.open_excerpts_common(true, cx)
11652    }
11653
11654    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11655        self.open_excerpts_common(false, cx)
11656    }
11657
11658    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11659        let buffer = self.buffer.read(cx);
11660        if buffer.is_singleton() {
11661            cx.propagate();
11662            return;
11663        }
11664
11665        let Some(workspace) = self.workspace() else {
11666            cx.propagate();
11667            return;
11668        };
11669
11670        let mut new_selections_by_buffer = HashMap::default();
11671        for selection in self.selections.all::<usize>(cx) {
11672            for (buffer, mut range, _) in
11673                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11674            {
11675                if selection.reversed {
11676                    mem::swap(&mut range.start, &mut range.end);
11677                }
11678                new_selections_by_buffer
11679                    .entry(buffer)
11680                    .or_insert(Vec::new())
11681                    .push(range)
11682            }
11683        }
11684
11685        // We defer the pane interaction because we ourselves are a workspace item
11686        // and activating a new item causes the pane to call a method on us reentrantly,
11687        // which panics if we're on the stack.
11688        cx.window_context().defer(move |cx| {
11689            workspace.update(cx, |workspace, cx| {
11690                let pane = if split {
11691                    workspace.adjacent_pane(cx)
11692                } else {
11693                    workspace.active_pane().clone()
11694                };
11695
11696                for (buffer, ranges) in new_selections_by_buffer {
11697                    let editor =
11698                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11699                    editor.update(cx, |editor, cx| {
11700                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11701                            s.select_ranges(ranges);
11702                        });
11703                    });
11704                }
11705            })
11706        });
11707    }
11708
11709    fn jump(
11710        &mut self,
11711        path: ProjectPath,
11712        position: Point,
11713        anchor: language::Anchor,
11714        offset_from_top: u32,
11715        cx: &mut ViewContext<Self>,
11716    ) {
11717        let workspace = self.workspace();
11718        cx.spawn(|_, mut cx| async move {
11719            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11720            let editor = workspace.update(&mut cx, |workspace, cx| {
11721                // Reset the preview item id before opening the new item
11722                workspace.active_pane().update(cx, |pane, cx| {
11723                    pane.set_preview_item_id(None, cx);
11724                });
11725                workspace.open_path_preview(path, None, true, true, cx)
11726            })?;
11727            let editor = editor
11728                .await?
11729                .downcast::<Editor>()
11730                .ok_or_else(|| anyhow!("opened item was not an editor"))?
11731                .downgrade();
11732            editor.update(&mut cx, |editor, cx| {
11733                let buffer = editor
11734                    .buffer()
11735                    .read(cx)
11736                    .as_singleton()
11737                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11738                let buffer = buffer.read(cx);
11739                let cursor = if buffer.can_resolve(&anchor) {
11740                    language::ToPoint::to_point(&anchor, buffer)
11741                } else {
11742                    buffer.clip_point(position, Bias::Left)
11743                };
11744
11745                let nav_history = editor.nav_history.take();
11746                editor.change_selections(
11747                    Some(Autoscroll::top_relative(offset_from_top as usize)),
11748                    cx,
11749                    |s| {
11750                        s.select_ranges([cursor..cursor]);
11751                    },
11752                );
11753                editor.nav_history = nav_history;
11754
11755                anyhow::Ok(())
11756            })??;
11757
11758            anyhow::Ok(())
11759        })
11760        .detach_and_log_err(cx);
11761    }
11762
11763    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11764        let snapshot = self.buffer.read(cx).read(cx);
11765        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11766        Some(
11767            ranges
11768                .iter()
11769                .map(move |range| {
11770                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11771                })
11772                .collect(),
11773        )
11774    }
11775
11776    fn selection_replacement_ranges(
11777        &self,
11778        range: Range<OffsetUtf16>,
11779        cx: &AppContext,
11780    ) -> Vec<Range<OffsetUtf16>> {
11781        let selections = self.selections.all::<OffsetUtf16>(cx);
11782        let newest_selection = selections
11783            .iter()
11784            .max_by_key(|selection| selection.id)
11785            .unwrap();
11786        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11787        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11788        let snapshot = self.buffer.read(cx).read(cx);
11789        selections
11790            .into_iter()
11791            .map(|mut selection| {
11792                selection.start.0 =
11793                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
11794                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11795                snapshot.clip_offset_utf16(selection.start, Bias::Left)
11796                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11797            })
11798            .collect()
11799    }
11800
11801    fn report_editor_event(
11802        &self,
11803        operation: &'static str,
11804        file_extension: Option<String>,
11805        cx: &AppContext,
11806    ) {
11807        if cfg!(any(test, feature = "test-support")) {
11808            return;
11809        }
11810
11811        let Some(project) = &self.project else { return };
11812
11813        // If None, we are in a file without an extension
11814        let file = self
11815            .buffer
11816            .read(cx)
11817            .as_singleton()
11818            .and_then(|b| b.read(cx).file());
11819        let file_extension = file_extension.or(file
11820            .as_ref()
11821            .and_then(|file| Path::new(file.file_name(cx)).extension())
11822            .and_then(|e| e.to_str())
11823            .map(|a| a.to_string()));
11824
11825        let vim_mode = cx
11826            .global::<SettingsStore>()
11827            .raw_user_settings()
11828            .get("vim_mode")
11829            == Some(&serde_json::Value::Bool(true));
11830
11831        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11832            == language::language_settings::InlineCompletionProvider::Copilot;
11833        let copilot_enabled_for_language = self
11834            .buffer
11835            .read(cx)
11836            .settings_at(0, cx)
11837            .show_inline_completions;
11838
11839        let telemetry = project.read(cx).client().telemetry().clone();
11840        telemetry.report_editor_event(
11841            file_extension,
11842            vim_mode,
11843            operation,
11844            copilot_enabled,
11845            copilot_enabled_for_language,
11846        )
11847    }
11848
11849    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11850    /// with each line being an array of {text, highlight} objects.
11851    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11852        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11853            return;
11854        };
11855
11856        #[derive(Serialize)]
11857        struct Chunk<'a> {
11858            text: String,
11859            highlight: Option<&'a str>,
11860        }
11861
11862        let snapshot = buffer.read(cx).snapshot();
11863        let range = self
11864            .selected_text_range(false, cx)
11865            .and_then(|selection| {
11866                if selection.range.is_empty() {
11867                    None
11868                } else {
11869                    Some(selection.range)
11870                }
11871            })
11872            .unwrap_or_else(|| 0..snapshot.len());
11873
11874        let chunks = snapshot.chunks(range, true);
11875        let mut lines = Vec::new();
11876        let mut line: VecDeque<Chunk> = VecDeque::new();
11877
11878        let Some(style) = self.style.as_ref() else {
11879            return;
11880        };
11881
11882        for chunk in chunks {
11883            let highlight = chunk
11884                .syntax_highlight_id
11885                .and_then(|id| id.name(&style.syntax));
11886            let mut chunk_lines = chunk.text.split('\n').peekable();
11887            while let Some(text) = chunk_lines.next() {
11888                let mut merged_with_last_token = false;
11889                if let Some(last_token) = line.back_mut() {
11890                    if last_token.highlight == highlight {
11891                        last_token.text.push_str(text);
11892                        merged_with_last_token = true;
11893                    }
11894                }
11895
11896                if !merged_with_last_token {
11897                    line.push_back(Chunk {
11898                        text: text.into(),
11899                        highlight,
11900                    });
11901                }
11902
11903                if chunk_lines.peek().is_some() {
11904                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
11905                        line.pop_front();
11906                    }
11907                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
11908                        line.pop_back();
11909                    }
11910
11911                    lines.push(mem::take(&mut line));
11912                }
11913            }
11914        }
11915
11916        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11917            return;
11918        };
11919        cx.write_to_clipboard(ClipboardItem::new_string(lines));
11920    }
11921
11922    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11923        &self.inlay_hint_cache
11924    }
11925
11926    pub fn replay_insert_event(
11927        &mut self,
11928        text: &str,
11929        relative_utf16_range: Option<Range<isize>>,
11930        cx: &mut ViewContext<Self>,
11931    ) {
11932        if !self.input_enabled {
11933            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11934            return;
11935        }
11936        if let Some(relative_utf16_range) = relative_utf16_range {
11937            let selections = self.selections.all::<OffsetUtf16>(cx);
11938            self.change_selections(None, cx, |s| {
11939                let new_ranges = selections.into_iter().map(|range| {
11940                    let start = OffsetUtf16(
11941                        range
11942                            .head()
11943                            .0
11944                            .saturating_add_signed(relative_utf16_range.start),
11945                    );
11946                    let end = OffsetUtf16(
11947                        range
11948                            .head()
11949                            .0
11950                            .saturating_add_signed(relative_utf16_range.end),
11951                    );
11952                    start..end
11953                });
11954                s.select_ranges(new_ranges);
11955            });
11956        }
11957
11958        self.handle_input(text, cx);
11959    }
11960
11961    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11962        let Some(project) = self.project.as_ref() else {
11963            return false;
11964        };
11965        let project = project.read(cx);
11966
11967        let mut supports = false;
11968        self.buffer().read(cx).for_each_buffer(|buffer| {
11969            if !supports {
11970                supports = project
11971                    .language_servers_for_buffer(buffer.read(cx), cx)
11972                    .any(
11973                        |(_, server)| match server.capabilities().inlay_hint_provider {
11974                            Some(lsp::OneOf::Left(enabled)) => enabled,
11975                            Some(lsp::OneOf::Right(_)) => true,
11976                            None => false,
11977                        },
11978                    )
11979            }
11980        });
11981        supports
11982    }
11983
11984    pub fn focus(&self, cx: &mut WindowContext) {
11985        cx.focus(&self.focus_handle)
11986    }
11987
11988    pub fn is_focused(&self, cx: &WindowContext) -> bool {
11989        self.focus_handle.is_focused(cx)
11990    }
11991
11992    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11993        cx.emit(EditorEvent::Focused);
11994
11995        if let Some(descendant) = self
11996            .last_focused_descendant
11997            .take()
11998            .and_then(|descendant| descendant.upgrade())
11999        {
12000            cx.focus(&descendant);
12001        } else {
12002            if let Some(blame) = self.blame.as_ref() {
12003                blame.update(cx, GitBlame::focus)
12004            }
12005
12006            self.blink_manager.update(cx, BlinkManager::enable);
12007            self.show_cursor_names(cx);
12008            self.buffer.update(cx, |buffer, cx| {
12009                buffer.finalize_last_transaction(cx);
12010                if self.leader_peer_id.is_none() {
12011                    buffer.set_active_selections(
12012                        &self.selections.disjoint_anchors(),
12013                        self.selections.line_mode,
12014                        self.cursor_shape,
12015                        cx,
12016                    );
12017                }
12018            });
12019        }
12020    }
12021
12022    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12023        cx.emit(EditorEvent::FocusedIn)
12024    }
12025
12026    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12027        if event.blurred != self.focus_handle {
12028            self.last_focused_descendant = Some(event.blurred);
12029        }
12030    }
12031
12032    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12033        self.blink_manager.update(cx, BlinkManager::disable);
12034        self.buffer
12035            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12036
12037        if let Some(blame) = self.blame.as_ref() {
12038            blame.update(cx, GitBlame::blur)
12039        }
12040        if !self.hover_state.focused(cx) {
12041            hide_hover(self, cx);
12042        }
12043
12044        self.hide_context_menu(cx);
12045        cx.emit(EditorEvent::Blurred);
12046        cx.notify();
12047    }
12048
12049    pub fn register_action<A: Action>(
12050        &mut self,
12051        listener: impl Fn(&A, &mut WindowContext) + 'static,
12052    ) -> Subscription {
12053        let id = self.next_editor_action_id.post_inc();
12054        let listener = Arc::new(listener);
12055        self.editor_actions.borrow_mut().insert(
12056            id,
12057            Box::new(move |cx| {
12058                let cx = cx.window_context();
12059                let listener = listener.clone();
12060                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12061                    let action = action.downcast_ref().unwrap();
12062                    if phase == DispatchPhase::Bubble {
12063                        listener(action, cx)
12064                    }
12065                })
12066            }),
12067        );
12068
12069        let editor_actions = self.editor_actions.clone();
12070        Subscription::new(move || {
12071            editor_actions.borrow_mut().remove(&id);
12072        })
12073    }
12074
12075    pub fn file_header_size(&self) -> u32 {
12076        self.file_header_size
12077    }
12078
12079    pub fn revert(
12080        &mut self,
12081        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12082        cx: &mut ViewContext<Self>,
12083    ) {
12084        self.buffer().update(cx, |multi_buffer, cx| {
12085            for (buffer_id, changes) in revert_changes {
12086                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12087                    buffer.update(cx, |buffer, cx| {
12088                        buffer.edit(
12089                            changes.into_iter().map(|(range, text)| {
12090                                (range, text.to_string().map(Arc::<str>::from))
12091                            }),
12092                            None,
12093                            cx,
12094                        );
12095                    });
12096                }
12097            }
12098        });
12099        self.change_selections(None, cx, |selections| selections.refresh());
12100    }
12101
12102    pub fn to_pixel_point(
12103        &mut self,
12104        source: multi_buffer::Anchor,
12105        editor_snapshot: &EditorSnapshot,
12106        cx: &mut ViewContext<Self>,
12107    ) -> Option<gpui::Point<Pixels>> {
12108        let source_point = source.to_display_point(editor_snapshot);
12109        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12110    }
12111
12112    pub fn display_to_pixel_point(
12113        &mut self,
12114        source: DisplayPoint,
12115        editor_snapshot: &EditorSnapshot,
12116        cx: &mut ViewContext<Self>,
12117    ) -> Option<gpui::Point<Pixels>> {
12118        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12119        let text_layout_details = self.text_layout_details(cx);
12120        let scroll_top = text_layout_details
12121            .scroll_anchor
12122            .scroll_position(editor_snapshot)
12123            .y;
12124
12125        if source.row().as_f32() < scroll_top.floor() {
12126            return None;
12127        }
12128        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12129        let source_y = line_height * (source.row().as_f32() - scroll_top);
12130        Some(gpui::Point::new(source_x, source_y))
12131    }
12132
12133    fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12134        let bounds = self.last_bounds?;
12135        Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12136    }
12137
12138    pub fn has_active_completions_menu(&self) -> bool {
12139        self.context_menu.read().as_ref().map_or(false, |menu| {
12140            menu.visible() && matches!(menu, ContextMenu::Completions(_))
12141        })
12142    }
12143
12144    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12145        self.addons
12146            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12147    }
12148
12149    pub fn unregister_addon<T: Addon>(&mut self) {
12150        self.addons.remove(&std::any::TypeId::of::<T>());
12151    }
12152
12153    pub fn addon<T: Addon>(&self) -> Option<&T> {
12154        let type_id = std::any::TypeId::of::<T>();
12155        self.addons
12156            .get(&type_id)
12157            .and_then(|item| item.to_any().downcast_ref::<T>())
12158    }
12159}
12160
12161fn hunks_for_selections(
12162    multi_buffer_snapshot: &MultiBufferSnapshot,
12163    selections: &[Selection<Anchor>],
12164) -> Vec<DiffHunk<MultiBufferRow>> {
12165    let buffer_rows_for_selections = selections.iter().map(|selection| {
12166        let head = selection.head();
12167        let tail = selection.tail();
12168        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12169        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12170        if start > end {
12171            end..start
12172        } else {
12173            start..end
12174        }
12175    });
12176
12177    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12178}
12179
12180pub fn hunks_for_rows(
12181    rows: impl Iterator<Item = Range<MultiBufferRow>>,
12182    multi_buffer_snapshot: &MultiBufferSnapshot,
12183) -> Vec<DiffHunk<MultiBufferRow>> {
12184    let mut hunks = Vec::new();
12185    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12186        HashMap::default();
12187    for selected_multi_buffer_rows in rows {
12188        let query_rows =
12189            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12190        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12191            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12192            // when the caret is just above or just below the deleted hunk.
12193            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12194            let related_to_selection = if allow_adjacent {
12195                hunk.associated_range.overlaps(&query_rows)
12196                    || hunk.associated_range.start == query_rows.end
12197                    || hunk.associated_range.end == query_rows.start
12198            } else {
12199                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12200                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12201                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12202                    || selected_multi_buffer_rows.end == hunk.associated_range.start
12203            };
12204            if related_to_selection {
12205                if !processed_buffer_rows
12206                    .entry(hunk.buffer_id)
12207                    .or_default()
12208                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12209                {
12210                    continue;
12211                }
12212                hunks.push(hunk);
12213            }
12214        }
12215    }
12216
12217    hunks
12218}
12219
12220pub trait CollaborationHub {
12221    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12222    fn user_participant_indices<'a>(
12223        &self,
12224        cx: &'a AppContext,
12225    ) -> &'a HashMap<u64, ParticipantIndex>;
12226    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12227}
12228
12229impl CollaborationHub for Model<Project> {
12230    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12231        self.read(cx).collaborators()
12232    }
12233
12234    fn user_participant_indices<'a>(
12235        &self,
12236        cx: &'a AppContext,
12237    ) -> &'a HashMap<u64, ParticipantIndex> {
12238        self.read(cx).user_store().read(cx).participant_indices()
12239    }
12240
12241    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12242        let this = self.read(cx);
12243        let user_ids = this.collaborators().values().map(|c| c.user_id);
12244        this.user_store().read_with(cx, |user_store, cx| {
12245            user_store.participant_names(user_ids, cx)
12246        })
12247    }
12248}
12249
12250pub trait CompletionProvider {
12251    fn completions(
12252        &self,
12253        buffer: &Model<Buffer>,
12254        buffer_position: text::Anchor,
12255        trigger: CompletionContext,
12256        cx: &mut ViewContext<Editor>,
12257    ) -> Task<Result<Vec<Completion>>>;
12258
12259    fn resolve_completions(
12260        &self,
12261        buffer: Model<Buffer>,
12262        completion_indices: Vec<usize>,
12263        completions: Arc<RwLock<Box<[Completion]>>>,
12264        cx: &mut ViewContext<Editor>,
12265    ) -> Task<Result<bool>>;
12266
12267    fn apply_additional_edits_for_completion(
12268        &self,
12269        buffer: Model<Buffer>,
12270        completion: Completion,
12271        push_to_history: bool,
12272        cx: &mut ViewContext<Editor>,
12273    ) -> Task<Result<Option<language::Transaction>>>;
12274
12275    fn is_completion_trigger(
12276        &self,
12277        buffer: &Model<Buffer>,
12278        position: language::Anchor,
12279        text: &str,
12280        trigger_in_words: bool,
12281        cx: &mut ViewContext<Editor>,
12282    ) -> bool;
12283
12284    fn sort_completions(&self) -> bool {
12285        true
12286    }
12287}
12288
12289fn snippet_completions(
12290    project: &Project,
12291    buffer: &Model<Buffer>,
12292    buffer_position: text::Anchor,
12293    cx: &mut AppContext,
12294) -> Vec<Completion> {
12295    let language = buffer.read(cx).language_at(buffer_position);
12296    let language_name = language.as_ref().map(|language| language.lsp_id());
12297    let snippet_store = project.snippets().read(cx);
12298    let snippets = snippet_store.snippets_for(language_name, cx);
12299
12300    if snippets.is_empty() {
12301        return vec![];
12302    }
12303    let snapshot = buffer.read(cx).text_snapshot();
12304    let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12305
12306    let mut lines = chunks.lines();
12307    let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12308        return vec![];
12309    };
12310
12311    let scope = language.map(|language| language.default_scope());
12312    let classifier = CharClassifier::new(scope).for_completion(true);
12313    let mut last_word = line_at
12314        .chars()
12315        .rev()
12316        .take_while(|c| classifier.is_word(*c))
12317        .collect::<String>();
12318    last_word = last_word.chars().rev().collect();
12319    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12320    let to_lsp = |point: &text::Anchor| {
12321        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12322        point_to_lsp(end)
12323    };
12324    let lsp_end = to_lsp(&buffer_position);
12325    snippets
12326        .into_iter()
12327        .filter_map(|snippet| {
12328            let matching_prefix = snippet
12329                .prefix
12330                .iter()
12331                .find(|prefix| prefix.starts_with(&last_word))?;
12332            let start = as_offset - last_word.len();
12333            let start = snapshot.anchor_before(start);
12334            let range = start..buffer_position;
12335            let lsp_start = to_lsp(&start);
12336            let lsp_range = lsp::Range {
12337                start: lsp_start,
12338                end: lsp_end,
12339            };
12340            Some(Completion {
12341                old_range: range,
12342                new_text: snippet.body.clone(),
12343                label: CodeLabel {
12344                    text: matching_prefix.clone(),
12345                    runs: vec![],
12346                    filter_range: 0..matching_prefix.len(),
12347                },
12348                server_id: LanguageServerId(usize::MAX),
12349                documentation: snippet.description.clone().map(Documentation::SingleLine),
12350                lsp_completion: lsp::CompletionItem {
12351                    label: snippet.prefix.first().unwrap().clone(),
12352                    kind: Some(CompletionItemKind::SNIPPET),
12353                    label_details: snippet.description.as_ref().map(|description| {
12354                        lsp::CompletionItemLabelDetails {
12355                            detail: Some(description.clone()),
12356                            description: None,
12357                        }
12358                    }),
12359                    insert_text_format: Some(InsertTextFormat::SNIPPET),
12360                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12361                        lsp::InsertReplaceEdit {
12362                            new_text: snippet.body.clone(),
12363                            insert: lsp_range,
12364                            replace: lsp_range,
12365                        },
12366                    )),
12367                    filter_text: Some(snippet.body.clone()),
12368                    sort_text: Some(char::MAX.to_string()),
12369                    ..Default::default()
12370                },
12371                confirm: None,
12372            })
12373        })
12374        .collect()
12375}
12376
12377impl CompletionProvider for Model<Project> {
12378    fn completions(
12379        &self,
12380        buffer: &Model<Buffer>,
12381        buffer_position: text::Anchor,
12382        options: CompletionContext,
12383        cx: &mut ViewContext<Editor>,
12384    ) -> Task<Result<Vec<Completion>>> {
12385        self.update(cx, |project, cx| {
12386            let snippets = snippet_completions(project, buffer, buffer_position, cx);
12387            let project_completions = project.completions(buffer, buffer_position, options, cx);
12388            cx.background_executor().spawn(async move {
12389                let mut completions = project_completions.await?;
12390                //let snippets = snippets.into_iter().;
12391                completions.extend(snippets);
12392                Ok(completions)
12393            })
12394        })
12395    }
12396
12397    fn resolve_completions(
12398        &self,
12399        buffer: Model<Buffer>,
12400        completion_indices: Vec<usize>,
12401        completions: Arc<RwLock<Box<[Completion]>>>,
12402        cx: &mut ViewContext<Editor>,
12403    ) -> Task<Result<bool>> {
12404        self.update(cx, |project, cx| {
12405            project.resolve_completions(buffer, completion_indices, completions, cx)
12406        })
12407    }
12408
12409    fn apply_additional_edits_for_completion(
12410        &self,
12411        buffer: Model<Buffer>,
12412        completion: Completion,
12413        push_to_history: bool,
12414        cx: &mut ViewContext<Editor>,
12415    ) -> Task<Result<Option<language::Transaction>>> {
12416        self.update(cx, |project, cx| {
12417            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12418        })
12419    }
12420
12421    fn is_completion_trigger(
12422        &self,
12423        buffer: &Model<Buffer>,
12424        position: language::Anchor,
12425        text: &str,
12426        trigger_in_words: bool,
12427        cx: &mut ViewContext<Editor>,
12428    ) -> bool {
12429        if !EditorSettings::get_global(cx).show_completions_on_input {
12430            return false;
12431        }
12432
12433        let mut chars = text.chars();
12434        let char = if let Some(char) = chars.next() {
12435            char
12436        } else {
12437            return false;
12438        };
12439        if chars.next().is_some() {
12440            return false;
12441        }
12442
12443        let buffer = buffer.read(cx);
12444        let classifier = buffer
12445            .snapshot()
12446            .char_classifier_at(position)
12447            .for_completion(true);
12448        if trigger_in_words && classifier.is_word(char) {
12449            return true;
12450        }
12451
12452        buffer
12453            .completion_triggers()
12454            .iter()
12455            .any(|string| string == text)
12456    }
12457}
12458
12459fn inlay_hint_settings(
12460    location: Anchor,
12461    snapshot: &MultiBufferSnapshot,
12462    cx: &mut ViewContext<'_, Editor>,
12463) -> InlayHintSettings {
12464    let file = snapshot.file_at(location);
12465    let language = snapshot.language_at(location);
12466    let settings = all_language_settings(file, cx);
12467    settings
12468        .language(language.map(|l| l.name()).as_deref())
12469        .inlay_hints
12470}
12471
12472fn consume_contiguous_rows(
12473    contiguous_row_selections: &mut Vec<Selection<Point>>,
12474    selection: &Selection<Point>,
12475    display_map: &DisplaySnapshot,
12476    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12477) -> (MultiBufferRow, MultiBufferRow) {
12478    contiguous_row_selections.push(selection.clone());
12479    let start_row = MultiBufferRow(selection.start.row);
12480    let mut end_row = ending_row(selection, display_map);
12481
12482    while let Some(next_selection) = selections.peek() {
12483        if next_selection.start.row <= end_row.0 {
12484            end_row = ending_row(next_selection, display_map);
12485            contiguous_row_selections.push(selections.next().unwrap().clone());
12486        } else {
12487            break;
12488        }
12489    }
12490    (start_row, end_row)
12491}
12492
12493fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12494    if next_selection.end.column > 0 || next_selection.is_empty() {
12495        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12496    } else {
12497        MultiBufferRow(next_selection.end.row)
12498    }
12499}
12500
12501impl EditorSnapshot {
12502    pub fn remote_selections_in_range<'a>(
12503        &'a self,
12504        range: &'a Range<Anchor>,
12505        collaboration_hub: &dyn CollaborationHub,
12506        cx: &'a AppContext,
12507    ) -> impl 'a + Iterator<Item = RemoteSelection> {
12508        let participant_names = collaboration_hub.user_names(cx);
12509        let participant_indices = collaboration_hub.user_participant_indices(cx);
12510        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12511        let collaborators_by_replica_id = collaborators_by_peer_id
12512            .iter()
12513            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12514            .collect::<HashMap<_, _>>();
12515        self.buffer_snapshot
12516            .selections_in_range(range, false)
12517            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12518                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12519                let participant_index = participant_indices.get(&collaborator.user_id).copied();
12520                let user_name = participant_names.get(&collaborator.user_id).cloned();
12521                Some(RemoteSelection {
12522                    replica_id,
12523                    selection,
12524                    cursor_shape,
12525                    line_mode,
12526                    participant_index,
12527                    peer_id: collaborator.peer_id,
12528                    user_name,
12529                })
12530            })
12531    }
12532
12533    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12534        self.display_snapshot.buffer_snapshot.language_at(position)
12535    }
12536
12537    pub fn is_focused(&self) -> bool {
12538        self.is_focused
12539    }
12540
12541    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12542        self.placeholder_text.as_ref()
12543    }
12544
12545    pub fn scroll_position(&self) -> gpui::Point<f32> {
12546        self.scroll_anchor.scroll_position(&self.display_snapshot)
12547    }
12548
12549    fn gutter_dimensions(
12550        &self,
12551        font_id: FontId,
12552        font_size: Pixels,
12553        em_width: Pixels,
12554        max_line_number_width: Pixels,
12555        cx: &AppContext,
12556    ) -> GutterDimensions {
12557        if !self.show_gutter {
12558            return GutterDimensions::default();
12559        }
12560        let descent = cx.text_system().descent(font_id, font_size);
12561
12562        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12563            matches!(
12564                ProjectSettings::get_global(cx).git.git_gutter,
12565                Some(GitGutterSetting::TrackedFiles)
12566            )
12567        });
12568        let gutter_settings = EditorSettings::get_global(cx).gutter;
12569        let show_line_numbers = self
12570            .show_line_numbers
12571            .unwrap_or(gutter_settings.line_numbers);
12572        let line_gutter_width = if show_line_numbers {
12573            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12574            let min_width_for_number_on_gutter = em_width * 4.0;
12575            max_line_number_width.max(min_width_for_number_on_gutter)
12576        } else {
12577            0.0.into()
12578        };
12579
12580        let show_code_actions = self
12581            .show_code_actions
12582            .unwrap_or(gutter_settings.code_actions);
12583
12584        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12585
12586        let git_blame_entries_width = self
12587            .render_git_blame_gutter
12588            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12589
12590        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12591        left_padding += if show_code_actions || show_runnables {
12592            em_width * 3.0
12593        } else if show_git_gutter && show_line_numbers {
12594            em_width * 2.0
12595        } else if show_git_gutter || show_line_numbers {
12596            em_width
12597        } else {
12598            px(0.)
12599        };
12600
12601        let right_padding = if gutter_settings.folds && show_line_numbers {
12602            em_width * 4.0
12603        } else if gutter_settings.folds {
12604            em_width * 3.0
12605        } else if show_line_numbers {
12606            em_width
12607        } else {
12608            px(0.)
12609        };
12610
12611        GutterDimensions {
12612            left_padding,
12613            right_padding,
12614            width: line_gutter_width + left_padding + right_padding,
12615            margin: -descent,
12616            git_blame_entries_width,
12617        }
12618    }
12619
12620    pub fn render_fold_toggle(
12621        &self,
12622        buffer_row: MultiBufferRow,
12623        row_contains_cursor: bool,
12624        editor: View<Editor>,
12625        cx: &mut WindowContext,
12626    ) -> Option<AnyElement> {
12627        let folded = self.is_line_folded(buffer_row);
12628
12629        if let Some(crease) = self
12630            .crease_snapshot
12631            .query_row(buffer_row, &self.buffer_snapshot)
12632        {
12633            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12634                if folded {
12635                    editor.update(cx, |editor, cx| {
12636                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12637                    });
12638                } else {
12639                    editor.update(cx, |editor, cx| {
12640                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12641                    });
12642                }
12643            });
12644
12645            Some((crease.render_toggle)(
12646                buffer_row,
12647                folded,
12648                toggle_callback,
12649                cx,
12650            ))
12651        } else if folded
12652            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12653        {
12654            Some(
12655                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12656                    .selected(folded)
12657                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12658                        if folded {
12659                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
12660                        } else {
12661                            this.fold_at(&FoldAt { buffer_row }, cx);
12662                        }
12663                    }))
12664                    .into_any_element(),
12665            )
12666        } else {
12667            None
12668        }
12669    }
12670
12671    pub fn render_crease_trailer(
12672        &self,
12673        buffer_row: MultiBufferRow,
12674        cx: &mut WindowContext,
12675    ) -> Option<AnyElement> {
12676        let folded = self.is_line_folded(buffer_row);
12677        let crease = self
12678            .crease_snapshot
12679            .query_row(buffer_row, &self.buffer_snapshot)?;
12680        Some((crease.render_trailer)(buffer_row, folded, cx))
12681    }
12682}
12683
12684impl Deref for EditorSnapshot {
12685    type Target = DisplaySnapshot;
12686
12687    fn deref(&self) -> &Self::Target {
12688        &self.display_snapshot
12689    }
12690}
12691
12692#[derive(Clone, Debug, PartialEq, Eq)]
12693pub enum EditorEvent {
12694    InputIgnored {
12695        text: Arc<str>,
12696    },
12697    InputHandled {
12698        utf16_range_to_replace: Option<Range<isize>>,
12699        text: Arc<str>,
12700    },
12701    ExcerptsAdded {
12702        buffer: Model<Buffer>,
12703        predecessor: ExcerptId,
12704        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12705    },
12706    ExcerptsRemoved {
12707        ids: Vec<ExcerptId>,
12708    },
12709    ExcerptsEdited {
12710        ids: Vec<ExcerptId>,
12711    },
12712    ExcerptsExpanded {
12713        ids: Vec<ExcerptId>,
12714    },
12715    BufferEdited,
12716    Edited {
12717        transaction_id: clock::Lamport,
12718    },
12719    Reparsed(BufferId),
12720    Focused,
12721    FocusedIn,
12722    Blurred,
12723    DirtyChanged,
12724    Saved,
12725    TitleChanged,
12726    DiffBaseChanged,
12727    SelectionsChanged {
12728        local: bool,
12729    },
12730    ScrollPositionChanged {
12731        local: bool,
12732        autoscroll: bool,
12733    },
12734    Closed,
12735    TransactionUndone {
12736        transaction_id: clock::Lamport,
12737    },
12738    TransactionBegun {
12739        transaction_id: clock::Lamport,
12740    },
12741}
12742
12743impl EventEmitter<EditorEvent> for Editor {}
12744
12745impl FocusableView for Editor {
12746    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12747        self.focus_handle.clone()
12748    }
12749}
12750
12751impl Render for Editor {
12752    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12753        let settings = ThemeSettings::get_global(cx);
12754
12755        let text_style = match self.mode {
12756            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12757                color: cx.theme().colors().editor_foreground,
12758                font_family: settings.ui_font.family.clone(),
12759                font_features: settings.ui_font.features.clone(),
12760                font_fallbacks: settings.ui_font.fallbacks.clone(),
12761                font_size: rems(0.875).into(),
12762                font_weight: settings.ui_font.weight,
12763                line_height: relative(settings.buffer_line_height.value()),
12764                ..Default::default()
12765            },
12766            EditorMode::Full => TextStyle {
12767                color: cx.theme().colors().editor_foreground,
12768                font_family: settings.buffer_font.family.clone(),
12769                font_features: settings.buffer_font.features.clone(),
12770                font_fallbacks: settings.buffer_font.fallbacks.clone(),
12771                font_size: settings.buffer_font_size(cx).into(),
12772                font_weight: settings.buffer_font.weight,
12773                line_height: relative(settings.buffer_line_height.value()),
12774                ..Default::default()
12775            },
12776        };
12777
12778        let background = match self.mode {
12779            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12780            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12781            EditorMode::Full => cx.theme().colors().editor_background,
12782        };
12783
12784        EditorElement::new(
12785            cx.view(),
12786            EditorStyle {
12787                background,
12788                local_player: cx.theme().players().local(),
12789                text: text_style,
12790                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12791                syntax: cx.theme().syntax().clone(),
12792                status: cx.theme().status().clone(),
12793                inlay_hints_style: HighlightStyle {
12794                    color: Some(cx.theme().status().hint),
12795                    ..HighlightStyle::default()
12796                },
12797                suggestions_style: HighlightStyle {
12798                    color: Some(cx.theme().status().predictive),
12799                    ..HighlightStyle::default()
12800                },
12801                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
12802            },
12803        )
12804    }
12805}
12806
12807impl ViewInputHandler for Editor {
12808    fn text_for_range(
12809        &mut self,
12810        range_utf16: Range<usize>,
12811        cx: &mut ViewContext<Self>,
12812    ) -> Option<String> {
12813        Some(
12814            self.buffer
12815                .read(cx)
12816                .read(cx)
12817                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12818                .collect(),
12819        )
12820    }
12821
12822    fn selected_text_range(
12823        &mut self,
12824        ignore_disabled_input: bool,
12825        cx: &mut ViewContext<Self>,
12826    ) -> Option<UTF16Selection> {
12827        // Prevent the IME menu from appearing when holding down an alphabetic key
12828        // while input is disabled.
12829        if !ignore_disabled_input && !self.input_enabled {
12830            return None;
12831        }
12832
12833        let selection = self.selections.newest::<OffsetUtf16>(cx);
12834        let range = selection.range();
12835
12836        Some(UTF16Selection {
12837            range: range.start.0..range.end.0,
12838            reversed: selection.reversed,
12839        })
12840    }
12841
12842    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12843        let snapshot = self.buffer.read(cx).read(cx);
12844        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
12845        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12846    }
12847
12848    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12849        self.clear_highlights::<InputComposition>(cx);
12850        self.ime_transaction.take();
12851    }
12852
12853    fn replace_text_in_range(
12854        &mut self,
12855        range_utf16: Option<Range<usize>>,
12856        text: &str,
12857        cx: &mut ViewContext<Self>,
12858    ) {
12859        if !self.input_enabled {
12860            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12861            return;
12862        }
12863
12864        self.transact(cx, |this, cx| {
12865            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12866                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12867                Some(this.selection_replacement_ranges(range_utf16, cx))
12868            } else {
12869                this.marked_text_ranges(cx)
12870            };
12871
12872            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12873                let newest_selection_id = this.selections.newest_anchor().id;
12874                this.selections
12875                    .all::<OffsetUtf16>(cx)
12876                    .iter()
12877                    .zip(ranges_to_replace.iter())
12878                    .find_map(|(selection, range)| {
12879                        if selection.id == newest_selection_id {
12880                            Some(
12881                                (range.start.0 as isize - selection.head().0 as isize)
12882                                    ..(range.end.0 as isize - selection.head().0 as isize),
12883                            )
12884                        } else {
12885                            None
12886                        }
12887                    })
12888            });
12889
12890            cx.emit(EditorEvent::InputHandled {
12891                utf16_range_to_replace: range_to_replace,
12892                text: text.into(),
12893            });
12894
12895            if let Some(new_selected_ranges) = new_selected_ranges {
12896                this.change_selections(None, cx, |selections| {
12897                    selections.select_ranges(new_selected_ranges)
12898                });
12899                this.backspace(&Default::default(), cx);
12900            }
12901
12902            this.handle_input(text, cx);
12903        });
12904
12905        if let Some(transaction) = self.ime_transaction {
12906            self.buffer.update(cx, |buffer, cx| {
12907                buffer.group_until_transaction(transaction, cx);
12908            });
12909        }
12910
12911        self.unmark_text(cx);
12912    }
12913
12914    fn replace_and_mark_text_in_range(
12915        &mut self,
12916        range_utf16: Option<Range<usize>>,
12917        text: &str,
12918        new_selected_range_utf16: Option<Range<usize>>,
12919        cx: &mut ViewContext<Self>,
12920    ) {
12921        if !self.input_enabled {
12922            return;
12923        }
12924
12925        let transaction = self.transact(cx, |this, cx| {
12926            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12927                let snapshot = this.buffer.read(cx).read(cx);
12928                if let Some(relative_range_utf16) = range_utf16.as_ref() {
12929                    for marked_range in &mut marked_ranges {
12930                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12931                        marked_range.start.0 += relative_range_utf16.start;
12932                        marked_range.start =
12933                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12934                        marked_range.end =
12935                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12936                    }
12937                }
12938                Some(marked_ranges)
12939            } else if let Some(range_utf16) = range_utf16 {
12940                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12941                Some(this.selection_replacement_ranges(range_utf16, cx))
12942            } else {
12943                None
12944            };
12945
12946            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12947                let newest_selection_id = this.selections.newest_anchor().id;
12948                this.selections
12949                    .all::<OffsetUtf16>(cx)
12950                    .iter()
12951                    .zip(ranges_to_replace.iter())
12952                    .find_map(|(selection, range)| {
12953                        if selection.id == newest_selection_id {
12954                            Some(
12955                                (range.start.0 as isize - selection.head().0 as isize)
12956                                    ..(range.end.0 as isize - selection.head().0 as isize),
12957                            )
12958                        } else {
12959                            None
12960                        }
12961                    })
12962            });
12963
12964            cx.emit(EditorEvent::InputHandled {
12965                utf16_range_to_replace: range_to_replace,
12966                text: text.into(),
12967            });
12968
12969            if let Some(ranges) = ranges_to_replace {
12970                this.change_selections(None, cx, |s| s.select_ranges(ranges));
12971            }
12972
12973            let marked_ranges = {
12974                let snapshot = this.buffer.read(cx).read(cx);
12975                this.selections
12976                    .disjoint_anchors()
12977                    .iter()
12978                    .map(|selection| {
12979                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12980                    })
12981                    .collect::<Vec<_>>()
12982            };
12983
12984            if text.is_empty() {
12985                this.unmark_text(cx);
12986            } else {
12987                this.highlight_text::<InputComposition>(
12988                    marked_ranges.clone(),
12989                    HighlightStyle {
12990                        underline: Some(UnderlineStyle {
12991                            thickness: px(1.),
12992                            color: None,
12993                            wavy: false,
12994                        }),
12995                        ..Default::default()
12996                    },
12997                    cx,
12998                );
12999            }
13000
13001            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13002            let use_autoclose = this.use_autoclose;
13003            let use_auto_surround = this.use_auto_surround;
13004            this.set_use_autoclose(false);
13005            this.set_use_auto_surround(false);
13006            this.handle_input(text, cx);
13007            this.set_use_autoclose(use_autoclose);
13008            this.set_use_auto_surround(use_auto_surround);
13009
13010            if let Some(new_selected_range) = new_selected_range_utf16 {
13011                let snapshot = this.buffer.read(cx).read(cx);
13012                let new_selected_ranges = marked_ranges
13013                    .into_iter()
13014                    .map(|marked_range| {
13015                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13016                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13017                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13018                        snapshot.clip_offset_utf16(new_start, Bias::Left)
13019                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13020                    })
13021                    .collect::<Vec<_>>();
13022
13023                drop(snapshot);
13024                this.change_selections(None, cx, |selections| {
13025                    selections.select_ranges(new_selected_ranges)
13026                });
13027            }
13028        });
13029
13030        self.ime_transaction = self.ime_transaction.or(transaction);
13031        if let Some(transaction) = self.ime_transaction {
13032            self.buffer.update(cx, |buffer, cx| {
13033                buffer.group_until_transaction(transaction, cx);
13034            });
13035        }
13036
13037        if self.text_highlights::<InputComposition>(cx).is_none() {
13038            self.ime_transaction.take();
13039        }
13040    }
13041
13042    fn bounds_for_range(
13043        &mut self,
13044        range_utf16: Range<usize>,
13045        element_bounds: gpui::Bounds<Pixels>,
13046        cx: &mut ViewContext<Self>,
13047    ) -> Option<gpui::Bounds<Pixels>> {
13048        let text_layout_details = self.text_layout_details(cx);
13049        let style = &text_layout_details.editor_style;
13050        let font_id = cx.text_system().resolve_font(&style.text.font());
13051        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13052        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13053
13054        let em_width = cx
13055            .text_system()
13056            .typographic_bounds(font_id, font_size, 'm')
13057            .unwrap()
13058            .size
13059            .width;
13060
13061        let snapshot = self.snapshot(cx);
13062        let scroll_position = snapshot.scroll_position();
13063        let scroll_left = scroll_position.x * em_width;
13064
13065        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13066        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13067            + self.gutter_dimensions.width;
13068        let y = line_height * (start.row().as_f32() - scroll_position.y);
13069
13070        Some(Bounds {
13071            origin: element_bounds.origin + point(x, y),
13072            size: size(em_width, line_height),
13073        })
13074    }
13075}
13076
13077trait SelectionExt {
13078    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13079    fn spanned_rows(
13080        &self,
13081        include_end_if_at_line_start: bool,
13082        map: &DisplaySnapshot,
13083    ) -> Range<MultiBufferRow>;
13084}
13085
13086impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13087    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13088        let start = self
13089            .start
13090            .to_point(&map.buffer_snapshot)
13091            .to_display_point(map);
13092        let end = self
13093            .end
13094            .to_point(&map.buffer_snapshot)
13095            .to_display_point(map);
13096        if self.reversed {
13097            end..start
13098        } else {
13099            start..end
13100        }
13101    }
13102
13103    fn spanned_rows(
13104        &self,
13105        include_end_if_at_line_start: bool,
13106        map: &DisplaySnapshot,
13107    ) -> Range<MultiBufferRow> {
13108        let start = self.start.to_point(&map.buffer_snapshot);
13109        let mut end = self.end.to_point(&map.buffer_snapshot);
13110        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13111            end.row -= 1;
13112        }
13113
13114        let buffer_start = map.prev_line_boundary(start).0;
13115        let buffer_end = map.next_line_boundary(end).0;
13116        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13117    }
13118}
13119
13120impl<T: InvalidationRegion> InvalidationStack<T> {
13121    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13122    where
13123        S: Clone + ToOffset,
13124    {
13125        while let Some(region) = self.last() {
13126            let all_selections_inside_invalidation_ranges =
13127                if selections.len() == region.ranges().len() {
13128                    selections
13129                        .iter()
13130                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13131                        .all(|(selection, invalidation_range)| {
13132                            let head = selection.head().to_offset(buffer);
13133                            invalidation_range.start <= head && invalidation_range.end >= head
13134                        })
13135                } else {
13136                    false
13137                };
13138
13139            if all_selections_inside_invalidation_ranges {
13140                break;
13141            } else {
13142                self.pop();
13143            }
13144        }
13145    }
13146}
13147
13148impl<T> Default for InvalidationStack<T> {
13149    fn default() -> Self {
13150        Self(Default::default())
13151    }
13152}
13153
13154impl<T> Deref for InvalidationStack<T> {
13155    type Target = Vec<T>;
13156
13157    fn deref(&self) -> &Self::Target {
13158        &self.0
13159    }
13160}
13161
13162impl<T> DerefMut for InvalidationStack<T> {
13163    fn deref_mut(&mut self) -> &mut Self::Target {
13164        &mut self.0
13165    }
13166}
13167
13168impl InvalidationRegion for SnippetState {
13169    fn ranges(&self) -> &[Range<Anchor>] {
13170        &self.ranges[self.active_index]
13171    }
13172}
13173
13174pub fn diagnostic_block_renderer(
13175    diagnostic: Diagnostic,
13176    max_message_rows: Option<u8>,
13177    allow_closing: bool,
13178    _is_valid: bool,
13179) -> RenderBlock {
13180    let (text_without_backticks, code_ranges) =
13181        highlight_diagnostic_message(&diagnostic, max_message_rows);
13182
13183    Box::new(move |cx: &mut BlockContext| {
13184        let group_id: SharedString = cx.block_id.to_string().into();
13185
13186        let mut text_style = cx.text_style().clone();
13187        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13188        let theme_settings = ThemeSettings::get_global(cx);
13189        text_style.font_family = theme_settings.buffer_font.family.clone();
13190        text_style.font_style = theme_settings.buffer_font.style;
13191        text_style.font_features = theme_settings.buffer_font.features.clone();
13192        text_style.font_weight = theme_settings.buffer_font.weight;
13193
13194        let multi_line_diagnostic = diagnostic.message.contains('\n');
13195
13196        let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13197            if multi_line_diagnostic {
13198                v_flex()
13199            } else {
13200                h_flex()
13201            }
13202            .when(allow_closing, |div| {
13203                div.children(diagnostic.is_primary.then(|| {
13204                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13205                        .icon_color(Color::Muted)
13206                        .size(ButtonSize::Compact)
13207                        .style(ButtonStyle::Transparent)
13208                        .visible_on_hover(group_id.clone())
13209                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13210                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13211                }))
13212            })
13213            .child(
13214                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13215                    .icon_color(Color::Muted)
13216                    .size(ButtonSize::Compact)
13217                    .style(ButtonStyle::Transparent)
13218                    .visible_on_hover(group_id.clone())
13219                    .on_click({
13220                        let message = diagnostic.message.clone();
13221                        move |_click, cx| {
13222                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13223                        }
13224                    })
13225                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13226            )
13227        };
13228
13229        let icon_size = buttons(&diagnostic, cx.block_id)
13230            .into_any_element()
13231            .layout_as_root(AvailableSpace::min_size(), cx);
13232
13233        h_flex()
13234            .id(cx.block_id)
13235            .group(group_id.clone())
13236            .relative()
13237            .size_full()
13238            .pl(cx.gutter_dimensions.width)
13239            .w(cx.max_width + cx.gutter_dimensions.width)
13240            .child(
13241                div()
13242                    .flex()
13243                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13244                    .flex_shrink(),
13245            )
13246            .child(buttons(&diagnostic, cx.block_id))
13247            .child(div().flex().flex_shrink_0().child(
13248                StyledText::new(text_without_backticks.clone()).with_highlights(
13249                    &text_style,
13250                    code_ranges.iter().map(|range| {
13251                        (
13252                            range.clone(),
13253                            HighlightStyle {
13254                                font_weight: Some(FontWeight::BOLD),
13255                                ..Default::default()
13256                            },
13257                        )
13258                    }),
13259                ),
13260            ))
13261            .into_any_element()
13262    })
13263}
13264
13265pub fn highlight_diagnostic_message(
13266    diagnostic: &Diagnostic,
13267    mut max_message_rows: Option<u8>,
13268) -> (SharedString, Vec<Range<usize>>) {
13269    let mut text_without_backticks = String::new();
13270    let mut code_ranges = Vec::new();
13271
13272    if let Some(source) = &diagnostic.source {
13273        text_without_backticks.push_str(source);
13274        code_ranges.push(0..source.len());
13275        text_without_backticks.push_str(": ");
13276    }
13277
13278    let mut prev_offset = 0;
13279    let mut in_code_block = false;
13280    let has_row_limit = max_message_rows.is_some();
13281    let mut newline_indices = diagnostic
13282        .message
13283        .match_indices('\n')
13284        .filter(|_| has_row_limit)
13285        .map(|(ix, _)| ix)
13286        .fuse()
13287        .peekable();
13288
13289    for (quote_ix, _) in diagnostic
13290        .message
13291        .match_indices('`')
13292        .chain([(diagnostic.message.len(), "")])
13293    {
13294        let mut first_newline_ix = None;
13295        let mut last_newline_ix = None;
13296        while let Some(newline_ix) = newline_indices.peek() {
13297            if *newline_ix < quote_ix {
13298                if first_newline_ix.is_none() {
13299                    first_newline_ix = Some(*newline_ix);
13300                }
13301                last_newline_ix = Some(*newline_ix);
13302
13303                if let Some(rows_left) = &mut max_message_rows {
13304                    if *rows_left == 0 {
13305                        break;
13306                    } else {
13307                        *rows_left -= 1;
13308                    }
13309                }
13310                let _ = newline_indices.next();
13311            } else {
13312                break;
13313            }
13314        }
13315        let prev_len = text_without_backticks.len();
13316        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13317        text_without_backticks.push_str(new_text);
13318        if in_code_block {
13319            code_ranges.push(prev_len..text_without_backticks.len());
13320        }
13321        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13322        in_code_block = !in_code_block;
13323        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13324            text_without_backticks.push_str("...");
13325            break;
13326        }
13327    }
13328
13329    (text_without_backticks.into(), code_ranges)
13330}
13331
13332fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13333    match severity {
13334        DiagnosticSeverity::ERROR => colors.error,
13335        DiagnosticSeverity::WARNING => colors.warning,
13336        DiagnosticSeverity::INFORMATION => colors.info,
13337        DiagnosticSeverity::HINT => colors.info,
13338        _ => colors.ignored,
13339    }
13340}
13341
13342pub fn styled_runs_for_code_label<'a>(
13343    label: &'a CodeLabel,
13344    syntax_theme: &'a theme::SyntaxTheme,
13345) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13346    let fade_out = HighlightStyle {
13347        fade_out: Some(0.35),
13348        ..Default::default()
13349    };
13350
13351    let mut prev_end = label.filter_range.end;
13352    label
13353        .runs
13354        .iter()
13355        .enumerate()
13356        .flat_map(move |(ix, (range, highlight_id))| {
13357            let style = if let Some(style) = highlight_id.style(syntax_theme) {
13358                style
13359            } else {
13360                return Default::default();
13361            };
13362            let mut muted_style = style;
13363            muted_style.highlight(fade_out);
13364
13365            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13366            if range.start >= label.filter_range.end {
13367                if range.start > prev_end {
13368                    runs.push((prev_end..range.start, fade_out));
13369                }
13370                runs.push((range.clone(), muted_style));
13371            } else if range.end <= label.filter_range.end {
13372                runs.push((range.clone(), style));
13373            } else {
13374                runs.push((range.start..label.filter_range.end, style));
13375                runs.push((label.filter_range.end..range.end, muted_style));
13376            }
13377            prev_end = cmp::max(prev_end, range.end);
13378
13379            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13380                runs.push((prev_end..label.text.len(), fade_out));
13381            }
13382
13383            runs
13384        })
13385}
13386
13387pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13388    let mut prev_index = 0;
13389    let mut prev_codepoint: Option<char> = None;
13390    text.char_indices()
13391        .chain([(text.len(), '\0')])
13392        .filter_map(move |(index, codepoint)| {
13393            let prev_codepoint = prev_codepoint.replace(codepoint)?;
13394            let is_boundary = index == text.len()
13395                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13396                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13397            if is_boundary {
13398                let chunk = &text[prev_index..index];
13399                prev_index = index;
13400                Some(chunk)
13401            } else {
13402                None
13403            }
13404        })
13405}
13406
13407pub trait RangeToAnchorExt: Sized {
13408    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13409
13410    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13411        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13412        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
13413    }
13414}
13415
13416impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13417    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13418        let start_offset = self.start.to_offset(snapshot);
13419        let end_offset = self.end.to_offset(snapshot);
13420        if start_offset == end_offset {
13421            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13422        } else {
13423            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13424        }
13425    }
13426}
13427
13428pub trait RowExt {
13429    fn as_f32(&self) -> f32;
13430
13431    fn next_row(&self) -> Self;
13432
13433    fn previous_row(&self) -> Self;
13434
13435    fn minus(&self, other: Self) -> u32;
13436}
13437
13438impl RowExt for DisplayRow {
13439    fn as_f32(&self) -> f32 {
13440        self.0 as f32
13441    }
13442
13443    fn next_row(&self) -> Self {
13444        Self(self.0 + 1)
13445    }
13446
13447    fn previous_row(&self) -> Self {
13448        Self(self.0.saturating_sub(1))
13449    }
13450
13451    fn minus(&self, other: Self) -> u32 {
13452        self.0 - other.0
13453    }
13454}
13455
13456impl RowExt for MultiBufferRow {
13457    fn as_f32(&self) -> f32 {
13458        self.0 as f32
13459    }
13460
13461    fn next_row(&self) -> Self {
13462        Self(self.0 + 1)
13463    }
13464
13465    fn previous_row(&self) -> Self {
13466        Self(self.0.saturating_sub(1))
13467    }
13468
13469    fn minus(&self, other: Self) -> u32 {
13470        self.0 - other.0
13471    }
13472}
13473
13474trait RowRangeExt {
13475    type Row;
13476
13477    fn len(&self) -> usize;
13478
13479    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13480}
13481
13482impl RowRangeExt for Range<MultiBufferRow> {
13483    type Row = MultiBufferRow;
13484
13485    fn len(&self) -> usize {
13486        (self.end.0 - self.start.0) as usize
13487    }
13488
13489    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13490        (self.start.0..self.end.0).map(MultiBufferRow)
13491    }
13492}
13493
13494impl RowRangeExt for Range<DisplayRow> {
13495    type Row = DisplayRow;
13496
13497    fn len(&self) -> usize {
13498        (self.end.0 - self.start.0) as usize
13499    }
13500
13501    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13502        (self.start.0..self.end.0).map(DisplayRow)
13503    }
13504}
13505
13506fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13507    if hunk.diff_base_byte_range.is_empty() {
13508        DiffHunkStatus::Added
13509    } else if hunk.associated_range.is_empty() {
13510        DiffHunkStatus::Removed
13511    } else {
13512        DiffHunkStatus::Modified
13513    }
13514}
13515
13516/// If select range has more than one line, we
13517/// just point the cursor to range.start.
13518fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13519    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13520        range
13521    } else {
13522        range.start..range.start
13523    }
13524}