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::{CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine};
   63pub use editor_settings_controls::*;
   64use element::LineWithInvisibles;
   65pub use element::{
   66    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   67};
   68use futures::FutureExt;
   69use fuzzy::{StringMatch, StringMatchCandidate};
   70use git::blame::GitBlame;
   71use git::diff_hunk_to_display;
   72use gpui::{
   73    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   74    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   75    ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
   76    FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
   77    KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   78    SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   79    UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext,
   80    WeakFocusHandle, WeakView, WindowContext,
   81};
   82use highlight_matching_bracket::refresh_matching_bracket_highlights;
   83use hover_popover::{hide_hover, HoverState};
   84use hunk_diff::ExpandedHunks;
   85pub(crate) use hunk_diff::HoveredHunk;
   86use indent_guides::ActiveIndentGuidesState;
   87use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   88pub use inline_completion_provider::*;
   89pub use items::MAX_TAB_TITLE_LEN;
   90use itertools::Itertools;
   91use language::{
   92    char_kind,
   93    language_settings::{self, all_language_settings, InlayHintSettings},
   94    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   95    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   96    Point, Selection, SelectionGoal, TransactionId,
   97};
   98use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
   99use linked_editing_ranges::refresh_linked_ranges;
  100use task::{ResolvedTask, TaskTemplate, TaskVariables};
  101
  102use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  103pub use lsp::CompletionContext;
  104use lsp::{
  105    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  106    LanguageServerId,
  107};
  108use mouse_context_menu::MouseContextMenu;
  109use movement::TextLayoutDetails;
  110pub use multi_buffer::{
  111    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  112    ToPoint,
  113};
  114use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
  115use ordered_float::OrderedFloat;
  116use parking_lot::{Mutex, RwLock};
  117use project::project_settings::{GitGutterSetting, ProjectSettings};
  118use project::{
  119    CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
  120    ProjectTransaction, TaskSourceKind, WorktreeId,
  121};
  122use rand::prelude::*;
  123use rpc::{proto::*, ErrorExt};
  124use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  125use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  126use serde::{Deserialize, Serialize};
  127use settings::{update_settings_file, Settings, SettingsStore};
  128use smallvec::SmallVec;
  129use snippet::Snippet;
  130use std::{
  131    any::TypeId,
  132    borrow::Cow,
  133    cell::RefCell,
  134    cmp::{self, Ordering, Reverse},
  135    mem,
  136    num::NonZeroU32,
  137    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  138    path::{Path, PathBuf},
  139    rc::Rc,
  140    sync::Arc,
  141    time::{Duration, Instant},
  142};
  143pub use sum_tree::Bias;
  144use sum_tree::TreeMap;
  145use text::{BufferId, OffsetUtf16, Rope};
  146use theme::{
  147    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  148    ThemeColors, ThemeSettings,
  149};
  150use ui::{
  151    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  152    ListItem, Popover, Tooltip,
  153};
  154use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  155use workspace::item::{ItemHandle, PreviewTabsSettings};
  156use workspace::notifications::{DetachAndPromptErr, NotificationId};
  157use workspace::{
  158    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  159};
  160use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  161
  162use crate::hover_links::find_url;
  163use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  164
  165pub const FILE_HEADER_HEIGHT: u32 = 1;
  166pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  167pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  168pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  169const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  170const MAX_LINE_LEN: usize = 1024;
  171const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  172const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  173pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  174#[doc(hidden)]
  175pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  176#[doc(hidden)]
  177pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  178
  179pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  180pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  181
  182pub fn render_parsed_markdown(
  183    element_id: impl Into<ElementId>,
  184    parsed: &language::ParsedMarkdown,
  185    editor_style: &EditorStyle,
  186    workspace: Option<WeakView<Workspace>>,
  187    cx: &mut WindowContext,
  188) -> InteractiveText {
  189    let code_span_background_color = cx
  190        .theme()
  191        .colors()
  192        .editor_document_highlight_read_background;
  193
  194    let highlights = gpui::combine_highlights(
  195        parsed.highlights.iter().filter_map(|(range, highlight)| {
  196            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  197            Some((range.clone(), highlight))
  198        }),
  199        parsed
  200            .regions
  201            .iter()
  202            .zip(&parsed.region_ranges)
  203            .filter_map(|(region, range)| {
  204                if region.code {
  205                    Some((
  206                        range.clone(),
  207                        HighlightStyle {
  208                            background_color: Some(code_span_background_color),
  209                            ..Default::default()
  210                        },
  211                    ))
  212                } else {
  213                    None
  214                }
  215            }),
  216    );
  217
  218    let mut links = Vec::new();
  219    let mut link_ranges = Vec::new();
  220    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  221        if let Some(link) = region.link.clone() {
  222            links.push(link);
  223            link_ranges.push(range.clone());
  224        }
  225    }
  226
  227    InteractiveText::new(
  228        element_id,
  229        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  230    )
  231    .on_click(link_ranges, move |clicked_range_ix, cx| {
  232        match &links[clicked_range_ix] {
  233            markdown::Link::Web { url } => cx.open_url(url),
  234            markdown::Link::Path { path } => {
  235                if let Some(workspace) = &workspace {
  236                    _ = workspace.update(cx, |workspace, cx| {
  237                        workspace.open_abs_path(path.clone(), false, cx).detach();
  238                    });
  239                }
  240            }
  241        }
  242    })
  243}
  244
  245#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  246pub(crate) enum InlayId {
  247    Suggestion(usize),
  248    Hint(usize),
  249}
  250
  251impl InlayId {
  252    fn id(&self) -> usize {
  253        match self {
  254            Self::Suggestion(id) => *id,
  255            Self::Hint(id) => *id,
  256        }
  257    }
  258}
  259
  260enum DiffRowHighlight {}
  261enum DocumentHighlightRead {}
  262enum DocumentHighlightWrite {}
  263enum InputComposition {}
  264
  265#[derive(Copy, Clone, PartialEq, Eq)]
  266pub enum Direction {
  267    Prev,
  268    Next,
  269}
  270
  271#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  272pub enum Navigated {
  273    Yes,
  274    No,
  275}
  276
  277impl Navigated {
  278    pub fn from_bool(yes: bool) -> Navigated {
  279        if yes {
  280            Navigated::Yes
  281        } else {
  282            Navigated::No
  283        }
  284    }
  285}
  286
  287pub fn init_settings(cx: &mut AppContext) {
  288    EditorSettings::register(cx);
  289}
  290
  291pub fn init(cx: &mut AppContext) {
  292    init_settings(cx);
  293
  294    workspace::register_project_item::<Editor>(cx);
  295    workspace::FollowableViewRegistry::register::<Editor>(cx);
  296    workspace::register_serializable_item::<Editor>(cx);
  297
  298    cx.observe_new_views(
  299        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  300            workspace.register_action(Editor::new_file);
  301            workspace.register_action(Editor::new_file_vertical);
  302            workspace.register_action(Editor::new_file_horizontal);
  303        },
  304    )
  305    .detach();
  306
  307    cx.on_action(move |_: &workspace::NewFile, cx| {
  308        let app_state = workspace::AppState::global(cx);
  309        if let Some(app_state) = app_state.upgrade() {
  310            workspace::open_new(app_state, cx, |workspace, cx| {
  311                Editor::new_file(workspace, &Default::default(), cx)
  312            })
  313            .detach();
  314        }
  315    });
  316    cx.on_action(move |_: &workspace::NewWindow, cx| {
  317        let app_state = workspace::AppState::global(cx);
  318        if let Some(app_state) = app_state.upgrade() {
  319            workspace::open_new(app_state, cx, |workspace, cx| {
  320                Editor::new_file(workspace, &Default::default(), cx)
  321            })
  322            .detach();
  323        }
  324    });
  325}
  326
  327pub struct SearchWithinRange;
  328
  329trait InvalidationRegion {
  330    fn ranges(&self) -> &[Range<Anchor>];
  331}
  332
  333#[derive(Clone, Debug, PartialEq)]
  334pub enum SelectPhase {
  335    Begin {
  336        position: DisplayPoint,
  337        add: bool,
  338        click_count: usize,
  339    },
  340    BeginColumnar {
  341        position: DisplayPoint,
  342        reset: bool,
  343        goal_column: u32,
  344    },
  345    Extend {
  346        position: DisplayPoint,
  347        click_count: usize,
  348    },
  349    Update {
  350        position: DisplayPoint,
  351        goal_column: u32,
  352        scroll_delta: gpui::Point<f32>,
  353    },
  354    End,
  355}
  356
  357#[derive(Clone, Debug)]
  358pub enum SelectMode {
  359    Character,
  360    Word(Range<Anchor>),
  361    Line(Range<Anchor>),
  362    All,
  363}
  364
  365#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  366pub enum EditorMode {
  367    SingleLine { auto_width: bool },
  368    AutoHeight { max_lines: usize },
  369    Full,
  370}
  371
  372#[derive(Clone, Debug)]
  373pub enum SoftWrap {
  374    None,
  375    PreferLine,
  376    EditorWidth,
  377    Column(u32),
  378    Bounded(u32),
  379}
  380
  381#[derive(Clone)]
  382pub struct EditorStyle {
  383    pub background: Hsla,
  384    pub local_player: PlayerColor,
  385    pub text: TextStyle,
  386    pub scrollbar_width: Pixels,
  387    pub syntax: Arc<SyntaxTheme>,
  388    pub status: StatusColors,
  389    pub inlay_hints_style: HighlightStyle,
  390    pub suggestions_style: HighlightStyle,
  391    pub unnecessary_code_fade: f32,
  392}
  393
  394impl Default for EditorStyle {
  395    fn default() -> Self {
  396        Self {
  397            background: Hsla::default(),
  398            local_player: PlayerColor::default(),
  399            text: TextStyle::default(),
  400            scrollbar_width: Pixels::default(),
  401            syntax: Default::default(),
  402            // HACK: Status colors don't have a real default.
  403            // We should look into removing the status colors from the editor
  404            // style and retrieve them directly from the theme.
  405            status: StatusColors::dark(),
  406            inlay_hints_style: HighlightStyle::default(),
  407            suggestions_style: HighlightStyle::default(),
  408            unnecessary_code_fade: Default::default(),
  409        }
  410    }
  411}
  412
  413type CompletionId = usize;
  414
  415#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  416struct EditorActionId(usize);
  417
  418impl EditorActionId {
  419    pub fn post_inc(&mut self) -> Self {
  420        let answer = self.0;
  421
  422        *self = Self(answer + 1);
  423
  424        Self(answer)
  425    }
  426}
  427
  428// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  429// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  430
  431type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  432type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  433
  434#[derive(Default)]
  435struct ScrollbarMarkerState {
  436    scrollbar_size: Size<Pixels>,
  437    dirty: bool,
  438    markers: Arc<[PaintQuad]>,
  439    pending_refresh: Option<Task<Result<()>>>,
  440}
  441
  442impl ScrollbarMarkerState {
  443    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  444        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  445    }
  446}
  447
  448#[derive(Clone, Debug)]
  449struct RunnableTasks {
  450    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  451    offset: MultiBufferOffset,
  452    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  453    column: u32,
  454    // Values of all named captures, including those starting with '_'
  455    extra_variables: HashMap<String, String>,
  456    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  457    context_range: Range<BufferOffset>,
  458}
  459
  460#[derive(Clone)]
  461struct ResolvedTasks {
  462    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  463    position: Anchor,
  464}
  465#[derive(Copy, Clone, Debug)]
  466struct MultiBufferOffset(usize);
  467#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  468struct BufferOffset(usize);
  469
  470// Addons allow storing per-editor state in other crates (e.g. Vim)
  471pub trait Addon: 'static {
  472    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  473
  474    fn to_any(&self) -> &dyn std::any::Any;
  475}
  476
  477/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  478///
  479/// See the [module level documentation](self) for more information.
  480pub struct Editor {
  481    focus_handle: FocusHandle,
  482    last_focused_descendant: Option<WeakFocusHandle>,
  483    /// The text buffer being edited
  484    buffer: Model<MultiBuffer>,
  485    /// Map of how text in the buffer should be displayed.
  486    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  487    pub display_map: Model<DisplayMap>,
  488    pub selections: SelectionsCollection,
  489    pub scroll_manager: ScrollManager,
  490    /// When inline assist editors are linked, they all render cursors because
  491    /// typing enters text into each of them, even the ones that aren't focused.
  492    pub(crate) show_cursor_when_unfocused: bool,
  493    columnar_selection_tail: Option<Anchor>,
  494    add_selections_state: Option<AddSelectionsState>,
  495    select_next_state: Option<SelectNextState>,
  496    select_prev_state: Option<SelectNextState>,
  497    selection_history: SelectionHistory,
  498    autoclose_regions: Vec<AutocloseRegion>,
  499    snippet_stack: InvalidationStack<SnippetState>,
  500    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  501    ime_transaction: Option<TransactionId>,
  502    active_diagnostics: Option<ActiveDiagnosticGroup>,
  503    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  504    project: Option<Model<Project>>,
  505    completion_provider: Option<Box<dyn CompletionProvider>>,
  506    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  507    blink_manager: Model<BlinkManager>,
  508    show_cursor_names: bool,
  509    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  510    pub show_local_selections: bool,
  511    mode: EditorMode,
  512    show_breadcrumbs: bool,
  513    show_gutter: bool,
  514    show_line_numbers: Option<bool>,
  515    show_git_diff_gutter: Option<bool>,
  516    show_code_actions: Option<bool>,
  517    show_runnables: Option<bool>,
  518    show_wrap_guides: Option<bool>,
  519    show_indent_guides: Option<bool>,
  520    placeholder_text: Option<Arc<str>>,
  521    highlight_order: usize,
  522    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  523    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  524    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  525    scrollbar_marker_state: ScrollbarMarkerState,
  526    active_indent_guides_state: ActiveIndentGuidesState,
  527    nav_history: Option<ItemNavHistory>,
  528    context_menu: RwLock<Option<ContextMenu>>,
  529    mouse_context_menu: Option<MouseContextMenu>,
  530    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  531    signature_help_state: SignatureHelpState,
  532    auto_signature_help: Option<bool>,
  533    find_all_references_task_sources: Vec<Anchor>,
  534    next_completion_id: CompletionId,
  535    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  536    available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
  537    code_actions_task: Option<Task<()>>,
  538    document_highlights_task: Option<Task<()>>,
  539    linked_editing_range_task: Option<Task<Option<()>>>,
  540    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  541    pending_rename: Option<RenameState>,
  542    searchable: bool,
  543    cursor_shape: CursorShape,
  544    current_line_highlight: Option<CurrentLineHighlight>,
  545    collapse_matches: bool,
  546    autoindent_mode: Option<AutoindentMode>,
  547    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  548    input_enabled: bool,
  549    use_modal_editing: bool,
  550    read_only: bool,
  551    leader_peer_id: Option<PeerId>,
  552    remote_id: Option<ViewId>,
  553    hover_state: HoverState,
  554    gutter_hovered: bool,
  555    hovered_link_state: Option<HoveredLinkState>,
  556    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  557    active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
  558    show_inline_completions: bool,
  559    inlay_hint_cache: InlayHintCache,
  560    expanded_hunks: ExpandedHunks,
  561    next_inlay_id: usize,
  562    _subscriptions: Vec<Subscription>,
  563    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  564    gutter_dimensions: GutterDimensions,
  565    style: Option<EditorStyle>,
  566    next_editor_action_id: EditorActionId,
  567    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  568    use_autoclose: bool,
  569    use_auto_surround: bool,
  570    auto_replace_emoji_shortcode: bool,
  571    show_git_blame_gutter: bool,
  572    show_git_blame_inline: bool,
  573    show_git_blame_inline_delay_task: Option<Task<()>>,
  574    git_blame_inline_enabled: bool,
  575    serialize_dirty_buffers: bool,
  576    show_selection_menu: Option<bool>,
  577    blame: Option<Model<GitBlame>>,
  578    blame_subscription: Option<Subscription>,
  579    custom_context_menu: Option<
  580        Box<
  581            dyn 'static
  582                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  583        >,
  584    >,
  585    last_bounds: Option<Bounds<Pixels>>,
  586    expect_bounds_change: Option<Bounds<Pixels>>,
  587    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  588    tasks_update_task: Option<Task<()>>,
  589    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  590    file_header_size: u32,
  591    breadcrumb_header: Option<String>,
  592    focused_block: Option<FocusedBlock>,
  593    next_scroll_position: NextScrollCursorCenterTopBottom,
  594    addons: HashMap<TypeId, Box<dyn Addon>>,
  595    _scroll_cursor_center_top_bottom_task: Task<()>,
  596}
  597
  598#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  599enum NextScrollCursorCenterTopBottom {
  600    #[default]
  601    Center,
  602    Top,
  603    Bottom,
  604}
  605
  606impl NextScrollCursorCenterTopBottom {
  607    fn next(&self) -> Self {
  608        match self {
  609            Self::Center => Self::Top,
  610            Self::Top => Self::Bottom,
  611            Self::Bottom => Self::Center,
  612        }
  613    }
  614}
  615
  616#[derive(Clone)]
  617pub struct EditorSnapshot {
  618    pub mode: EditorMode,
  619    show_gutter: bool,
  620    show_line_numbers: Option<bool>,
  621    show_git_diff_gutter: Option<bool>,
  622    show_code_actions: Option<bool>,
  623    show_runnables: Option<bool>,
  624    render_git_blame_gutter: bool,
  625    pub display_snapshot: DisplaySnapshot,
  626    pub placeholder_text: Option<Arc<str>>,
  627    is_focused: bool,
  628    scroll_anchor: ScrollAnchor,
  629    ongoing_scroll: OngoingScroll,
  630    current_line_highlight: CurrentLineHighlight,
  631    gutter_hovered: bool,
  632}
  633
  634const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
  635
  636#[derive(Default, Debug, Clone, Copy)]
  637pub struct GutterDimensions {
  638    pub left_padding: Pixels,
  639    pub right_padding: Pixels,
  640    pub width: Pixels,
  641    pub margin: Pixels,
  642    pub git_blame_entries_width: Option<Pixels>,
  643}
  644
  645impl GutterDimensions {
  646    /// The full width of the space taken up by the gutter.
  647    pub fn full_width(&self) -> Pixels {
  648        self.margin + self.width
  649    }
  650
  651    /// The width of the space reserved for the fold indicators,
  652    /// use alongside 'justify_end' and `gutter_width` to
  653    /// right align content with the line numbers
  654    pub fn fold_area_width(&self) -> Pixels {
  655        self.margin + self.right_padding
  656    }
  657}
  658
  659#[derive(Debug)]
  660pub struct RemoteSelection {
  661    pub replica_id: ReplicaId,
  662    pub selection: Selection<Anchor>,
  663    pub cursor_shape: CursorShape,
  664    pub peer_id: PeerId,
  665    pub line_mode: bool,
  666    pub participant_index: Option<ParticipantIndex>,
  667    pub user_name: Option<SharedString>,
  668}
  669
  670#[derive(Clone, Debug)]
  671struct SelectionHistoryEntry {
  672    selections: Arc<[Selection<Anchor>]>,
  673    select_next_state: Option<SelectNextState>,
  674    select_prev_state: Option<SelectNextState>,
  675    add_selections_state: Option<AddSelectionsState>,
  676}
  677
  678enum SelectionHistoryMode {
  679    Normal,
  680    Undoing,
  681    Redoing,
  682}
  683
  684#[derive(Clone, PartialEq, Eq, Hash)]
  685struct HoveredCursor {
  686    replica_id: u16,
  687    selection_id: usize,
  688}
  689
  690impl Default for SelectionHistoryMode {
  691    fn default() -> Self {
  692        Self::Normal
  693    }
  694}
  695
  696#[derive(Default)]
  697struct SelectionHistory {
  698    #[allow(clippy::type_complexity)]
  699    selections_by_transaction:
  700        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  701    mode: SelectionHistoryMode,
  702    undo_stack: VecDeque<SelectionHistoryEntry>,
  703    redo_stack: VecDeque<SelectionHistoryEntry>,
  704}
  705
  706impl SelectionHistory {
  707    fn insert_transaction(
  708        &mut self,
  709        transaction_id: TransactionId,
  710        selections: Arc<[Selection<Anchor>]>,
  711    ) {
  712        self.selections_by_transaction
  713            .insert(transaction_id, (selections, None));
  714    }
  715
  716    #[allow(clippy::type_complexity)]
  717    fn transaction(
  718        &self,
  719        transaction_id: TransactionId,
  720    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  721        self.selections_by_transaction.get(&transaction_id)
  722    }
  723
  724    #[allow(clippy::type_complexity)]
  725    fn transaction_mut(
  726        &mut self,
  727        transaction_id: TransactionId,
  728    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  729        self.selections_by_transaction.get_mut(&transaction_id)
  730    }
  731
  732    fn push(&mut self, entry: SelectionHistoryEntry) {
  733        if !entry.selections.is_empty() {
  734            match self.mode {
  735                SelectionHistoryMode::Normal => {
  736                    self.push_undo(entry);
  737                    self.redo_stack.clear();
  738                }
  739                SelectionHistoryMode::Undoing => self.push_redo(entry),
  740                SelectionHistoryMode::Redoing => self.push_undo(entry),
  741            }
  742        }
  743    }
  744
  745    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  746        if self
  747            .undo_stack
  748            .back()
  749            .map_or(true, |e| e.selections != entry.selections)
  750        {
  751            self.undo_stack.push_back(entry);
  752            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  753                self.undo_stack.pop_front();
  754            }
  755        }
  756    }
  757
  758    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  759        if self
  760            .redo_stack
  761            .back()
  762            .map_or(true, |e| e.selections != entry.selections)
  763        {
  764            self.redo_stack.push_back(entry);
  765            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  766                self.redo_stack.pop_front();
  767            }
  768        }
  769    }
  770}
  771
  772struct RowHighlight {
  773    index: usize,
  774    range: RangeInclusive<Anchor>,
  775    color: Option<Hsla>,
  776    should_autoscroll: bool,
  777}
  778
  779#[derive(Clone, Debug)]
  780struct AddSelectionsState {
  781    above: bool,
  782    stack: Vec<usize>,
  783}
  784
  785#[derive(Clone)]
  786struct SelectNextState {
  787    query: AhoCorasick,
  788    wordwise: bool,
  789    done: bool,
  790}
  791
  792impl std::fmt::Debug for SelectNextState {
  793    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  794        f.debug_struct(std::any::type_name::<Self>())
  795            .field("wordwise", &self.wordwise)
  796            .field("done", &self.done)
  797            .finish()
  798    }
  799}
  800
  801#[derive(Debug)]
  802struct AutocloseRegion {
  803    selection_id: usize,
  804    range: Range<Anchor>,
  805    pair: BracketPair,
  806}
  807
  808#[derive(Debug)]
  809struct SnippetState {
  810    ranges: Vec<Vec<Range<Anchor>>>,
  811    active_index: usize,
  812}
  813
  814#[doc(hidden)]
  815pub struct RenameState {
  816    pub range: Range<Anchor>,
  817    pub old_name: Arc<str>,
  818    pub editor: View<Editor>,
  819    block_id: CustomBlockId,
  820}
  821
  822struct InvalidationStack<T>(Vec<T>);
  823
  824struct RegisteredInlineCompletionProvider {
  825    provider: Arc<dyn InlineCompletionProviderHandle>,
  826    _subscription: Subscription,
  827}
  828
  829enum ContextMenu {
  830    Completions(CompletionsMenu),
  831    CodeActions(CodeActionsMenu),
  832}
  833
  834impl ContextMenu {
  835    fn select_first(
  836        &mut self,
  837        project: Option<&Model<Project>>,
  838        cx: &mut ViewContext<Editor>,
  839    ) -> bool {
  840        if self.visible() {
  841            match self {
  842                ContextMenu::Completions(menu) => menu.select_first(project, cx),
  843                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  844            }
  845            true
  846        } else {
  847            false
  848        }
  849    }
  850
  851    fn select_prev(
  852        &mut self,
  853        project: Option<&Model<Project>>,
  854        cx: &mut ViewContext<Editor>,
  855    ) -> bool {
  856        if self.visible() {
  857            match self {
  858                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
  859                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  860            }
  861            true
  862        } else {
  863            false
  864        }
  865    }
  866
  867    fn select_next(
  868        &mut self,
  869        project: Option<&Model<Project>>,
  870        cx: &mut ViewContext<Editor>,
  871    ) -> bool {
  872        if self.visible() {
  873            match self {
  874                ContextMenu::Completions(menu) => menu.select_next(project, cx),
  875                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  876            }
  877            true
  878        } else {
  879            false
  880        }
  881    }
  882
  883    fn select_last(
  884        &mut self,
  885        project: Option<&Model<Project>>,
  886        cx: &mut ViewContext<Editor>,
  887    ) -> bool {
  888        if self.visible() {
  889            match self {
  890                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  891                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  892            }
  893            true
  894        } else {
  895            false
  896        }
  897    }
  898
  899    fn visible(&self) -> bool {
  900        match self {
  901            ContextMenu::Completions(menu) => menu.visible(),
  902            ContextMenu::CodeActions(menu) => menu.visible(),
  903        }
  904    }
  905
  906    fn render(
  907        &self,
  908        cursor_position: DisplayPoint,
  909        style: &EditorStyle,
  910        max_height: Pixels,
  911        workspace: Option<WeakView<Workspace>>,
  912        cx: &mut ViewContext<Editor>,
  913    ) -> (ContextMenuOrigin, AnyElement) {
  914        match self {
  915            ContextMenu::Completions(menu) => (
  916                ContextMenuOrigin::EditorPoint(cursor_position),
  917                menu.render(style, max_height, workspace, cx),
  918            ),
  919            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  920        }
  921    }
  922}
  923
  924enum ContextMenuOrigin {
  925    EditorPoint(DisplayPoint),
  926    GutterIndicator(DisplayRow),
  927}
  928
  929#[derive(Clone)]
  930struct CompletionsMenu {
  931    id: CompletionId,
  932    sort_completions: bool,
  933    initial_position: Anchor,
  934    buffer: Model<Buffer>,
  935    completions: Arc<RwLock<Box<[Completion]>>>,
  936    match_candidates: Arc<[StringMatchCandidate]>,
  937    matches: Arc<[StringMatch]>,
  938    selected_item: usize,
  939    scroll_handle: UniformListScrollHandle,
  940    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  941}
  942
  943impl CompletionsMenu {
  944    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  945        self.selected_item = 0;
  946        self.scroll_handle.scroll_to_item(self.selected_item);
  947        self.attempt_resolve_selected_completion_documentation(project, cx);
  948        cx.notify();
  949    }
  950
  951    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  952        if self.selected_item > 0 {
  953            self.selected_item -= 1;
  954        } else {
  955            self.selected_item = self.matches.len() - 1;
  956        }
  957        self.scroll_handle.scroll_to_item(self.selected_item);
  958        self.attempt_resolve_selected_completion_documentation(project, cx);
  959        cx.notify();
  960    }
  961
  962    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  963        if self.selected_item + 1 < self.matches.len() {
  964            self.selected_item += 1;
  965        } else {
  966            self.selected_item = 0;
  967        }
  968        self.scroll_handle.scroll_to_item(self.selected_item);
  969        self.attempt_resolve_selected_completion_documentation(project, cx);
  970        cx.notify();
  971    }
  972
  973    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  974        self.selected_item = self.matches.len() - 1;
  975        self.scroll_handle.scroll_to_item(self.selected_item);
  976        self.attempt_resolve_selected_completion_documentation(project, cx);
  977        cx.notify();
  978    }
  979
  980    fn pre_resolve_completion_documentation(
  981        buffer: Model<Buffer>,
  982        completions: Arc<RwLock<Box<[Completion]>>>,
  983        matches: Arc<[StringMatch]>,
  984        editor: &Editor,
  985        cx: &mut ViewContext<Editor>,
  986    ) -> Task<()> {
  987        let settings = EditorSettings::get_global(cx);
  988        if !settings.show_completion_documentation {
  989            return Task::ready(());
  990        }
  991
  992        let Some(provider) = editor.completion_provider.as_ref() else {
  993            return Task::ready(());
  994        };
  995
  996        let resolve_task = provider.resolve_completions(
  997            buffer,
  998            matches.iter().map(|m| m.candidate_id).collect(),
  999            completions.clone(),
 1000            cx,
 1001        );
 1002
 1003        return cx.spawn(move |this, mut cx| async move {
 1004            if let Some(true) = resolve_task.await.log_err() {
 1005                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1006            }
 1007        });
 1008    }
 1009
 1010    fn attempt_resolve_selected_completion_documentation(
 1011        &mut self,
 1012        project: Option<&Model<Project>>,
 1013        cx: &mut ViewContext<Editor>,
 1014    ) {
 1015        let settings = EditorSettings::get_global(cx);
 1016        if !settings.show_completion_documentation {
 1017            return;
 1018        }
 1019
 1020        let completion_index = self.matches[self.selected_item].candidate_id;
 1021        let Some(project) = project else {
 1022            return;
 1023        };
 1024
 1025        let resolve_task = project.update(cx, |project, cx| {
 1026            project.resolve_completions(
 1027                self.buffer.clone(),
 1028                vec![completion_index],
 1029                self.completions.clone(),
 1030                cx,
 1031            )
 1032        });
 1033
 1034        let delay_ms =
 1035            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1036        let delay = Duration::from_millis(delay_ms);
 1037
 1038        self.selected_completion_documentation_resolve_debounce
 1039            .lock()
 1040            .fire_new(delay, cx, |_, cx| {
 1041                cx.spawn(move |this, mut cx| async move {
 1042                    if let Some(true) = resolve_task.await.log_err() {
 1043                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1044                    }
 1045                })
 1046            });
 1047    }
 1048
 1049    fn visible(&self) -> bool {
 1050        !self.matches.is_empty()
 1051    }
 1052
 1053    fn render(
 1054        &self,
 1055        style: &EditorStyle,
 1056        max_height: Pixels,
 1057        workspace: Option<WeakView<Workspace>>,
 1058        cx: &mut ViewContext<Editor>,
 1059    ) -> AnyElement {
 1060        let settings = EditorSettings::get_global(cx);
 1061        let show_completion_documentation = settings.show_completion_documentation;
 1062
 1063        let widest_completion_ix = self
 1064            .matches
 1065            .iter()
 1066            .enumerate()
 1067            .max_by_key(|(_, mat)| {
 1068                let completions = self.completions.read();
 1069                let completion = &completions[mat.candidate_id];
 1070                let documentation = &completion.documentation;
 1071
 1072                let mut len = completion.label.text.chars().count();
 1073                if let Some(Documentation::SingleLine(text)) = documentation {
 1074                    if show_completion_documentation {
 1075                        len += text.chars().count();
 1076                    }
 1077                }
 1078
 1079                len
 1080            })
 1081            .map(|(ix, _)| ix);
 1082
 1083        let completions = self.completions.clone();
 1084        let matches = self.matches.clone();
 1085        let selected_item = self.selected_item;
 1086        let style = style.clone();
 1087
 1088        let multiline_docs = if show_completion_documentation {
 1089            let mat = &self.matches[selected_item];
 1090            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1091                Some(Documentation::MultiLinePlainText(text)) => {
 1092                    Some(div().child(SharedString::from(text.clone())))
 1093                }
 1094                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1095                    Some(div().child(render_parsed_markdown(
 1096                        "completions_markdown",
 1097                        parsed,
 1098                        &style,
 1099                        workspace,
 1100                        cx,
 1101                    )))
 1102                }
 1103                _ => None,
 1104            };
 1105            multiline_docs.map(|div| {
 1106                div.id("multiline_docs")
 1107                    .max_h(max_height)
 1108                    .flex_1()
 1109                    .px_1p5()
 1110                    .py_1()
 1111                    .min_w(px(260.))
 1112                    .max_w(px(640.))
 1113                    .w(px(500.))
 1114                    .overflow_y_scroll()
 1115                    .occlude()
 1116            })
 1117        } else {
 1118            None
 1119        };
 1120
 1121        let list = uniform_list(
 1122            cx.view().clone(),
 1123            "completions",
 1124            matches.len(),
 1125            move |_editor, range, cx| {
 1126                let start_ix = range.start;
 1127                let completions_guard = completions.read();
 1128
 1129                matches[range]
 1130                    .iter()
 1131                    .enumerate()
 1132                    .map(|(ix, mat)| {
 1133                        let item_ix = start_ix + ix;
 1134                        let candidate_id = mat.candidate_id;
 1135                        let completion = &completions_guard[candidate_id];
 1136
 1137                        let documentation = if show_completion_documentation {
 1138                            &completion.documentation
 1139                        } else {
 1140                            &None
 1141                        };
 1142
 1143                        let highlights = gpui::combine_highlights(
 1144                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1145                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1146                                |(range, mut highlight)| {
 1147                                    // Ignore font weight for syntax highlighting, as we'll use it
 1148                                    // for fuzzy matches.
 1149                                    highlight.font_weight = None;
 1150
 1151                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1152                                        highlight.strikethrough = Some(StrikethroughStyle {
 1153                                            thickness: 1.0.into(),
 1154                                            ..Default::default()
 1155                                        });
 1156                                        highlight.color = Some(cx.theme().colors().text_muted);
 1157                                    }
 1158
 1159                                    (range, highlight)
 1160                                },
 1161                            ),
 1162                        );
 1163                        let completion_label = StyledText::new(completion.label.text.clone())
 1164                            .with_highlights(&style.text, highlights);
 1165                        let documentation_label =
 1166                            if let Some(Documentation::SingleLine(text)) = documentation {
 1167                                if text.trim().is_empty() {
 1168                                    None
 1169                                } else {
 1170                                    Some(
 1171                                        Label::new(text.clone())
 1172                                            .ml_4()
 1173                                            .size(LabelSize::Small)
 1174                                            .color(Color::Muted),
 1175                                    )
 1176                                }
 1177                            } else {
 1178                                None
 1179                            };
 1180
 1181                        div().min_w(px(220.)).max_w(px(540.)).child(
 1182                            ListItem::new(mat.candidate_id)
 1183                                .inset(true)
 1184                                .selected(item_ix == selected_item)
 1185                                .on_click(cx.listener(move |editor, _event, cx| {
 1186                                    cx.stop_propagation();
 1187                                    if let Some(task) = editor.confirm_completion(
 1188                                        &ConfirmCompletion {
 1189                                            item_ix: Some(item_ix),
 1190                                        },
 1191                                        cx,
 1192                                    ) {
 1193                                        task.detach_and_log_err(cx)
 1194                                    }
 1195                                }))
 1196                                .child(h_flex().overflow_hidden().child(completion_label))
 1197                                .end_slot::<Label>(documentation_label),
 1198                        )
 1199                    })
 1200                    .collect()
 1201            },
 1202        )
 1203        .occlude()
 1204        .max_h(max_height)
 1205        .track_scroll(self.scroll_handle.clone())
 1206        .with_width_from_item(widest_completion_ix)
 1207        .with_sizing_behavior(ListSizingBehavior::Infer);
 1208
 1209        Popover::new()
 1210            .child(list)
 1211            .when_some(multiline_docs, |popover, multiline_docs| {
 1212                popover.aside(multiline_docs)
 1213            })
 1214            .into_any_element()
 1215    }
 1216
 1217    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1218        let mut matches = if let Some(query) = query {
 1219            fuzzy::match_strings(
 1220                &self.match_candidates,
 1221                query,
 1222                query.chars().any(|c| c.is_uppercase()),
 1223                100,
 1224                &Default::default(),
 1225                executor,
 1226            )
 1227            .await
 1228        } else {
 1229            self.match_candidates
 1230                .iter()
 1231                .enumerate()
 1232                .map(|(candidate_id, candidate)| StringMatch {
 1233                    candidate_id,
 1234                    score: Default::default(),
 1235                    positions: Default::default(),
 1236                    string: candidate.string.clone(),
 1237                })
 1238                .collect()
 1239        };
 1240
 1241        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1242        if let Some(query) = query {
 1243            if let Some(query_start) = query.chars().next() {
 1244                matches.retain(|string_match| {
 1245                    split_words(&string_match.string).any(|word| {
 1246                        // Check that the first codepoint of the word as lowercase matches the first
 1247                        // codepoint of the query as lowercase
 1248                        word.chars()
 1249                            .flat_map(|codepoint| codepoint.to_lowercase())
 1250                            .zip(query_start.to_lowercase())
 1251                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1252                    })
 1253                });
 1254            }
 1255        }
 1256
 1257        let completions = self.completions.read();
 1258        if self.sort_completions {
 1259            matches.sort_unstable_by_key(|mat| {
 1260                // We do want to strike a balance here between what the language server tells us
 1261                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1262                // `Creat` and there is a local variable called `CreateComponent`).
 1263                // So what we do is: we bucket all matches into two buckets
 1264                // - Strong matches
 1265                // - Weak matches
 1266                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1267                // and the Weak matches are the rest.
 1268                //
 1269                // For the strong matches, we sort by the language-servers score first and for the weak
 1270                // matches, we prefer our fuzzy finder first.
 1271                //
 1272                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1273                // us into account when it's obviously a bad match.
 1274
 1275                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1276                enum MatchScore<'a> {
 1277                    Strong {
 1278                        sort_text: Option<&'a str>,
 1279                        score: Reverse<OrderedFloat<f64>>,
 1280                        sort_key: (usize, &'a str),
 1281                    },
 1282                    Weak {
 1283                        score: Reverse<OrderedFloat<f64>>,
 1284                        sort_text: Option<&'a str>,
 1285                        sort_key: (usize, &'a str),
 1286                    },
 1287                }
 1288
 1289                let completion = &completions[mat.candidate_id];
 1290                let sort_key = completion.sort_key();
 1291                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1292                let score = Reverse(OrderedFloat(mat.score));
 1293
 1294                if mat.score >= 0.2 {
 1295                    MatchScore::Strong {
 1296                        sort_text,
 1297                        score,
 1298                        sort_key,
 1299                    }
 1300                } else {
 1301                    MatchScore::Weak {
 1302                        score,
 1303                        sort_text,
 1304                        sort_key,
 1305                    }
 1306                }
 1307            });
 1308        }
 1309
 1310        for mat in &mut matches {
 1311            let completion = &completions[mat.candidate_id];
 1312            mat.string.clone_from(&completion.label.text);
 1313            for position in &mut mat.positions {
 1314                *position += completion.label.filter_range.start;
 1315            }
 1316        }
 1317        drop(completions);
 1318
 1319        self.matches = matches.into();
 1320        self.selected_item = 0;
 1321    }
 1322}
 1323
 1324#[derive(Clone)]
 1325struct CodeActionContents {
 1326    tasks: Option<Arc<ResolvedTasks>>,
 1327    actions: Option<Arc<[CodeAction]>>,
 1328}
 1329
 1330impl CodeActionContents {
 1331    fn len(&self) -> usize {
 1332        match (&self.tasks, &self.actions) {
 1333            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1334            (Some(tasks), None) => tasks.templates.len(),
 1335            (None, Some(actions)) => actions.len(),
 1336            (None, None) => 0,
 1337        }
 1338    }
 1339
 1340    fn is_empty(&self) -> bool {
 1341        match (&self.tasks, &self.actions) {
 1342            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1343            (Some(tasks), None) => tasks.templates.is_empty(),
 1344            (None, Some(actions)) => actions.is_empty(),
 1345            (None, None) => true,
 1346        }
 1347    }
 1348
 1349    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1350        self.tasks
 1351            .iter()
 1352            .flat_map(|tasks| {
 1353                tasks
 1354                    .templates
 1355                    .iter()
 1356                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1357            })
 1358            .chain(self.actions.iter().flat_map(|actions| {
 1359                actions
 1360                    .iter()
 1361                    .map(|action| CodeActionsItem::CodeAction(action.clone()))
 1362            }))
 1363    }
 1364    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1365        match (&self.tasks, &self.actions) {
 1366            (Some(tasks), Some(actions)) => {
 1367                if index < tasks.templates.len() {
 1368                    tasks
 1369                        .templates
 1370                        .get(index)
 1371                        .cloned()
 1372                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1373                } else {
 1374                    actions
 1375                        .get(index - tasks.templates.len())
 1376                        .cloned()
 1377                        .map(CodeActionsItem::CodeAction)
 1378                }
 1379            }
 1380            (Some(tasks), None) => tasks
 1381                .templates
 1382                .get(index)
 1383                .cloned()
 1384                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1385            (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
 1386            (None, None) => None,
 1387        }
 1388    }
 1389}
 1390
 1391#[allow(clippy::large_enum_variant)]
 1392#[derive(Clone)]
 1393enum CodeActionsItem {
 1394    Task(TaskSourceKind, ResolvedTask),
 1395    CodeAction(CodeAction),
 1396}
 1397
 1398impl CodeActionsItem {
 1399    fn as_task(&self) -> Option<&ResolvedTask> {
 1400        let Self::Task(_, task) = self else {
 1401            return None;
 1402        };
 1403        Some(task)
 1404    }
 1405    fn as_code_action(&self) -> Option<&CodeAction> {
 1406        let Self::CodeAction(action) = self else {
 1407            return None;
 1408        };
 1409        Some(action)
 1410    }
 1411    fn label(&self) -> String {
 1412        match self {
 1413            Self::CodeAction(action) => action.lsp_action.title.clone(),
 1414            Self::Task(_, task) => task.resolved_label.clone(),
 1415        }
 1416    }
 1417}
 1418
 1419struct CodeActionsMenu {
 1420    actions: CodeActionContents,
 1421    buffer: Model<Buffer>,
 1422    selected_item: usize,
 1423    scroll_handle: UniformListScrollHandle,
 1424    deployed_from_indicator: Option<DisplayRow>,
 1425}
 1426
 1427impl CodeActionsMenu {
 1428    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1429        self.selected_item = 0;
 1430        self.scroll_handle.scroll_to_item(self.selected_item);
 1431        cx.notify()
 1432    }
 1433
 1434    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1435        if self.selected_item > 0 {
 1436            self.selected_item -= 1;
 1437        } else {
 1438            self.selected_item = self.actions.len() - 1;
 1439        }
 1440        self.scroll_handle.scroll_to_item(self.selected_item);
 1441        cx.notify();
 1442    }
 1443
 1444    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1445        if self.selected_item + 1 < self.actions.len() {
 1446            self.selected_item += 1;
 1447        } else {
 1448            self.selected_item = 0;
 1449        }
 1450        self.scroll_handle.scroll_to_item(self.selected_item);
 1451        cx.notify();
 1452    }
 1453
 1454    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1455        self.selected_item = self.actions.len() - 1;
 1456        self.scroll_handle.scroll_to_item(self.selected_item);
 1457        cx.notify()
 1458    }
 1459
 1460    fn visible(&self) -> bool {
 1461        !self.actions.is_empty()
 1462    }
 1463
 1464    fn render(
 1465        &self,
 1466        cursor_position: DisplayPoint,
 1467        _style: &EditorStyle,
 1468        max_height: Pixels,
 1469        cx: &mut ViewContext<Editor>,
 1470    ) -> (ContextMenuOrigin, AnyElement) {
 1471        let actions = self.actions.clone();
 1472        let selected_item = self.selected_item;
 1473        let element = uniform_list(
 1474            cx.view().clone(),
 1475            "code_actions_menu",
 1476            self.actions.len(),
 1477            move |_this, range, cx| {
 1478                actions
 1479                    .iter()
 1480                    .skip(range.start)
 1481                    .take(range.end - range.start)
 1482                    .enumerate()
 1483                    .map(|(ix, action)| {
 1484                        let item_ix = range.start + ix;
 1485                        let selected = selected_item == item_ix;
 1486                        let colors = cx.theme().colors();
 1487                        div()
 1488                            .px_2()
 1489                            .text_color(colors.text)
 1490                            .when(selected, |style| {
 1491                                style
 1492                                    .bg(colors.element_active)
 1493                                    .text_color(colors.text_accent)
 1494                            })
 1495                            .hover(|style| {
 1496                                style
 1497                                    .bg(colors.element_hover)
 1498                                    .text_color(colors.text_accent)
 1499                            })
 1500                            .whitespace_nowrap()
 1501                            .when_some(action.as_code_action(), |this, action| {
 1502                                this.on_mouse_down(
 1503                                    MouseButton::Left,
 1504                                    cx.listener(move |editor, _, cx| {
 1505                                        cx.stop_propagation();
 1506                                        if let Some(task) = editor.confirm_code_action(
 1507                                            &ConfirmCodeAction {
 1508                                                item_ix: Some(item_ix),
 1509                                            },
 1510                                            cx,
 1511                                        ) {
 1512                                            task.detach_and_log_err(cx)
 1513                                        }
 1514                                    }),
 1515                                )
 1516                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1517                                .child(SharedString::from(action.lsp_action.title.clone()))
 1518                            })
 1519                            .when_some(action.as_task(), |this, task| {
 1520                                this.on_mouse_down(
 1521                                    MouseButton::Left,
 1522                                    cx.listener(move |editor, _, cx| {
 1523                                        cx.stop_propagation();
 1524                                        if let Some(task) = editor.confirm_code_action(
 1525                                            &ConfirmCodeAction {
 1526                                                item_ix: Some(item_ix),
 1527                                            },
 1528                                            cx,
 1529                                        ) {
 1530                                            task.detach_and_log_err(cx)
 1531                                        }
 1532                                    }),
 1533                                )
 1534                                .child(SharedString::from(task.resolved_label.clone()))
 1535                            })
 1536                    })
 1537                    .collect()
 1538            },
 1539        )
 1540        .elevation_1(cx)
 1541        .px_2()
 1542        .py_1()
 1543        .max_h(max_height)
 1544        .occlude()
 1545        .track_scroll(self.scroll_handle.clone())
 1546        .with_width_from_item(
 1547            self.actions
 1548                .iter()
 1549                .enumerate()
 1550                .max_by_key(|(_, action)| match action {
 1551                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1552                    CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
 1553                })
 1554                .map(|(ix, _)| ix),
 1555        )
 1556        .with_sizing_behavior(ListSizingBehavior::Infer)
 1557        .into_any_element();
 1558
 1559        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1560            ContextMenuOrigin::GutterIndicator(row)
 1561        } else {
 1562            ContextMenuOrigin::EditorPoint(cursor_position)
 1563        };
 1564
 1565        (cursor_position, element)
 1566    }
 1567}
 1568
 1569#[derive(Debug)]
 1570struct ActiveDiagnosticGroup {
 1571    primary_range: Range<Anchor>,
 1572    primary_message: String,
 1573    group_id: usize,
 1574    blocks: HashMap<CustomBlockId, Diagnostic>,
 1575    is_valid: bool,
 1576}
 1577
 1578#[derive(Serialize, Deserialize, Clone, Debug)]
 1579pub struct ClipboardSelection {
 1580    pub len: usize,
 1581    pub is_entire_line: bool,
 1582    pub first_line_indent: u32,
 1583}
 1584
 1585#[derive(Debug)]
 1586pub(crate) struct NavigationData {
 1587    cursor_anchor: Anchor,
 1588    cursor_position: Point,
 1589    scroll_anchor: ScrollAnchor,
 1590    scroll_top_row: u32,
 1591}
 1592
 1593#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1594enum GotoDefinitionKind {
 1595    Symbol,
 1596    Declaration,
 1597    Type,
 1598    Implementation,
 1599}
 1600
 1601#[derive(Debug, Clone)]
 1602enum InlayHintRefreshReason {
 1603    Toggle(bool),
 1604    SettingsChange(InlayHintSettings),
 1605    NewLinesShown,
 1606    BufferEdited(HashSet<Arc<Language>>),
 1607    RefreshRequested,
 1608    ExcerptsRemoved(Vec<ExcerptId>),
 1609}
 1610
 1611impl InlayHintRefreshReason {
 1612    fn description(&self) -> &'static str {
 1613        match self {
 1614            Self::Toggle(_) => "toggle",
 1615            Self::SettingsChange(_) => "settings change",
 1616            Self::NewLinesShown => "new lines shown",
 1617            Self::BufferEdited(_) => "buffer edited",
 1618            Self::RefreshRequested => "refresh requested",
 1619            Self::ExcerptsRemoved(_) => "excerpts removed",
 1620        }
 1621    }
 1622}
 1623
 1624pub(crate) struct FocusedBlock {
 1625    id: BlockId,
 1626    focus_handle: WeakFocusHandle,
 1627}
 1628
 1629impl Editor {
 1630    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1631        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1632        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1633        Self::new(
 1634            EditorMode::SingleLine { auto_width: false },
 1635            buffer,
 1636            None,
 1637            false,
 1638            cx,
 1639        )
 1640    }
 1641
 1642    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1643        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1644        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1645        Self::new(EditorMode::Full, buffer, None, false, cx)
 1646    }
 1647
 1648    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1649        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1650        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1651        Self::new(
 1652            EditorMode::SingleLine { auto_width: true },
 1653            buffer,
 1654            None,
 1655            false,
 1656            cx,
 1657        )
 1658    }
 1659
 1660    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1661        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1662        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1663        Self::new(
 1664            EditorMode::AutoHeight { max_lines },
 1665            buffer,
 1666            None,
 1667            false,
 1668            cx,
 1669        )
 1670    }
 1671
 1672    pub fn for_buffer(
 1673        buffer: Model<Buffer>,
 1674        project: Option<Model<Project>>,
 1675        cx: &mut ViewContext<Self>,
 1676    ) -> Self {
 1677        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1678        Self::new(EditorMode::Full, buffer, project, false, cx)
 1679    }
 1680
 1681    pub fn for_multibuffer(
 1682        buffer: Model<MultiBuffer>,
 1683        project: Option<Model<Project>>,
 1684        show_excerpt_controls: bool,
 1685        cx: &mut ViewContext<Self>,
 1686    ) -> Self {
 1687        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1688    }
 1689
 1690    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1691        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1692        let mut clone = Self::new(
 1693            self.mode,
 1694            self.buffer.clone(),
 1695            self.project.clone(),
 1696            show_excerpt_controls,
 1697            cx,
 1698        );
 1699        self.display_map.update(cx, |display_map, cx| {
 1700            let snapshot = display_map.snapshot(cx);
 1701            clone.display_map.update(cx, |display_map, cx| {
 1702                display_map.set_state(&snapshot, cx);
 1703            });
 1704        });
 1705        clone.selections.clone_state(&self.selections);
 1706        clone.scroll_manager.clone_state(&self.scroll_manager);
 1707        clone.searchable = self.searchable;
 1708        clone
 1709    }
 1710
 1711    pub fn new(
 1712        mode: EditorMode,
 1713        buffer: Model<MultiBuffer>,
 1714        project: Option<Model<Project>>,
 1715        show_excerpt_controls: bool,
 1716        cx: &mut ViewContext<Self>,
 1717    ) -> Self {
 1718        let style = cx.text_style();
 1719        let font_size = style.font_size.to_pixels(cx.rem_size());
 1720        let editor = cx.view().downgrade();
 1721        let fold_placeholder = FoldPlaceholder {
 1722            constrain_width: true,
 1723            render: Arc::new(move |fold_id, fold_range, cx| {
 1724                let editor = editor.clone();
 1725                div()
 1726                    .id(fold_id)
 1727                    .bg(cx.theme().colors().ghost_element_background)
 1728                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1729                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1730                    .rounded_sm()
 1731                    .size_full()
 1732                    .cursor_pointer()
 1733                    .child("")
 1734                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1735                    .on_click(move |_, cx| {
 1736                        editor
 1737                            .update(cx, |editor, cx| {
 1738                                editor.unfold_ranges(
 1739                                    [fold_range.start..fold_range.end],
 1740                                    true,
 1741                                    false,
 1742                                    cx,
 1743                                );
 1744                                cx.stop_propagation();
 1745                            })
 1746                            .ok();
 1747                    })
 1748                    .into_any()
 1749            }),
 1750            merge_adjacent: true,
 1751        };
 1752        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1753        let display_map = cx.new_model(|cx| {
 1754            DisplayMap::new(
 1755                buffer.clone(),
 1756                style.font(),
 1757                font_size,
 1758                None,
 1759                show_excerpt_controls,
 1760                file_header_size,
 1761                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1762                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1763                fold_placeholder,
 1764                cx,
 1765            )
 1766        });
 1767
 1768        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1769
 1770        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1771
 1772        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1773            .then(|| language_settings::SoftWrap::PreferLine);
 1774
 1775        let mut project_subscriptions = Vec::new();
 1776        if mode == EditorMode::Full {
 1777            if let Some(project) = project.as_ref() {
 1778                if buffer.read(cx).is_singleton() {
 1779                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1780                        cx.emit(EditorEvent::TitleChanged);
 1781                    }));
 1782                }
 1783                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1784                    if let project::Event::RefreshInlayHints = event {
 1785                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1786                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1787                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1788                            let focus_handle = editor.focus_handle(cx);
 1789                            if focus_handle.is_focused(cx) {
 1790                                let snapshot = buffer.read(cx).snapshot();
 1791                                for (range, snippet) in snippet_edits {
 1792                                    let editor_range =
 1793                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1794                                    editor
 1795                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1796                                        .ok();
 1797                                }
 1798                            }
 1799                        }
 1800                    }
 1801                }));
 1802                let task_inventory = project.read(cx).task_inventory().clone();
 1803                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1804                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1805                }));
 1806            }
 1807        }
 1808
 1809        let inlay_hint_settings = inlay_hint_settings(
 1810            selections.newest_anchor().head(),
 1811            &buffer.read(cx).snapshot(cx),
 1812            cx,
 1813        );
 1814        let focus_handle = cx.focus_handle();
 1815        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1816        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1817            .detach();
 1818        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1819            .detach();
 1820        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1821
 1822        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1823            Some(false)
 1824        } else {
 1825            None
 1826        };
 1827
 1828        let mut this = Self {
 1829            focus_handle,
 1830            show_cursor_when_unfocused: false,
 1831            last_focused_descendant: None,
 1832            buffer: buffer.clone(),
 1833            display_map: display_map.clone(),
 1834            selections,
 1835            scroll_manager: ScrollManager::new(cx),
 1836            columnar_selection_tail: None,
 1837            add_selections_state: None,
 1838            select_next_state: None,
 1839            select_prev_state: None,
 1840            selection_history: Default::default(),
 1841            autoclose_regions: Default::default(),
 1842            snippet_stack: Default::default(),
 1843            select_larger_syntax_node_stack: Vec::new(),
 1844            ime_transaction: Default::default(),
 1845            active_diagnostics: None,
 1846            soft_wrap_mode_override,
 1847            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1848            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1849            project,
 1850            blink_manager: blink_manager.clone(),
 1851            show_local_selections: true,
 1852            mode,
 1853            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1854            show_gutter: mode == EditorMode::Full,
 1855            show_line_numbers: None,
 1856            show_git_diff_gutter: None,
 1857            show_code_actions: None,
 1858            show_runnables: None,
 1859            show_wrap_guides: None,
 1860            show_indent_guides,
 1861            placeholder_text: None,
 1862            highlight_order: 0,
 1863            highlighted_rows: HashMap::default(),
 1864            background_highlights: Default::default(),
 1865            gutter_highlights: TreeMap::default(),
 1866            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1867            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1868            nav_history: None,
 1869            context_menu: RwLock::new(None),
 1870            mouse_context_menu: None,
 1871            completion_tasks: Default::default(),
 1872            signature_help_state: SignatureHelpState::default(),
 1873            auto_signature_help: None,
 1874            find_all_references_task_sources: Vec::new(),
 1875            next_completion_id: 0,
 1876            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1877            next_inlay_id: 0,
 1878            available_code_actions: Default::default(),
 1879            code_actions_task: Default::default(),
 1880            document_highlights_task: Default::default(),
 1881            linked_editing_range_task: Default::default(),
 1882            pending_rename: Default::default(),
 1883            searchable: true,
 1884            cursor_shape: Default::default(),
 1885            current_line_highlight: None,
 1886            autoindent_mode: Some(AutoindentMode::EachLine),
 1887            collapse_matches: false,
 1888            workspace: None,
 1889            input_enabled: true,
 1890            use_modal_editing: mode == EditorMode::Full,
 1891            read_only: false,
 1892            use_autoclose: true,
 1893            use_auto_surround: true,
 1894            auto_replace_emoji_shortcode: false,
 1895            leader_peer_id: None,
 1896            remote_id: None,
 1897            hover_state: Default::default(),
 1898            hovered_link_state: Default::default(),
 1899            inline_completion_provider: None,
 1900            active_inline_completion: None,
 1901            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1902            expanded_hunks: ExpandedHunks::default(),
 1903            gutter_hovered: false,
 1904            pixel_position_of_newest_cursor: None,
 1905            last_bounds: None,
 1906            expect_bounds_change: None,
 1907            gutter_dimensions: GutterDimensions::default(),
 1908            style: None,
 1909            show_cursor_names: false,
 1910            hovered_cursors: Default::default(),
 1911            next_editor_action_id: EditorActionId::default(),
 1912            editor_actions: Rc::default(),
 1913            show_inline_completions: mode == EditorMode::Full,
 1914            custom_context_menu: None,
 1915            show_git_blame_gutter: false,
 1916            show_git_blame_inline: false,
 1917            show_selection_menu: None,
 1918            show_git_blame_inline_delay_task: None,
 1919            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1920            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1921                .session
 1922                .restore_unsaved_buffers,
 1923            blame: None,
 1924            blame_subscription: None,
 1925            file_header_size,
 1926            tasks: Default::default(),
 1927            _subscriptions: vec![
 1928                cx.observe(&buffer, Self::on_buffer_changed),
 1929                cx.subscribe(&buffer, Self::on_buffer_event),
 1930                cx.observe(&display_map, Self::on_display_map_changed),
 1931                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1932                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1933                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1934                cx.observe_window_activation(|editor, cx| {
 1935                    let active = cx.is_window_active();
 1936                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1937                        if active {
 1938                            blink_manager.enable(cx);
 1939                        } else {
 1940                            blink_manager.disable(cx);
 1941                        }
 1942                    });
 1943                }),
 1944            ],
 1945            tasks_update_task: None,
 1946            linked_edit_ranges: Default::default(),
 1947            previous_search_ranges: None,
 1948            breadcrumb_header: None,
 1949            focused_block: None,
 1950            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1951            addons: HashMap::default(),
 1952            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1953        };
 1954        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1955        this._subscriptions.extend(project_subscriptions);
 1956
 1957        this.end_selection(cx);
 1958        this.scroll_manager.show_scrollbar(cx);
 1959
 1960        if mode == EditorMode::Full {
 1961            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1962            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1963
 1964            if this.git_blame_inline_enabled {
 1965                this.git_blame_inline_enabled = true;
 1966                this.start_git_blame_inline(false, cx);
 1967            }
 1968        }
 1969
 1970        this.report_editor_event("open", None, cx);
 1971        this
 1972    }
 1973
 1974    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1975        self.mouse_context_menu
 1976            .as_ref()
 1977            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1978    }
 1979
 1980    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1981        let mut key_context = KeyContext::new_with_defaults();
 1982        key_context.add("Editor");
 1983        let mode = match self.mode {
 1984            EditorMode::SingleLine { .. } => "single_line",
 1985            EditorMode::AutoHeight { .. } => "auto_height",
 1986            EditorMode::Full => "full",
 1987        };
 1988
 1989        if EditorSettings::jupyter_enabled(cx) {
 1990            key_context.add("jupyter");
 1991        }
 1992
 1993        key_context.set("mode", mode);
 1994        if self.pending_rename.is_some() {
 1995            key_context.add("renaming");
 1996        }
 1997        if self.context_menu_visible() {
 1998            match self.context_menu.read().as_ref() {
 1999                Some(ContextMenu::Completions(_)) => {
 2000                    key_context.add("menu");
 2001                    key_context.add("showing_completions")
 2002                }
 2003                Some(ContextMenu::CodeActions(_)) => {
 2004                    key_context.add("menu");
 2005                    key_context.add("showing_code_actions")
 2006                }
 2007                None => {}
 2008            }
 2009        }
 2010
 2011        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2012        if !self.focus_handle(cx).contains_focused(cx)
 2013            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2014        {
 2015            for addon in self.addons.values() {
 2016                addon.extend_key_context(&mut key_context, cx)
 2017            }
 2018        }
 2019
 2020        if let Some(extension) = self
 2021            .buffer
 2022            .read(cx)
 2023            .as_singleton()
 2024            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2025        {
 2026            key_context.set("extension", extension.to_string());
 2027        }
 2028
 2029        if self.has_active_inline_completion(cx) {
 2030            key_context.add("copilot_suggestion");
 2031            key_context.add("inline_completion");
 2032        }
 2033
 2034        key_context
 2035    }
 2036
 2037    pub fn new_file(
 2038        workspace: &mut Workspace,
 2039        _: &workspace::NewFile,
 2040        cx: &mut ViewContext<Workspace>,
 2041    ) {
 2042        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2043            "Failed to create buffer",
 2044            cx,
 2045            |e, _| match e.error_code() {
 2046                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2047                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2048                e.error_tag("required").unwrap_or("the latest version")
 2049            )),
 2050                _ => None,
 2051            },
 2052        );
 2053    }
 2054
 2055    pub fn new_in_workspace(
 2056        workspace: &mut Workspace,
 2057        cx: &mut ViewContext<Workspace>,
 2058    ) -> Task<Result<View<Editor>>> {
 2059        let project = workspace.project().clone();
 2060        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2061
 2062        cx.spawn(|workspace, mut cx| async move {
 2063            let buffer = create.await?;
 2064            workspace.update(&mut cx, |workspace, cx| {
 2065                let editor =
 2066                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2067                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2068                editor
 2069            })
 2070        })
 2071    }
 2072
 2073    fn new_file_vertical(
 2074        workspace: &mut Workspace,
 2075        _: &workspace::NewFileSplitVertical,
 2076        cx: &mut ViewContext<Workspace>,
 2077    ) {
 2078        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2079    }
 2080
 2081    fn new_file_horizontal(
 2082        workspace: &mut Workspace,
 2083        _: &workspace::NewFileSplitHorizontal,
 2084        cx: &mut ViewContext<Workspace>,
 2085    ) {
 2086        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2087    }
 2088
 2089    fn new_file_in_direction(
 2090        workspace: &mut Workspace,
 2091        direction: SplitDirection,
 2092        cx: &mut ViewContext<Workspace>,
 2093    ) {
 2094        let project = workspace.project().clone();
 2095        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2096
 2097        cx.spawn(|workspace, mut cx| async move {
 2098            let buffer = create.await?;
 2099            workspace.update(&mut cx, move |workspace, cx| {
 2100                workspace.split_item(
 2101                    direction,
 2102                    Box::new(
 2103                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2104                    ),
 2105                    cx,
 2106                )
 2107            })?;
 2108            anyhow::Ok(())
 2109        })
 2110        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2111            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2112                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2113                e.error_tag("required").unwrap_or("the latest version")
 2114            )),
 2115            _ => None,
 2116        });
 2117    }
 2118
 2119    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 2120        self.buffer.read(cx).replica_id()
 2121    }
 2122
 2123    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2124        self.leader_peer_id
 2125    }
 2126
 2127    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2128        &self.buffer
 2129    }
 2130
 2131    pub fn workspace(&self) -> Option<View<Workspace>> {
 2132        self.workspace.as_ref()?.0.upgrade()
 2133    }
 2134
 2135    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2136        self.buffer().read(cx).title(cx)
 2137    }
 2138
 2139    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2140        EditorSnapshot {
 2141            mode: self.mode,
 2142            show_gutter: self.show_gutter,
 2143            show_line_numbers: self.show_line_numbers,
 2144            show_git_diff_gutter: self.show_git_diff_gutter,
 2145            show_code_actions: self.show_code_actions,
 2146            show_runnables: self.show_runnables,
 2147            render_git_blame_gutter: self.render_git_blame_gutter(cx),
 2148            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2149            scroll_anchor: self.scroll_manager.anchor(),
 2150            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2151            placeholder_text: self.placeholder_text.clone(),
 2152            is_focused: self.focus_handle.is_focused(cx),
 2153            current_line_highlight: self
 2154                .current_line_highlight
 2155                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2156            gutter_hovered: self.gutter_hovered,
 2157        }
 2158    }
 2159
 2160    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2161        self.buffer.read(cx).language_at(point, cx)
 2162    }
 2163
 2164    pub fn file_at<T: ToOffset>(
 2165        &self,
 2166        point: T,
 2167        cx: &AppContext,
 2168    ) -> Option<Arc<dyn language::File>> {
 2169        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2170    }
 2171
 2172    pub fn active_excerpt(
 2173        &self,
 2174        cx: &AppContext,
 2175    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2176        self.buffer
 2177            .read(cx)
 2178            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2179    }
 2180
 2181    pub fn mode(&self) -> EditorMode {
 2182        self.mode
 2183    }
 2184
 2185    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2186        self.collaboration_hub.as_deref()
 2187    }
 2188
 2189    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2190        self.collaboration_hub = Some(hub);
 2191    }
 2192
 2193    pub fn set_custom_context_menu(
 2194        &mut self,
 2195        f: impl 'static
 2196            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2197    ) {
 2198        self.custom_context_menu = Some(Box::new(f))
 2199    }
 2200
 2201    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2202        self.completion_provider = Some(provider);
 2203    }
 2204
 2205    pub fn set_inline_completion_provider<T>(
 2206        &mut self,
 2207        provider: Option<Model<T>>,
 2208        cx: &mut ViewContext<Self>,
 2209    ) where
 2210        T: InlineCompletionProvider,
 2211    {
 2212        self.inline_completion_provider =
 2213            provider.map(|provider| RegisteredInlineCompletionProvider {
 2214                _subscription: cx.observe(&provider, |this, _, cx| {
 2215                    if this.focus_handle.is_focused(cx) {
 2216                        this.update_visible_inline_completion(cx);
 2217                    }
 2218                }),
 2219                provider: Arc::new(provider),
 2220            });
 2221        self.refresh_inline_completion(false, false, cx);
 2222    }
 2223
 2224    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2225        self.placeholder_text.as_deref()
 2226    }
 2227
 2228    pub fn set_placeholder_text(
 2229        &mut self,
 2230        placeholder_text: impl Into<Arc<str>>,
 2231        cx: &mut ViewContext<Self>,
 2232    ) {
 2233        let placeholder_text = Some(placeholder_text.into());
 2234        if self.placeholder_text != placeholder_text {
 2235            self.placeholder_text = placeholder_text;
 2236            cx.notify();
 2237        }
 2238    }
 2239
 2240    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2241        self.cursor_shape = cursor_shape;
 2242
 2243        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2244        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2245
 2246        cx.notify();
 2247    }
 2248
 2249    pub fn set_current_line_highlight(
 2250        &mut self,
 2251        current_line_highlight: Option<CurrentLineHighlight>,
 2252    ) {
 2253        self.current_line_highlight = current_line_highlight;
 2254    }
 2255
 2256    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2257        self.collapse_matches = collapse_matches;
 2258    }
 2259
 2260    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2261        if self.collapse_matches {
 2262            return range.start..range.start;
 2263        }
 2264        range.clone()
 2265    }
 2266
 2267    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2268        if self.display_map.read(cx).clip_at_line_ends != clip {
 2269            self.display_map
 2270                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2271        }
 2272    }
 2273
 2274    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2275        self.input_enabled = input_enabled;
 2276    }
 2277
 2278    pub fn set_autoindent(&mut self, autoindent: bool) {
 2279        if autoindent {
 2280            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2281        } else {
 2282            self.autoindent_mode = None;
 2283        }
 2284    }
 2285
 2286    pub fn read_only(&self, cx: &AppContext) -> bool {
 2287        self.read_only || self.buffer.read(cx).read_only()
 2288    }
 2289
 2290    pub fn set_read_only(&mut self, read_only: bool) {
 2291        self.read_only = read_only;
 2292    }
 2293
 2294    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2295        self.use_autoclose = autoclose;
 2296    }
 2297
 2298    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2299        self.use_auto_surround = auto_surround;
 2300    }
 2301
 2302    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2303        self.auto_replace_emoji_shortcode = auto_replace;
 2304    }
 2305
 2306    pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
 2307        self.show_inline_completions = show_inline_completions;
 2308    }
 2309
 2310    pub fn set_use_modal_editing(&mut self, to: bool) {
 2311        self.use_modal_editing = to;
 2312    }
 2313
 2314    pub fn use_modal_editing(&self) -> bool {
 2315        self.use_modal_editing
 2316    }
 2317
 2318    fn selections_did_change(
 2319        &mut self,
 2320        local: bool,
 2321        old_cursor_position: &Anchor,
 2322        show_completions: bool,
 2323        cx: &mut ViewContext<Self>,
 2324    ) {
 2325        // Copy selections to primary selection buffer
 2326        #[cfg(target_os = "linux")]
 2327        if local {
 2328            let selections = self.selections.all::<usize>(cx);
 2329            let buffer_handle = self.buffer.read(cx).read(cx);
 2330
 2331            let mut text = String::new();
 2332            for (index, selection) in selections.iter().enumerate() {
 2333                let text_for_selection = buffer_handle
 2334                    .text_for_range(selection.start..selection.end)
 2335                    .collect::<String>();
 2336
 2337                text.push_str(&text_for_selection);
 2338                if index != selections.len() - 1 {
 2339                    text.push('\n');
 2340                }
 2341            }
 2342
 2343            if !text.is_empty() {
 2344                cx.write_to_primary(ClipboardItem::new_string(text));
 2345            }
 2346        }
 2347
 2348        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2349            self.buffer.update(cx, |buffer, cx| {
 2350                buffer.set_active_selections(
 2351                    &self.selections.disjoint_anchors(),
 2352                    self.selections.line_mode,
 2353                    self.cursor_shape,
 2354                    cx,
 2355                )
 2356            });
 2357        }
 2358        let display_map = self
 2359            .display_map
 2360            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2361        let buffer = &display_map.buffer_snapshot;
 2362        self.add_selections_state = None;
 2363        self.select_next_state = None;
 2364        self.select_prev_state = None;
 2365        self.select_larger_syntax_node_stack.clear();
 2366        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2367        self.snippet_stack
 2368            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2369        self.take_rename(false, cx);
 2370
 2371        let new_cursor_position = self.selections.newest_anchor().head();
 2372
 2373        self.push_to_nav_history(
 2374            *old_cursor_position,
 2375            Some(new_cursor_position.to_point(buffer)),
 2376            cx,
 2377        );
 2378
 2379        if local {
 2380            let new_cursor_position = self.selections.newest_anchor().head();
 2381            let mut context_menu = self.context_menu.write();
 2382            let completion_menu = match context_menu.as_ref() {
 2383                Some(ContextMenu::Completions(menu)) => Some(menu),
 2384
 2385                _ => {
 2386                    *context_menu = None;
 2387                    None
 2388                }
 2389            };
 2390
 2391            if let Some(completion_menu) = completion_menu {
 2392                let cursor_position = new_cursor_position.to_offset(buffer);
 2393                let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
 2394                if kind == Some(CharKind::Word)
 2395                    && word_range.to_inclusive().contains(&cursor_position)
 2396                {
 2397                    let mut completion_menu = completion_menu.clone();
 2398                    drop(context_menu);
 2399
 2400                    let query = Self::completion_query(buffer, cursor_position);
 2401                    cx.spawn(move |this, mut cx| async move {
 2402                        completion_menu
 2403                            .filter(query.as_deref(), cx.background_executor().clone())
 2404                            .await;
 2405
 2406                        this.update(&mut cx, |this, cx| {
 2407                            let mut context_menu = this.context_menu.write();
 2408                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2409                                return;
 2410                            };
 2411
 2412                            if menu.id > completion_menu.id {
 2413                                return;
 2414                            }
 2415
 2416                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2417                            drop(context_menu);
 2418                            cx.notify();
 2419                        })
 2420                    })
 2421                    .detach();
 2422
 2423                    if show_completions {
 2424                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2425                    }
 2426                } else {
 2427                    drop(context_menu);
 2428                    self.hide_context_menu(cx);
 2429                }
 2430            } else {
 2431                drop(context_menu);
 2432            }
 2433
 2434            hide_hover(self, cx);
 2435
 2436            if old_cursor_position.to_display_point(&display_map).row()
 2437                != new_cursor_position.to_display_point(&display_map).row()
 2438            {
 2439                self.available_code_actions.take();
 2440            }
 2441            self.refresh_code_actions(cx);
 2442            self.refresh_document_highlights(cx);
 2443            refresh_matching_bracket_highlights(self, cx);
 2444            self.discard_inline_completion(false, cx);
 2445            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2446            if self.git_blame_inline_enabled {
 2447                self.start_inline_blame_timer(cx);
 2448            }
 2449        }
 2450
 2451        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2452        cx.emit(EditorEvent::SelectionsChanged { local });
 2453
 2454        if self.selections.disjoint_anchors().len() == 1 {
 2455            cx.emit(SearchEvent::ActiveMatchChanged)
 2456        }
 2457        cx.notify();
 2458    }
 2459
 2460    pub fn change_selections<R>(
 2461        &mut self,
 2462        autoscroll: Option<Autoscroll>,
 2463        cx: &mut ViewContext<Self>,
 2464        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2465    ) -> R {
 2466        self.change_selections_inner(autoscroll, true, cx, change)
 2467    }
 2468
 2469    pub fn change_selections_inner<R>(
 2470        &mut self,
 2471        autoscroll: Option<Autoscroll>,
 2472        request_completions: bool,
 2473        cx: &mut ViewContext<Self>,
 2474        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2475    ) -> R {
 2476        let old_cursor_position = self.selections.newest_anchor().head();
 2477        self.push_to_selection_history();
 2478
 2479        let (changed, result) = self.selections.change_with(cx, change);
 2480
 2481        if changed {
 2482            if let Some(autoscroll) = autoscroll {
 2483                self.request_autoscroll(autoscroll, cx);
 2484            }
 2485            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2486
 2487            if self.should_open_signature_help_automatically(
 2488                &old_cursor_position,
 2489                self.signature_help_state.backspace_pressed(),
 2490                cx,
 2491            ) {
 2492                self.show_signature_help(&ShowSignatureHelp, cx);
 2493            }
 2494            self.signature_help_state.set_backspace_pressed(false);
 2495        }
 2496
 2497        result
 2498    }
 2499
 2500    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2501    where
 2502        I: IntoIterator<Item = (Range<S>, T)>,
 2503        S: ToOffset,
 2504        T: Into<Arc<str>>,
 2505    {
 2506        if self.read_only(cx) {
 2507            return;
 2508        }
 2509
 2510        self.buffer
 2511            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2512    }
 2513
 2514    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2515    where
 2516        I: IntoIterator<Item = (Range<S>, T)>,
 2517        S: ToOffset,
 2518        T: Into<Arc<str>>,
 2519    {
 2520        if self.read_only(cx) {
 2521            return;
 2522        }
 2523
 2524        self.buffer.update(cx, |buffer, cx| {
 2525            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2526        });
 2527    }
 2528
 2529    pub fn edit_with_block_indent<I, S, T>(
 2530        &mut self,
 2531        edits: I,
 2532        original_indent_columns: Vec<u32>,
 2533        cx: &mut ViewContext<Self>,
 2534    ) where
 2535        I: IntoIterator<Item = (Range<S>, T)>,
 2536        S: ToOffset,
 2537        T: Into<Arc<str>>,
 2538    {
 2539        if self.read_only(cx) {
 2540            return;
 2541        }
 2542
 2543        self.buffer.update(cx, |buffer, cx| {
 2544            buffer.edit(
 2545                edits,
 2546                Some(AutoindentMode::Block {
 2547                    original_indent_columns,
 2548                }),
 2549                cx,
 2550            )
 2551        });
 2552    }
 2553
 2554    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2555        self.hide_context_menu(cx);
 2556
 2557        match phase {
 2558            SelectPhase::Begin {
 2559                position,
 2560                add,
 2561                click_count,
 2562            } => self.begin_selection(position, add, click_count, cx),
 2563            SelectPhase::BeginColumnar {
 2564                position,
 2565                goal_column,
 2566                reset,
 2567            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2568            SelectPhase::Extend {
 2569                position,
 2570                click_count,
 2571            } => self.extend_selection(position, click_count, cx),
 2572            SelectPhase::Update {
 2573                position,
 2574                goal_column,
 2575                scroll_delta,
 2576            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2577            SelectPhase::End => self.end_selection(cx),
 2578        }
 2579    }
 2580
 2581    fn extend_selection(
 2582        &mut self,
 2583        position: DisplayPoint,
 2584        click_count: usize,
 2585        cx: &mut ViewContext<Self>,
 2586    ) {
 2587        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2588        let tail = self.selections.newest::<usize>(cx).tail();
 2589        self.begin_selection(position, false, click_count, cx);
 2590
 2591        let position = position.to_offset(&display_map, Bias::Left);
 2592        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2593
 2594        let mut pending_selection = self
 2595            .selections
 2596            .pending_anchor()
 2597            .expect("extend_selection not called with pending selection");
 2598        if position >= tail {
 2599            pending_selection.start = tail_anchor;
 2600        } else {
 2601            pending_selection.end = tail_anchor;
 2602            pending_selection.reversed = true;
 2603        }
 2604
 2605        let mut pending_mode = self.selections.pending_mode().unwrap();
 2606        match &mut pending_mode {
 2607            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2608            _ => {}
 2609        }
 2610
 2611        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2612            s.set_pending(pending_selection, pending_mode)
 2613        });
 2614    }
 2615
 2616    fn begin_selection(
 2617        &mut self,
 2618        position: DisplayPoint,
 2619        add: bool,
 2620        click_count: usize,
 2621        cx: &mut ViewContext<Self>,
 2622    ) {
 2623        if !self.focus_handle.is_focused(cx) {
 2624            self.last_focused_descendant = None;
 2625            cx.focus(&self.focus_handle);
 2626        }
 2627
 2628        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2629        let buffer = &display_map.buffer_snapshot;
 2630        let newest_selection = self.selections.newest_anchor().clone();
 2631        let position = display_map.clip_point(position, Bias::Left);
 2632
 2633        let start;
 2634        let end;
 2635        let mode;
 2636        let auto_scroll;
 2637        match click_count {
 2638            1 => {
 2639                start = buffer.anchor_before(position.to_point(&display_map));
 2640                end = start;
 2641                mode = SelectMode::Character;
 2642                auto_scroll = true;
 2643            }
 2644            2 => {
 2645                let range = movement::surrounding_word(&display_map, position);
 2646                start = buffer.anchor_before(range.start.to_point(&display_map));
 2647                end = buffer.anchor_before(range.end.to_point(&display_map));
 2648                mode = SelectMode::Word(start..end);
 2649                auto_scroll = true;
 2650            }
 2651            3 => {
 2652                let position = display_map
 2653                    .clip_point(position, Bias::Left)
 2654                    .to_point(&display_map);
 2655                let line_start = display_map.prev_line_boundary(position).0;
 2656                let next_line_start = buffer.clip_point(
 2657                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2658                    Bias::Left,
 2659                );
 2660                start = buffer.anchor_before(line_start);
 2661                end = buffer.anchor_before(next_line_start);
 2662                mode = SelectMode::Line(start..end);
 2663                auto_scroll = true;
 2664            }
 2665            _ => {
 2666                start = buffer.anchor_before(0);
 2667                end = buffer.anchor_before(buffer.len());
 2668                mode = SelectMode::All;
 2669                auto_scroll = false;
 2670            }
 2671        }
 2672
 2673        let point_to_delete: Option<usize> = {
 2674            let selected_points: Vec<Selection<Point>> =
 2675                self.selections.disjoint_in_range(start..end, cx);
 2676
 2677            if !add || click_count > 1 {
 2678                None
 2679            } else if selected_points.len() > 0 {
 2680                Some(selected_points[0].id)
 2681            } else {
 2682                let clicked_point_already_selected =
 2683                    self.selections.disjoint.iter().find(|selection| {
 2684                        selection.start.to_point(buffer) == start.to_point(buffer)
 2685                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2686                    });
 2687
 2688                if let Some(selection) = clicked_point_already_selected {
 2689                    Some(selection.id)
 2690                } else {
 2691                    None
 2692                }
 2693            }
 2694        };
 2695
 2696        let selections_count = self.selections.count();
 2697
 2698        self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
 2699            if let Some(point_to_delete) = point_to_delete {
 2700                s.delete(point_to_delete);
 2701
 2702                if selections_count == 1 {
 2703                    s.set_pending_anchor_range(start..end, mode);
 2704                }
 2705            } else {
 2706                if !add {
 2707                    s.clear_disjoint();
 2708                } else if click_count > 1 {
 2709                    s.delete(newest_selection.id)
 2710                }
 2711
 2712                s.set_pending_anchor_range(start..end, mode);
 2713            }
 2714        });
 2715    }
 2716
 2717    fn begin_columnar_selection(
 2718        &mut self,
 2719        position: DisplayPoint,
 2720        goal_column: u32,
 2721        reset: bool,
 2722        cx: &mut ViewContext<Self>,
 2723    ) {
 2724        if !self.focus_handle.is_focused(cx) {
 2725            self.last_focused_descendant = None;
 2726            cx.focus(&self.focus_handle);
 2727        }
 2728
 2729        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2730
 2731        if reset {
 2732            let pointer_position = display_map
 2733                .buffer_snapshot
 2734                .anchor_before(position.to_point(&display_map));
 2735
 2736            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2737                s.clear_disjoint();
 2738                s.set_pending_anchor_range(
 2739                    pointer_position..pointer_position,
 2740                    SelectMode::Character,
 2741                );
 2742            });
 2743        }
 2744
 2745        let tail = self.selections.newest::<Point>(cx).tail();
 2746        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2747
 2748        if !reset {
 2749            self.select_columns(
 2750                tail.to_display_point(&display_map),
 2751                position,
 2752                goal_column,
 2753                &display_map,
 2754                cx,
 2755            );
 2756        }
 2757    }
 2758
 2759    fn update_selection(
 2760        &mut self,
 2761        position: DisplayPoint,
 2762        goal_column: u32,
 2763        scroll_delta: gpui::Point<f32>,
 2764        cx: &mut ViewContext<Self>,
 2765    ) {
 2766        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2767
 2768        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2769            let tail = tail.to_display_point(&display_map);
 2770            self.select_columns(tail, position, goal_column, &display_map, cx);
 2771        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2772            let buffer = self.buffer.read(cx).snapshot(cx);
 2773            let head;
 2774            let tail;
 2775            let mode = self.selections.pending_mode().unwrap();
 2776            match &mode {
 2777                SelectMode::Character => {
 2778                    head = position.to_point(&display_map);
 2779                    tail = pending.tail().to_point(&buffer);
 2780                }
 2781                SelectMode::Word(original_range) => {
 2782                    let original_display_range = original_range.start.to_display_point(&display_map)
 2783                        ..original_range.end.to_display_point(&display_map);
 2784                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2785                        ..original_display_range.end.to_point(&display_map);
 2786                    if movement::is_inside_word(&display_map, position)
 2787                        || original_display_range.contains(&position)
 2788                    {
 2789                        let word_range = movement::surrounding_word(&display_map, position);
 2790                        if word_range.start < original_display_range.start {
 2791                            head = word_range.start.to_point(&display_map);
 2792                        } else {
 2793                            head = word_range.end.to_point(&display_map);
 2794                        }
 2795                    } else {
 2796                        head = position.to_point(&display_map);
 2797                    }
 2798
 2799                    if head <= original_buffer_range.start {
 2800                        tail = original_buffer_range.end;
 2801                    } else {
 2802                        tail = original_buffer_range.start;
 2803                    }
 2804                }
 2805                SelectMode::Line(original_range) => {
 2806                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2807
 2808                    let position = display_map
 2809                        .clip_point(position, Bias::Left)
 2810                        .to_point(&display_map);
 2811                    let line_start = display_map.prev_line_boundary(position).0;
 2812                    let next_line_start = buffer.clip_point(
 2813                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2814                        Bias::Left,
 2815                    );
 2816
 2817                    if line_start < original_range.start {
 2818                        head = line_start
 2819                    } else {
 2820                        head = next_line_start
 2821                    }
 2822
 2823                    if head <= original_range.start {
 2824                        tail = original_range.end;
 2825                    } else {
 2826                        tail = original_range.start;
 2827                    }
 2828                }
 2829                SelectMode::All => {
 2830                    return;
 2831                }
 2832            };
 2833
 2834            if head < tail {
 2835                pending.start = buffer.anchor_before(head);
 2836                pending.end = buffer.anchor_before(tail);
 2837                pending.reversed = true;
 2838            } else {
 2839                pending.start = buffer.anchor_before(tail);
 2840                pending.end = buffer.anchor_before(head);
 2841                pending.reversed = false;
 2842            }
 2843
 2844            self.change_selections(None, cx, |s| {
 2845                s.set_pending(pending, mode);
 2846            });
 2847        } else {
 2848            log::error!("update_selection dispatched with no pending selection");
 2849            return;
 2850        }
 2851
 2852        self.apply_scroll_delta(scroll_delta, cx);
 2853        cx.notify();
 2854    }
 2855
 2856    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2857        self.columnar_selection_tail.take();
 2858        if self.selections.pending_anchor().is_some() {
 2859            let selections = self.selections.all::<usize>(cx);
 2860            self.change_selections(None, cx, |s| {
 2861                s.select(selections);
 2862                s.clear_pending();
 2863            });
 2864        }
 2865    }
 2866
 2867    fn select_columns(
 2868        &mut self,
 2869        tail: DisplayPoint,
 2870        head: DisplayPoint,
 2871        goal_column: u32,
 2872        display_map: &DisplaySnapshot,
 2873        cx: &mut ViewContext<Self>,
 2874    ) {
 2875        let start_row = cmp::min(tail.row(), head.row());
 2876        let end_row = cmp::max(tail.row(), head.row());
 2877        let start_column = cmp::min(tail.column(), goal_column);
 2878        let end_column = cmp::max(tail.column(), goal_column);
 2879        let reversed = start_column < tail.column();
 2880
 2881        let selection_ranges = (start_row.0..=end_row.0)
 2882            .map(DisplayRow)
 2883            .filter_map(|row| {
 2884                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2885                    let start = display_map
 2886                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2887                        .to_point(display_map);
 2888                    let end = display_map
 2889                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2890                        .to_point(display_map);
 2891                    if reversed {
 2892                        Some(end..start)
 2893                    } else {
 2894                        Some(start..end)
 2895                    }
 2896                } else {
 2897                    None
 2898                }
 2899            })
 2900            .collect::<Vec<_>>();
 2901
 2902        self.change_selections(None, cx, |s| {
 2903            s.select_ranges(selection_ranges);
 2904        });
 2905        cx.notify();
 2906    }
 2907
 2908    pub fn has_pending_nonempty_selection(&self) -> bool {
 2909        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2910            Some(Selection { start, end, .. }) => start != end,
 2911            None => false,
 2912        };
 2913
 2914        pending_nonempty_selection
 2915            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2916    }
 2917
 2918    pub fn has_pending_selection(&self) -> bool {
 2919        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2920    }
 2921
 2922    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2923        if self.clear_clicked_diff_hunks(cx) {
 2924            cx.notify();
 2925            return;
 2926        }
 2927        if self.dismiss_menus_and_popups(true, cx) {
 2928            return;
 2929        }
 2930
 2931        if self.mode == EditorMode::Full {
 2932            if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
 2933                return;
 2934            }
 2935        }
 2936
 2937        cx.propagate();
 2938    }
 2939
 2940    pub fn dismiss_menus_and_popups(
 2941        &mut self,
 2942        should_report_inline_completion_event: bool,
 2943        cx: &mut ViewContext<Self>,
 2944    ) -> bool {
 2945        if self.take_rename(false, cx).is_some() {
 2946            return true;
 2947        }
 2948
 2949        if hide_hover(self, cx) {
 2950            return true;
 2951        }
 2952
 2953        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2954            return true;
 2955        }
 2956
 2957        if self.hide_context_menu(cx).is_some() {
 2958            return true;
 2959        }
 2960
 2961        if self.mouse_context_menu.take().is_some() {
 2962            return true;
 2963        }
 2964
 2965        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2966            return true;
 2967        }
 2968
 2969        if self.snippet_stack.pop().is_some() {
 2970            return true;
 2971        }
 2972
 2973        if self.mode == EditorMode::Full {
 2974            if self.active_diagnostics.is_some() {
 2975                self.dismiss_diagnostics(cx);
 2976                return true;
 2977            }
 2978        }
 2979
 2980        false
 2981    }
 2982
 2983    fn linked_editing_ranges_for(
 2984        &self,
 2985        selection: Range<text::Anchor>,
 2986        cx: &AppContext,
 2987    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2988        if self.linked_edit_ranges.is_empty() {
 2989            return None;
 2990        }
 2991        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2992            selection.end.buffer_id.and_then(|end_buffer_id| {
 2993                if selection.start.buffer_id != Some(end_buffer_id) {
 2994                    return None;
 2995                }
 2996                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2997                let snapshot = buffer.read(cx).snapshot();
 2998                self.linked_edit_ranges
 2999                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3000                    .map(|ranges| (ranges, snapshot, buffer))
 3001            })?;
 3002        use text::ToOffset as TO;
 3003        // find offset from the start of current range to current cursor position
 3004        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3005
 3006        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3007        let start_difference = start_offset - start_byte_offset;
 3008        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3009        let end_difference = end_offset - start_byte_offset;
 3010        // Current range has associated linked ranges.
 3011        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3012        for range in linked_ranges.iter() {
 3013            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3014            let end_offset = start_offset + end_difference;
 3015            let start_offset = start_offset + start_difference;
 3016            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3017                continue;
 3018            }
 3019            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3020                if s.start.buffer_id != selection.start.buffer_id
 3021                    || s.end.buffer_id != selection.end.buffer_id
 3022                {
 3023                    return false;
 3024                }
 3025                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3026                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3027            }) {
 3028                continue;
 3029            }
 3030            let start = buffer_snapshot.anchor_after(start_offset);
 3031            let end = buffer_snapshot.anchor_after(end_offset);
 3032            linked_edits
 3033                .entry(buffer.clone())
 3034                .or_default()
 3035                .push(start..end);
 3036        }
 3037        Some(linked_edits)
 3038    }
 3039
 3040    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3041        let text: Arc<str> = text.into();
 3042
 3043        if self.read_only(cx) {
 3044            return;
 3045        }
 3046
 3047        let selections = self.selections.all_adjusted(cx);
 3048        let mut bracket_inserted = false;
 3049        let mut edits = Vec::new();
 3050        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3051        let mut new_selections = Vec::with_capacity(selections.len());
 3052        let mut new_autoclose_regions = Vec::new();
 3053        let snapshot = self.buffer.read(cx).read(cx);
 3054
 3055        for (selection, autoclose_region) in
 3056            self.selections_with_autoclose_regions(selections, &snapshot)
 3057        {
 3058            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3059                // Determine if the inserted text matches the opening or closing
 3060                // bracket of any of this language's bracket pairs.
 3061                let mut bracket_pair = None;
 3062                let mut is_bracket_pair_start = false;
 3063                let mut is_bracket_pair_end = false;
 3064                if !text.is_empty() {
 3065                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3066                    //  and they are removing the character that triggered IME popup.
 3067                    for (pair, enabled) in scope.brackets() {
 3068                        if !pair.close && !pair.surround {
 3069                            continue;
 3070                        }
 3071
 3072                        if enabled && pair.start.ends_with(text.as_ref()) {
 3073                            bracket_pair = Some(pair.clone());
 3074                            is_bracket_pair_start = true;
 3075                            break;
 3076                        }
 3077                        if pair.end.as_str() == text.as_ref() {
 3078                            bracket_pair = Some(pair.clone());
 3079                            is_bracket_pair_end = true;
 3080                            break;
 3081                        }
 3082                    }
 3083                }
 3084
 3085                if let Some(bracket_pair) = bracket_pair {
 3086                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3087                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3088                    let auto_surround =
 3089                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3090                    if selection.is_empty() {
 3091                        if is_bracket_pair_start {
 3092                            let prefix_len = bracket_pair.start.len() - text.len();
 3093
 3094                            // If the inserted text is a suffix of an opening bracket and the
 3095                            // selection is preceded by the rest of the opening bracket, then
 3096                            // insert the closing bracket.
 3097                            let following_text_allows_autoclose = snapshot
 3098                                .chars_at(selection.start)
 3099                                .next()
 3100                                .map_or(true, |c| scope.should_autoclose_before(c));
 3101                            let preceding_text_matches_prefix = prefix_len == 0
 3102                                || (selection.start.column >= (prefix_len as u32)
 3103                                    && snapshot.contains_str_at(
 3104                                        Point::new(
 3105                                            selection.start.row,
 3106                                            selection.start.column - (prefix_len as u32),
 3107                                        ),
 3108                                        &bracket_pair.start[..prefix_len],
 3109                                    ));
 3110
 3111                            if autoclose
 3112                                && bracket_pair.close
 3113                                && following_text_allows_autoclose
 3114                                && preceding_text_matches_prefix
 3115                            {
 3116                                let anchor = snapshot.anchor_before(selection.end);
 3117                                new_selections.push((selection.map(|_| anchor), text.len()));
 3118                                new_autoclose_regions.push((
 3119                                    anchor,
 3120                                    text.len(),
 3121                                    selection.id,
 3122                                    bracket_pair.clone(),
 3123                                ));
 3124                                edits.push((
 3125                                    selection.range(),
 3126                                    format!("{}{}", text, bracket_pair.end).into(),
 3127                                ));
 3128                                bracket_inserted = true;
 3129                                continue;
 3130                            }
 3131                        }
 3132
 3133                        if let Some(region) = autoclose_region {
 3134                            // If the selection is followed by an auto-inserted closing bracket,
 3135                            // then don't insert that closing bracket again; just move the selection
 3136                            // past the closing bracket.
 3137                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3138                                && text.as_ref() == region.pair.end.as_str();
 3139                            if should_skip {
 3140                                let anchor = snapshot.anchor_after(selection.end);
 3141                                new_selections
 3142                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3143                                continue;
 3144                            }
 3145                        }
 3146
 3147                        let always_treat_brackets_as_autoclosed = snapshot
 3148                            .settings_at(selection.start, cx)
 3149                            .always_treat_brackets_as_autoclosed;
 3150                        if always_treat_brackets_as_autoclosed
 3151                            && is_bracket_pair_end
 3152                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3153                        {
 3154                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3155                            // and the inserted text is a closing bracket and the selection is followed
 3156                            // by the closing bracket then move the selection past the closing bracket.
 3157                            let anchor = snapshot.anchor_after(selection.end);
 3158                            new_selections.push((selection.map(|_| anchor), text.len()));
 3159                            continue;
 3160                        }
 3161                    }
 3162                    // If an opening bracket is 1 character long and is typed while
 3163                    // text is selected, then surround that text with the bracket pair.
 3164                    else if auto_surround
 3165                        && bracket_pair.surround
 3166                        && is_bracket_pair_start
 3167                        && bracket_pair.start.chars().count() == 1
 3168                    {
 3169                        edits.push((selection.start..selection.start, text.clone()));
 3170                        edits.push((
 3171                            selection.end..selection.end,
 3172                            bracket_pair.end.as_str().into(),
 3173                        ));
 3174                        bracket_inserted = true;
 3175                        new_selections.push((
 3176                            Selection {
 3177                                id: selection.id,
 3178                                start: snapshot.anchor_after(selection.start),
 3179                                end: snapshot.anchor_before(selection.end),
 3180                                reversed: selection.reversed,
 3181                                goal: selection.goal,
 3182                            },
 3183                            0,
 3184                        ));
 3185                        continue;
 3186                    }
 3187                }
 3188            }
 3189
 3190            if self.auto_replace_emoji_shortcode
 3191                && selection.is_empty()
 3192                && text.as_ref().ends_with(':')
 3193            {
 3194                if let Some(possible_emoji_short_code) =
 3195                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3196                {
 3197                    if !possible_emoji_short_code.is_empty() {
 3198                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3199                            let emoji_shortcode_start = Point::new(
 3200                                selection.start.row,
 3201                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3202                            );
 3203
 3204                            // Remove shortcode from buffer
 3205                            edits.push((
 3206                                emoji_shortcode_start..selection.start,
 3207                                "".to_string().into(),
 3208                            ));
 3209                            new_selections.push((
 3210                                Selection {
 3211                                    id: selection.id,
 3212                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3213                                    end: snapshot.anchor_before(selection.start),
 3214                                    reversed: selection.reversed,
 3215                                    goal: selection.goal,
 3216                                },
 3217                                0,
 3218                            ));
 3219
 3220                            // Insert emoji
 3221                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3222                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3223                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3224
 3225                            continue;
 3226                        }
 3227                    }
 3228                }
 3229            }
 3230
 3231            // If not handling any auto-close operation, then just replace the selected
 3232            // text with the given input and move the selection to the end of the
 3233            // newly inserted text.
 3234            let anchor = snapshot.anchor_after(selection.end);
 3235            if !self.linked_edit_ranges.is_empty() {
 3236                let start_anchor = snapshot.anchor_before(selection.start);
 3237
 3238                let is_word_char = text.chars().next().map_or(true, |char| {
 3239                    let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
 3240                    let kind = char_kind(&scope, char);
 3241
 3242                    kind == CharKind::Word
 3243                });
 3244
 3245                if is_word_char {
 3246                    if let Some(ranges) = self
 3247                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3248                    {
 3249                        for (buffer, edits) in ranges {
 3250                            linked_edits
 3251                                .entry(buffer.clone())
 3252                                .or_default()
 3253                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3254                        }
 3255                    }
 3256                }
 3257            }
 3258
 3259            new_selections.push((selection.map(|_| anchor), 0));
 3260            edits.push((selection.start..selection.end, text.clone()));
 3261        }
 3262
 3263        drop(snapshot);
 3264
 3265        self.transact(cx, |this, cx| {
 3266            this.buffer.update(cx, |buffer, cx| {
 3267                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3268            });
 3269            for (buffer, edits) in linked_edits {
 3270                buffer.update(cx, |buffer, cx| {
 3271                    let snapshot = buffer.snapshot();
 3272                    let edits = edits
 3273                        .into_iter()
 3274                        .map(|(range, text)| {
 3275                            use text::ToPoint as TP;
 3276                            let end_point = TP::to_point(&range.end, &snapshot);
 3277                            let start_point = TP::to_point(&range.start, &snapshot);
 3278                            (start_point..end_point, text)
 3279                        })
 3280                        .sorted_by_key(|(range, _)| range.start)
 3281                        .collect::<Vec<_>>();
 3282                    buffer.edit(edits, None, cx);
 3283                })
 3284            }
 3285            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3286            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3287            let snapshot = this.buffer.read(cx).read(cx);
 3288            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3289                .zip(new_selection_deltas)
 3290                .map(|(selection, delta)| Selection {
 3291                    id: selection.id,
 3292                    start: selection.start + delta,
 3293                    end: selection.end + delta,
 3294                    reversed: selection.reversed,
 3295                    goal: SelectionGoal::None,
 3296                })
 3297                .collect::<Vec<_>>();
 3298
 3299            let mut i = 0;
 3300            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3301                let position = position.to_offset(&snapshot) + delta;
 3302                let start = snapshot.anchor_before(position);
 3303                let end = snapshot.anchor_after(position);
 3304                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3305                    match existing_state.range.start.cmp(&start, &snapshot) {
 3306                        Ordering::Less => i += 1,
 3307                        Ordering::Greater => break,
 3308                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3309                            Ordering::Less => i += 1,
 3310                            Ordering::Equal => break,
 3311                            Ordering::Greater => break,
 3312                        },
 3313                    }
 3314                }
 3315                this.autoclose_regions.insert(
 3316                    i,
 3317                    AutocloseRegion {
 3318                        selection_id,
 3319                        range: start..end,
 3320                        pair,
 3321                    },
 3322                );
 3323            }
 3324
 3325            drop(snapshot);
 3326            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3327            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3328                s.select(new_selections)
 3329            });
 3330
 3331            if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
 3332                if let Some(on_type_format_task) =
 3333                    this.trigger_on_type_formatting(text.to_string(), cx)
 3334                {
 3335                    on_type_format_task.detach_and_log_err(cx);
 3336                }
 3337            }
 3338
 3339            let editor_settings = EditorSettings::get_global(cx);
 3340            if bracket_inserted
 3341                && (editor_settings.auto_signature_help
 3342                    || editor_settings.show_signature_help_after_edits)
 3343            {
 3344                this.show_signature_help(&ShowSignatureHelp, cx);
 3345            }
 3346
 3347            let trigger_in_words = !had_active_inline_completion;
 3348            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3349            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3350            this.refresh_inline_completion(true, false, cx);
 3351        });
 3352    }
 3353
 3354    fn find_possible_emoji_shortcode_at_position(
 3355        snapshot: &MultiBufferSnapshot,
 3356        position: Point,
 3357    ) -> Option<String> {
 3358        let mut chars = Vec::new();
 3359        let mut found_colon = false;
 3360        for char in snapshot.reversed_chars_at(position).take(100) {
 3361            // Found a possible emoji shortcode in the middle of the buffer
 3362            if found_colon {
 3363                if char.is_whitespace() {
 3364                    chars.reverse();
 3365                    return Some(chars.iter().collect());
 3366                }
 3367                // If the previous character is not a whitespace, we are in the middle of a word
 3368                // and we only want to complete the shortcode if the word is made up of other emojis
 3369                let mut containing_word = String::new();
 3370                for ch in snapshot
 3371                    .reversed_chars_at(position)
 3372                    .skip(chars.len() + 1)
 3373                    .take(100)
 3374                {
 3375                    if ch.is_whitespace() {
 3376                        break;
 3377                    }
 3378                    containing_word.push(ch);
 3379                }
 3380                let containing_word = containing_word.chars().rev().collect::<String>();
 3381                if util::word_consists_of_emojis(containing_word.as_str()) {
 3382                    chars.reverse();
 3383                    return Some(chars.iter().collect());
 3384                }
 3385            }
 3386
 3387            if char.is_whitespace() || !char.is_ascii() {
 3388                return None;
 3389            }
 3390            if char == ':' {
 3391                found_colon = true;
 3392            } else {
 3393                chars.push(char);
 3394            }
 3395        }
 3396        // Found a possible emoji shortcode at the beginning of the buffer
 3397        chars.reverse();
 3398        Some(chars.iter().collect())
 3399    }
 3400
 3401    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3402        self.transact(cx, |this, cx| {
 3403            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3404                let selections = this.selections.all::<usize>(cx);
 3405                let multi_buffer = this.buffer.read(cx);
 3406                let buffer = multi_buffer.snapshot(cx);
 3407                selections
 3408                    .iter()
 3409                    .map(|selection| {
 3410                        let start_point = selection.start.to_point(&buffer);
 3411                        let mut indent =
 3412                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3413                        indent.len = cmp::min(indent.len, start_point.column);
 3414                        let start = selection.start;
 3415                        let end = selection.end;
 3416                        let selection_is_empty = start == end;
 3417                        let language_scope = buffer.language_scope_at(start);
 3418                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3419                            &language_scope
 3420                        {
 3421                            let leading_whitespace_len = buffer
 3422                                .reversed_chars_at(start)
 3423                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3424                                .map(|c| c.len_utf8())
 3425                                .sum::<usize>();
 3426
 3427                            let trailing_whitespace_len = buffer
 3428                                .chars_at(end)
 3429                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3430                                .map(|c| c.len_utf8())
 3431                                .sum::<usize>();
 3432
 3433                            let insert_extra_newline =
 3434                                language.brackets().any(|(pair, enabled)| {
 3435                                    let pair_start = pair.start.trim_end();
 3436                                    let pair_end = pair.end.trim_start();
 3437
 3438                                    enabled
 3439                                        && pair.newline
 3440                                        && buffer.contains_str_at(
 3441                                            end + trailing_whitespace_len,
 3442                                            pair_end,
 3443                                        )
 3444                                        && buffer.contains_str_at(
 3445                                            (start - leading_whitespace_len)
 3446                                                .saturating_sub(pair_start.len()),
 3447                                            pair_start,
 3448                                        )
 3449                                });
 3450
 3451                            // Comment extension on newline is allowed only for cursor selections
 3452                            let comment_delimiter = maybe!({
 3453                                if !selection_is_empty {
 3454                                    return None;
 3455                                }
 3456
 3457                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3458                                    return None;
 3459                                }
 3460
 3461                                let delimiters = language.line_comment_prefixes();
 3462                                let max_len_of_delimiter =
 3463                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3464                                let (snapshot, range) =
 3465                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3466
 3467                                let mut index_of_first_non_whitespace = 0;
 3468                                let comment_candidate = snapshot
 3469                                    .chars_for_range(range)
 3470                                    .skip_while(|c| {
 3471                                        let should_skip = c.is_whitespace();
 3472                                        if should_skip {
 3473                                            index_of_first_non_whitespace += 1;
 3474                                        }
 3475                                        should_skip
 3476                                    })
 3477                                    .take(max_len_of_delimiter)
 3478                                    .collect::<String>();
 3479                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3480                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3481                                })?;
 3482                                let cursor_is_placed_after_comment_marker =
 3483                                    index_of_first_non_whitespace + comment_prefix.len()
 3484                                        <= start_point.column as usize;
 3485                                if cursor_is_placed_after_comment_marker {
 3486                                    Some(comment_prefix.clone())
 3487                                } else {
 3488                                    None
 3489                                }
 3490                            });
 3491                            (comment_delimiter, insert_extra_newline)
 3492                        } else {
 3493                            (None, false)
 3494                        };
 3495
 3496                        let capacity_for_delimiter = comment_delimiter
 3497                            .as_deref()
 3498                            .map(str::len)
 3499                            .unwrap_or_default();
 3500                        let mut new_text =
 3501                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3502                        new_text.push_str("\n");
 3503                        new_text.extend(indent.chars());
 3504                        if let Some(delimiter) = &comment_delimiter {
 3505                            new_text.push_str(&delimiter);
 3506                        }
 3507                        if insert_extra_newline {
 3508                            new_text = new_text.repeat(2);
 3509                        }
 3510
 3511                        let anchor = buffer.anchor_after(end);
 3512                        let new_selection = selection.map(|_| anchor);
 3513                        (
 3514                            (start..end, new_text),
 3515                            (insert_extra_newline, new_selection),
 3516                        )
 3517                    })
 3518                    .unzip()
 3519            };
 3520
 3521            this.edit_with_autoindent(edits, cx);
 3522            let buffer = this.buffer.read(cx).snapshot(cx);
 3523            let new_selections = selection_fixup_info
 3524                .into_iter()
 3525                .map(|(extra_newline_inserted, new_selection)| {
 3526                    let mut cursor = new_selection.end.to_point(&buffer);
 3527                    if extra_newline_inserted {
 3528                        cursor.row -= 1;
 3529                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3530                    }
 3531                    new_selection.map(|_| cursor)
 3532                })
 3533                .collect();
 3534
 3535            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3536            this.refresh_inline_completion(true, false, cx);
 3537        });
 3538    }
 3539
 3540    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3541        let buffer = self.buffer.read(cx);
 3542        let snapshot = buffer.snapshot(cx);
 3543
 3544        let mut edits = Vec::new();
 3545        let mut rows = Vec::new();
 3546
 3547        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3548            let cursor = selection.head();
 3549            let row = cursor.row;
 3550
 3551            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3552
 3553            let newline = "\n".to_string();
 3554            edits.push((start_of_line..start_of_line, newline));
 3555
 3556            rows.push(row + rows_inserted as u32);
 3557        }
 3558
 3559        self.transact(cx, |editor, cx| {
 3560            editor.edit(edits, cx);
 3561
 3562            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3563                let mut index = 0;
 3564                s.move_cursors_with(|map, _, _| {
 3565                    let row = rows[index];
 3566                    index += 1;
 3567
 3568                    let point = Point::new(row, 0);
 3569                    let boundary = map.next_line_boundary(point).1;
 3570                    let clipped = map.clip_point(boundary, Bias::Left);
 3571
 3572                    (clipped, SelectionGoal::None)
 3573                });
 3574            });
 3575
 3576            let mut indent_edits = Vec::new();
 3577            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3578            for row in rows {
 3579                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3580                for (row, indent) in indents {
 3581                    if indent.len == 0 {
 3582                        continue;
 3583                    }
 3584
 3585                    let text = match indent.kind {
 3586                        IndentKind::Space => " ".repeat(indent.len as usize),
 3587                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3588                    };
 3589                    let point = Point::new(row.0, 0);
 3590                    indent_edits.push((point..point, text));
 3591                }
 3592            }
 3593            editor.edit(indent_edits, cx);
 3594        });
 3595    }
 3596
 3597    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3598        let buffer = self.buffer.read(cx);
 3599        let snapshot = buffer.snapshot(cx);
 3600
 3601        let mut edits = Vec::new();
 3602        let mut rows = Vec::new();
 3603        let mut rows_inserted = 0;
 3604
 3605        for selection in self.selections.all_adjusted(cx) {
 3606            let cursor = selection.head();
 3607            let row = cursor.row;
 3608
 3609            let point = Point::new(row + 1, 0);
 3610            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3611
 3612            let newline = "\n".to_string();
 3613            edits.push((start_of_line..start_of_line, newline));
 3614
 3615            rows_inserted += 1;
 3616            rows.push(row + rows_inserted);
 3617        }
 3618
 3619        self.transact(cx, |editor, cx| {
 3620            editor.edit(edits, cx);
 3621
 3622            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3623                let mut index = 0;
 3624                s.move_cursors_with(|map, _, _| {
 3625                    let row = rows[index];
 3626                    index += 1;
 3627
 3628                    let point = Point::new(row, 0);
 3629                    let boundary = map.next_line_boundary(point).1;
 3630                    let clipped = map.clip_point(boundary, Bias::Left);
 3631
 3632                    (clipped, SelectionGoal::None)
 3633                });
 3634            });
 3635
 3636            let mut indent_edits = Vec::new();
 3637            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3638            for row in rows {
 3639                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3640                for (row, indent) in indents {
 3641                    if indent.len == 0 {
 3642                        continue;
 3643                    }
 3644
 3645                    let text = match indent.kind {
 3646                        IndentKind::Space => " ".repeat(indent.len as usize),
 3647                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3648                    };
 3649                    let point = Point::new(row.0, 0);
 3650                    indent_edits.push((point..point, text));
 3651                }
 3652            }
 3653            editor.edit(indent_edits, cx);
 3654        });
 3655    }
 3656
 3657    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3658        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3659            original_indent_columns: Vec::new(),
 3660        });
 3661        self.insert_with_autoindent_mode(text, autoindent, cx);
 3662    }
 3663
 3664    fn insert_with_autoindent_mode(
 3665        &mut self,
 3666        text: &str,
 3667        autoindent_mode: Option<AutoindentMode>,
 3668        cx: &mut ViewContext<Self>,
 3669    ) {
 3670        if self.read_only(cx) {
 3671            return;
 3672        }
 3673
 3674        let text: Arc<str> = text.into();
 3675        self.transact(cx, |this, cx| {
 3676            let old_selections = this.selections.all_adjusted(cx);
 3677            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3678                let anchors = {
 3679                    let snapshot = buffer.read(cx);
 3680                    old_selections
 3681                        .iter()
 3682                        .map(|s| {
 3683                            let anchor = snapshot.anchor_after(s.head());
 3684                            s.map(|_| anchor)
 3685                        })
 3686                        .collect::<Vec<_>>()
 3687                };
 3688                buffer.edit(
 3689                    old_selections
 3690                        .iter()
 3691                        .map(|s| (s.start..s.end, text.clone())),
 3692                    autoindent_mode,
 3693                    cx,
 3694                );
 3695                anchors
 3696            });
 3697
 3698            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3699                s.select_anchors(selection_anchors);
 3700            })
 3701        });
 3702    }
 3703
 3704    fn trigger_completion_on_input(
 3705        &mut self,
 3706        text: &str,
 3707        trigger_in_words: bool,
 3708        cx: &mut ViewContext<Self>,
 3709    ) {
 3710        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3711            self.show_completions(
 3712                &ShowCompletions {
 3713                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3714                },
 3715                cx,
 3716            );
 3717        } else {
 3718            self.hide_context_menu(cx);
 3719        }
 3720    }
 3721
 3722    fn is_completion_trigger(
 3723        &self,
 3724        text: &str,
 3725        trigger_in_words: bool,
 3726        cx: &mut ViewContext<Self>,
 3727    ) -> bool {
 3728        let position = self.selections.newest_anchor().head();
 3729        let multibuffer = self.buffer.read(cx);
 3730        let Some(buffer) = position
 3731            .buffer_id
 3732            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3733        else {
 3734            return false;
 3735        };
 3736
 3737        if let Some(completion_provider) = &self.completion_provider {
 3738            completion_provider.is_completion_trigger(
 3739                &buffer,
 3740                position.text_anchor,
 3741                text,
 3742                trigger_in_words,
 3743                cx,
 3744            )
 3745        } else {
 3746            false
 3747        }
 3748    }
 3749
 3750    /// If any empty selections is touching the start of its innermost containing autoclose
 3751    /// region, expand it to select the brackets.
 3752    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3753        let selections = self.selections.all::<usize>(cx);
 3754        let buffer = self.buffer.read(cx).read(cx);
 3755        let new_selections = self
 3756            .selections_with_autoclose_regions(selections, &buffer)
 3757            .map(|(mut selection, region)| {
 3758                if !selection.is_empty() {
 3759                    return selection;
 3760                }
 3761
 3762                if let Some(region) = region {
 3763                    let mut range = region.range.to_offset(&buffer);
 3764                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3765                        range.start -= region.pair.start.len();
 3766                        if buffer.contains_str_at(range.start, &region.pair.start)
 3767                            && buffer.contains_str_at(range.end, &region.pair.end)
 3768                        {
 3769                            range.end += region.pair.end.len();
 3770                            selection.start = range.start;
 3771                            selection.end = range.end;
 3772
 3773                            return selection;
 3774                        }
 3775                    }
 3776                }
 3777
 3778                let always_treat_brackets_as_autoclosed = buffer
 3779                    .settings_at(selection.start, cx)
 3780                    .always_treat_brackets_as_autoclosed;
 3781
 3782                if !always_treat_brackets_as_autoclosed {
 3783                    return selection;
 3784                }
 3785
 3786                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3787                    for (pair, enabled) in scope.brackets() {
 3788                        if !enabled || !pair.close {
 3789                            continue;
 3790                        }
 3791
 3792                        if buffer.contains_str_at(selection.start, &pair.end) {
 3793                            let pair_start_len = pair.start.len();
 3794                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3795                            {
 3796                                selection.start -= pair_start_len;
 3797                                selection.end += pair.end.len();
 3798
 3799                                return selection;
 3800                            }
 3801                        }
 3802                    }
 3803                }
 3804
 3805                selection
 3806            })
 3807            .collect();
 3808
 3809        drop(buffer);
 3810        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3811    }
 3812
 3813    /// Iterate the given selections, and for each one, find the smallest surrounding
 3814    /// autoclose region. This uses the ordering of the selections and the autoclose
 3815    /// regions to avoid repeated comparisons.
 3816    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3817        &'a self,
 3818        selections: impl IntoIterator<Item = Selection<D>>,
 3819        buffer: &'a MultiBufferSnapshot,
 3820    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3821        let mut i = 0;
 3822        let mut regions = self.autoclose_regions.as_slice();
 3823        selections.into_iter().map(move |selection| {
 3824            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3825
 3826            let mut enclosing = None;
 3827            while let Some(pair_state) = regions.get(i) {
 3828                if pair_state.range.end.to_offset(buffer) < range.start {
 3829                    regions = &regions[i + 1..];
 3830                    i = 0;
 3831                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3832                    break;
 3833                } else {
 3834                    if pair_state.selection_id == selection.id {
 3835                        enclosing = Some(pair_state);
 3836                    }
 3837                    i += 1;
 3838                }
 3839            }
 3840
 3841            (selection.clone(), enclosing)
 3842        })
 3843    }
 3844
 3845    /// Remove any autoclose regions that no longer contain their selection.
 3846    fn invalidate_autoclose_regions(
 3847        &mut self,
 3848        mut selections: &[Selection<Anchor>],
 3849        buffer: &MultiBufferSnapshot,
 3850    ) {
 3851        self.autoclose_regions.retain(|state| {
 3852            let mut i = 0;
 3853            while let Some(selection) = selections.get(i) {
 3854                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3855                    selections = &selections[1..];
 3856                    continue;
 3857                }
 3858                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3859                    break;
 3860                }
 3861                if selection.id == state.selection_id {
 3862                    return true;
 3863                } else {
 3864                    i += 1;
 3865                }
 3866            }
 3867            false
 3868        });
 3869    }
 3870
 3871    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3872        let offset = position.to_offset(buffer);
 3873        let (word_range, kind) = buffer.surrounding_word(offset);
 3874        if offset > word_range.start && kind == Some(CharKind::Word) {
 3875            Some(
 3876                buffer
 3877                    .text_for_range(word_range.start..offset)
 3878                    .collect::<String>(),
 3879            )
 3880        } else {
 3881            None
 3882        }
 3883    }
 3884
 3885    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3886        self.refresh_inlay_hints(
 3887            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3888            cx,
 3889        );
 3890    }
 3891
 3892    pub fn inlay_hints_enabled(&self) -> bool {
 3893        self.inlay_hint_cache.enabled
 3894    }
 3895
 3896    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3897        if self.project.is_none() || self.mode != EditorMode::Full {
 3898            return;
 3899        }
 3900
 3901        let reason_description = reason.description();
 3902        let ignore_debounce = matches!(
 3903            reason,
 3904            InlayHintRefreshReason::SettingsChange(_)
 3905                | InlayHintRefreshReason::Toggle(_)
 3906                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3907        );
 3908        let (invalidate_cache, required_languages) = match reason {
 3909            InlayHintRefreshReason::Toggle(enabled) => {
 3910                self.inlay_hint_cache.enabled = enabled;
 3911                if enabled {
 3912                    (InvalidationStrategy::RefreshRequested, None)
 3913                } else {
 3914                    self.inlay_hint_cache.clear();
 3915                    self.splice_inlays(
 3916                        self.visible_inlay_hints(cx)
 3917                            .iter()
 3918                            .map(|inlay| inlay.id)
 3919                            .collect(),
 3920                        Vec::new(),
 3921                        cx,
 3922                    );
 3923                    return;
 3924                }
 3925            }
 3926            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3927                match self.inlay_hint_cache.update_settings(
 3928                    &self.buffer,
 3929                    new_settings,
 3930                    self.visible_inlay_hints(cx),
 3931                    cx,
 3932                ) {
 3933                    ControlFlow::Break(Some(InlaySplice {
 3934                        to_remove,
 3935                        to_insert,
 3936                    })) => {
 3937                        self.splice_inlays(to_remove, to_insert, cx);
 3938                        return;
 3939                    }
 3940                    ControlFlow::Break(None) => return,
 3941                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3942                }
 3943            }
 3944            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3945                if let Some(InlaySplice {
 3946                    to_remove,
 3947                    to_insert,
 3948                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3949                {
 3950                    self.splice_inlays(to_remove, to_insert, cx);
 3951                }
 3952                return;
 3953            }
 3954            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3955            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3956                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3957            }
 3958            InlayHintRefreshReason::RefreshRequested => {
 3959                (InvalidationStrategy::RefreshRequested, None)
 3960            }
 3961        };
 3962
 3963        if let Some(InlaySplice {
 3964            to_remove,
 3965            to_insert,
 3966        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3967            reason_description,
 3968            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3969            invalidate_cache,
 3970            ignore_debounce,
 3971            cx,
 3972        ) {
 3973            self.splice_inlays(to_remove, to_insert, cx);
 3974        }
 3975    }
 3976
 3977    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3978        self.display_map
 3979            .read(cx)
 3980            .current_inlays()
 3981            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3982            .cloned()
 3983            .collect()
 3984    }
 3985
 3986    pub fn excerpts_for_inlay_hints_query(
 3987        &self,
 3988        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3989        cx: &mut ViewContext<Editor>,
 3990    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3991        let Some(project) = self.project.as_ref() else {
 3992            return HashMap::default();
 3993        };
 3994        let project = project.read(cx);
 3995        let multi_buffer = self.buffer().read(cx);
 3996        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3997        let multi_buffer_visible_start = self
 3998            .scroll_manager
 3999            .anchor()
 4000            .anchor
 4001            .to_point(&multi_buffer_snapshot);
 4002        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4003            multi_buffer_visible_start
 4004                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4005            Bias::Left,
 4006        );
 4007        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4008        multi_buffer
 4009            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4010            .into_iter()
 4011            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4012            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4013                let buffer = buffer_handle.read(cx);
 4014                let buffer_file = project::File::from_dyn(buffer.file())?;
 4015                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4016                let worktree_entry = buffer_worktree
 4017                    .read(cx)
 4018                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4019                if worktree_entry.is_ignored {
 4020                    return None;
 4021                }
 4022
 4023                let language = buffer.language()?;
 4024                if let Some(restrict_to_languages) = restrict_to_languages {
 4025                    if !restrict_to_languages.contains(language) {
 4026                        return None;
 4027                    }
 4028                }
 4029                Some((
 4030                    excerpt_id,
 4031                    (
 4032                        buffer_handle,
 4033                        buffer.version().clone(),
 4034                        excerpt_visible_range,
 4035                    ),
 4036                ))
 4037            })
 4038            .collect()
 4039    }
 4040
 4041    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4042        TextLayoutDetails {
 4043            text_system: cx.text_system().clone(),
 4044            editor_style: self.style.clone().unwrap(),
 4045            rem_size: cx.rem_size(),
 4046            scroll_anchor: self.scroll_manager.anchor(),
 4047            visible_rows: self.visible_line_count(),
 4048            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4049        }
 4050    }
 4051
 4052    fn splice_inlays(
 4053        &self,
 4054        to_remove: Vec<InlayId>,
 4055        to_insert: Vec<Inlay>,
 4056        cx: &mut ViewContext<Self>,
 4057    ) {
 4058        self.display_map.update(cx, |display_map, cx| {
 4059            display_map.splice_inlays(to_remove, to_insert, cx);
 4060        });
 4061        cx.notify();
 4062    }
 4063
 4064    fn trigger_on_type_formatting(
 4065        &self,
 4066        input: String,
 4067        cx: &mut ViewContext<Self>,
 4068    ) -> Option<Task<Result<()>>> {
 4069        if input.len() != 1 {
 4070            return None;
 4071        }
 4072
 4073        let project = self.project.as_ref()?;
 4074        let position = self.selections.newest_anchor().head();
 4075        let (buffer, buffer_position) = self
 4076            .buffer
 4077            .read(cx)
 4078            .text_anchor_for_position(position, cx)?;
 4079
 4080        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4081        // hence we do LSP request & edit on host side only — add formats to host's history.
 4082        let push_to_lsp_host_history = true;
 4083        // If this is not the host, append its history with new edits.
 4084        let push_to_client_history = project.read(cx).is_via_collab();
 4085
 4086        let on_type_formatting = project.update(cx, |project, cx| {
 4087            project.on_type_format(
 4088                buffer.clone(),
 4089                buffer_position,
 4090                input,
 4091                push_to_lsp_host_history,
 4092                cx,
 4093            )
 4094        });
 4095        Some(cx.spawn(|editor, mut cx| async move {
 4096            if let Some(transaction) = on_type_formatting.await? {
 4097                if push_to_client_history {
 4098                    buffer
 4099                        .update(&mut cx, |buffer, _| {
 4100                            buffer.push_transaction(transaction, Instant::now());
 4101                        })
 4102                        .ok();
 4103                }
 4104                editor.update(&mut cx, |editor, cx| {
 4105                    editor.refresh_document_highlights(cx);
 4106                })?;
 4107            }
 4108            Ok(())
 4109        }))
 4110    }
 4111
 4112    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4113        if self.pending_rename.is_some() {
 4114            return;
 4115        }
 4116
 4117        let Some(provider) = self.completion_provider.as_ref() else {
 4118            return;
 4119        };
 4120
 4121        let position = self.selections.newest_anchor().head();
 4122        let (buffer, buffer_position) =
 4123            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4124                output
 4125            } else {
 4126                return;
 4127            };
 4128
 4129        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4130        let is_followup_invoke = {
 4131            let context_menu_state = self.context_menu.read();
 4132            matches!(
 4133                context_menu_state.deref(),
 4134                Some(ContextMenu::Completions(_))
 4135            )
 4136        };
 4137        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4138            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4139            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
 4140                CompletionTriggerKind::TRIGGER_CHARACTER
 4141            }
 4142
 4143            _ => CompletionTriggerKind::INVOKED,
 4144        };
 4145        let completion_context = CompletionContext {
 4146            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4147                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4148                    Some(String::from(trigger))
 4149                } else {
 4150                    None
 4151                }
 4152            }),
 4153            trigger_kind,
 4154        };
 4155        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4156        let sort_completions = provider.sort_completions();
 4157
 4158        let id = post_inc(&mut self.next_completion_id);
 4159        let task = cx.spawn(|this, mut cx| {
 4160            async move {
 4161                this.update(&mut cx, |this, _| {
 4162                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4163                })?;
 4164                let completions = completions.await.log_err();
 4165                let menu = if let Some(completions) = completions {
 4166                    let mut menu = CompletionsMenu {
 4167                        id,
 4168                        sort_completions,
 4169                        initial_position: position,
 4170                        match_candidates: completions
 4171                            .iter()
 4172                            .enumerate()
 4173                            .map(|(id, completion)| {
 4174                                StringMatchCandidate::new(
 4175                                    id,
 4176                                    completion.label.text[completion.label.filter_range.clone()]
 4177                                        .into(),
 4178                                )
 4179                            })
 4180                            .collect(),
 4181                        buffer: buffer.clone(),
 4182                        completions: Arc::new(RwLock::new(completions.into())),
 4183                        matches: Vec::new().into(),
 4184                        selected_item: 0,
 4185                        scroll_handle: UniformListScrollHandle::new(),
 4186                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4187                            DebouncedDelay::new(),
 4188                        )),
 4189                    };
 4190                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4191                        .await;
 4192
 4193                    if menu.matches.is_empty() {
 4194                        None
 4195                    } else {
 4196                        this.update(&mut cx, |editor, cx| {
 4197                            let completions = menu.completions.clone();
 4198                            let matches = menu.matches.clone();
 4199
 4200                            let delay_ms = EditorSettings::get_global(cx)
 4201                                .completion_documentation_secondary_query_debounce;
 4202                            let delay = Duration::from_millis(delay_ms);
 4203                            editor
 4204                                .completion_documentation_pre_resolve_debounce
 4205                                .fire_new(delay, cx, |editor, cx| {
 4206                                    CompletionsMenu::pre_resolve_completion_documentation(
 4207                                        buffer,
 4208                                        completions,
 4209                                        matches,
 4210                                        editor,
 4211                                        cx,
 4212                                    )
 4213                                });
 4214                        })
 4215                        .ok();
 4216                        Some(menu)
 4217                    }
 4218                } else {
 4219                    None
 4220                };
 4221
 4222                this.update(&mut cx, |this, cx| {
 4223                    let mut context_menu = this.context_menu.write();
 4224                    match context_menu.as_ref() {
 4225                        None => {}
 4226
 4227                        Some(ContextMenu::Completions(prev_menu)) => {
 4228                            if prev_menu.id > id {
 4229                                return;
 4230                            }
 4231                        }
 4232
 4233                        _ => return,
 4234                    }
 4235
 4236                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4237                        let menu = menu.unwrap();
 4238                        *context_menu = Some(ContextMenu::Completions(menu));
 4239                        drop(context_menu);
 4240                        this.discard_inline_completion(false, cx);
 4241                        cx.notify();
 4242                    } else if this.completion_tasks.len() <= 1 {
 4243                        // If there are no more completion tasks and the last menu was
 4244                        // empty, we should hide it. If it was already hidden, we should
 4245                        // also show the copilot completion when available.
 4246                        drop(context_menu);
 4247                        if this.hide_context_menu(cx).is_none() {
 4248                            this.update_visible_inline_completion(cx);
 4249                        }
 4250                    }
 4251                })?;
 4252
 4253                Ok::<_, anyhow::Error>(())
 4254            }
 4255            .log_err()
 4256        });
 4257
 4258        self.completion_tasks.push((id, task));
 4259    }
 4260
 4261    pub fn confirm_completion(
 4262        &mut self,
 4263        action: &ConfirmCompletion,
 4264        cx: &mut ViewContext<Self>,
 4265    ) -> Option<Task<Result<()>>> {
 4266        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4267    }
 4268
 4269    pub fn compose_completion(
 4270        &mut self,
 4271        action: &ComposeCompletion,
 4272        cx: &mut ViewContext<Self>,
 4273    ) -> Option<Task<Result<()>>> {
 4274        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4275    }
 4276
 4277    fn do_completion(
 4278        &mut self,
 4279        item_ix: Option<usize>,
 4280        intent: CompletionIntent,
 4281        cx: &mut ViewContext<Editor>,
 4282    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4283        use language::ToOffset as _;
 4284
 4285        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4286            menu
 4287        } else {
 4288            return None;
 4289        };
 4290
 4291        let mat = completions_menu
 4292            .matches
 4293            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4294        let buffer_handle = completions_menu.buffer;
 4295        let completions = completions_menu.completions.read();
 4296        let completion = completions.get(mat.candidate_id)?;
 4297        cx.stop_propagation();
 4298
 4299        let snippet;
 4300        let text;
 4301
 4302        if completion.is_snippet() {
 4303            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4304            text = snippet.as_ref().unwrap().text.clone();
 4305        } else {
 4306            snippet = None;
 4307            text = completion.new_text.clone();
 4308        };
 4309        let selections = self.selections.all::<usize>(cx);
 4310        let buffer = buffer_handle.read(cx);
 4311        let old_range = completion.old_range.to_offset(buffer);
 4312        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4313
 4314        let newest_selection = self.selections.newest_anchor();
 4315        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4316            return None;
 4317        }
 4318
 4319        let lookbehind = newest_selection
 4320            .start
 4321            .text_anchor
 4322            .to_offset(buffer)
 4323            .saturating_sub(old_range.start);
 4324        let lookahead = old_range
 4325            .end
 4326            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4327        let mut common_prefix_len = old_text
 4328            .bytes()
 4329            .zip(text.bytes())
 4330            .take_while(|(a, b)| a == b)
 4331            .count();
 4332
 4333        let snapshot = self.buffer.read(cx).snapshot(cx);
 4334        let mut range_to_replace: Option<Range<isize>> = None;
 4335        let mut ranges = Vec::new();
 4336        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4337        for selection in &selections {
 4338            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4339                let start = selection.start.saturating_sub(lookbehind);
 4340                let end = selection.end + lookahead;
 4341                if selection.id == newest_selection.id {
 4342                    range_to_replace = Some(
 4343                        ((start + common_prefix_len) as isize - selection.start as isize)
 4344                            ..(end as isize - selection.start as isize),
 4345                    );
 4346                }
 4347                ranges.push(start + common_prefix_len..end);
 4348            } else {
 4349                common_prefix_len = 0;
 4350                ranges.clear();
 4351                ranges.extend(selections.iter().map(|s| {
 4352                    if s.id == newest_selection.id {
 4353                        range_to_replace = Some(
 4354                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4355                                - selection.start as isize
 4356                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4357                                    - selection.start as isize,
 4358                        );
 4359                        old_range.clone()
 4360                    } else {
 4361                        s.start..s.end
 4362                    }
 4363                }));
 4364                break;
 4365            }
 4366            if !self.linked_edit_ranges.is_empty() {
 4367                let start_anchor = snapshot.anchor_before(selection.head());
 4368                let end_anchor = snapshot.anchor_after(selection.tail());
 4369                if let Some(ranges) = self
 4370                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4371                {
 4372                    for (buffer, edits) in ranges {
 4373                        linked_edits.entry(buffer.clone()).or_default().extend(
 4374                            edits
 4375                                .into_iter()
 4376                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4377                        );
 4378                    }
 4379                }
 4380            }
 4381        }
 4382        let text = &text[common_prefix_len..];
 4383
 4384        cx.emit(EditorEvent::InputHandled {
 4385            utf16_range_to_replace: range_to_replace,
 4386            text: text.into(),
 4387        });
 4388
 4389        self.transact(cx, |this, cx| {
 4390            if let Some(mut snippet) = snippet {
 4391                snippet.text = text.to_string();
 4392                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4393                    tabstop.start -= common_prefix_len as isize;
 4394                    tabstop.end -= common_prefix_len as isize;
 4395                }
 4396
 4397                this.insert_snippet(&ranges, snippet, cx).log_err();
 4398            } else {
 4399                this.buffer.update(cx, |buffer, cx| {
 4400                    buffer.edit(
 4401                        ranges.iter().map(|range| (range.clone(), text)),
 4402                        this.autoindent_mode.clone(),
 4403                        cx,
 4404                    );
 4405                });
 4406            }
 4407            for (buffer, edits) in linked_edits {
 4408                buffer.update(cx, |buffer, cx| {
 4409                    let snapshot = buffer.snapshot();
 4410                    let edits = edits
 4411                        .into_iter()
 4412                        .map(|(range, text)| {
 4413                            use text::ToPoint as TP;
 4414                            let end_point = TP::to_point(&range.end, &snapshot);
 4415                            let start_point = TP::to_point(&range.start, &snapshot);
 4416                            (start_point..end_point, text)
 4417                        })
 4418                        .sorted_by_key(|(range, _)| range.start)
 4419                        .collect::<Vec<_>>();
 4420                    buffer.edit(edits, None, cx);
 4421                })
 4422            }
 4423
 4424            this.refresh_inline_completion(true, false, cx);
 4425        });
 4426
 4427        let show_new_completions_on_confirm = completion
 4428            .confirm
 4429            .as_ref()
 4430            .map_or(false, |confirm| confirm(intent, cx));
 4431        if show_new_completions_on_confirm {
 4432            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4433        }
 4434
 4435        let provider = self.completion_provider.as_ref()?;
 4436        let apply_edits = provider.apply_additional_edits_for_completion(
 4437            buffer_handle,
 4438            completion.clone(),
 4439            true,
 4440            cx,
 4441        );
 4442
 4443        let editor_settings = EditorSettings::get_global(cx);
 4444        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4445            // After the code completion is finished, users often want to know what signatures are needed.
 4446            // so we should automatically call signature_help
 4447            self.show_signature_help(&ShowSignatureHelp, cx);
 4448        }
 4449
 4450        Some(cx.foreground_executor().spawn(async move {
 4451            apply_edits.await?;
 4452            Ok(())
 4453        }))
 4454    }
 4455
 4456    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4457        let mut context_menu = self.context_menu.write();
 4458        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4459            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4460                // Toggle if we're selecting the same one
 4461                *context_menu = None;
 4462                cx.notify();
 4463                return;
 4464            } else {
 4465                // Otherwise, clear it and start a new one
 4466                *context_menu = None;
 4467                cx.notify();
 4468            }
 4469        }
 4470        drop(context_menu);
 4471        let snapshot = self.snapshot(cx);
 4472        let deployed_from_indicator = action.deployed_from_indicator;
 4473        let mut task = self.code_actions_task.take();
 4474        let action = action.clone();
 4475        cx.spawn(|editor, mut cx| async move {
 4476            while let Some(prev_task) = task {
 4477                prev_task.await;
 4478                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4479            }
 4480
 4481            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4482                if editor.focus_handle.is_focused(cx) {
 4483                    let multibuffer_point = action
 4484                        .deployed_from_indicator
 4485                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4486                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4487                    let (buffer, buffer_row) = snapshot
 4488                        .buffer_snapshot
 4489                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4490                        .and_then(|(buffer_snapshot, range)| {
 4491                            editor
 4492                                .buffer
 4493                                .read(cx)
 4494                                .buffer(buffer_snapshot.remote_id())
 4495                                .map(|buffer| (buffer, range.start.row))
 4496                        })?;
 4497                    let (_, code_actions) = editor
 4498                        .available_code_actions
 4499                        .clone()
 4500                        .and_then(|(location, code_actions)| {
 4501                            let snapshot = location.buffer.read(cx).snapshot();
 4502                            let point_range = location.range.to_point(&snapshot);
 4503                            let point_range = point_range.start.row..=point_range.end.row;
 4504                            if point_range.contains(&buffer_row) {
 4505                                Some((location, code_actions))
 4506                            } else {
 4507                                None
 4508                            }
 4509                        })
 4510                        .unzip();
 4511                    let buffer_id = buffer.read(cx).remote_id();
 4512                    let tasks = editor
 4513                        .tasks
 4514                        .get(&(buffer_id, buffer_row))
 4515                        .map(|t| Arc::new(t.to_owned()));
 4516                    if tasks.is_none() && code_actions.is_none() {
 4517                        return None;
 4518                    }
 4519
 4520                    editor.completion_tasks.clear();
 4521                    editor.discard_inline_completion(false, cx);
 4522                    let task_context =
 4523                        tasks
 4524                            .as_ref()
 4525                            .zip(editor.project.clone())
 4526                            .map(|(tasks, project)| {
 4527                                let position = Point::new(buffer_row, tasks.column);
 4528                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4529                                let location = Location {
 4530                                    buffer: buffer.clone(),
 4531                                    range: range_start..range_start,
 4532                                };
 4533                                // Fill in the environmental variables from the tree-sitter captures
 4534                                let mut captured_task_variables = TaskVariables::default();
 4535                                for (capture_name, value) in tasks.extra_variables.clone() {
 4536                                    captured_task_variables.insert(
 4537                                        task::VariableName::Custom(capture_name.into()),
 4538                                        value.clone(),
 4539                                    );
 4540                                }
 4541                                project.update(cx, |project, cx| {
 4542                                    project.task_context_for_location(
 4543                                        captured_task_variables,
 4544                                        location,
 4545                                        cx,
 4546                                    )
 4547                                })
 4548                            });
 4549
 4550                    Some(cx.spawn(|editor, mut cx| async move {
 4551                        let task_context = match task_context {
 4552                            Some(task_context) => task_context.await,
 4553                            None => None,
 4554                        };
 4555                        let resolved_tasks =
 4556                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4557                                Arc::new(ResolvedTasks {
 4558                                    templates: tasks
 4559                                        .templates
 4560                                        .iter()
 4561                                        .filter_map(|(kind, template)| {
 4562                                            template
 4563                                                .resolve_task(&kind.to_id_base(), &task_context)
 4564                                                .map(|task| (kind.clone(), task))
 4565                                        })
 4566                                        .collect(),
 4567                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4568                                        multibuffer_point.row,
 4569                                        tasks.column,
 4570                                    )),
 4571                                })
 4572                            });
 4573                        let spawn_straight_away = resolved_tasks
 4574                            .as_ref()
 4575                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4576                            && code_actions
 4577                                .as_ref()
 4578                                .map_or(true, |actions| actions.is_empty());
 4579                        if let Some(task) = editor
 4580                            .update(&mut cx, |editor, cx| {
 4581                                *editor.context_menu.write() =
 4582                                    Some(ContextMenu::CodeActions(CodeActionsMenu {
 4583                                        buffer,
 4584                                        actions: CodeActionContents {
 4585                                            tasks: resolved_tasks,
 4586                                            actions: code_actions,
 4587                                        },
 4588                                        selected_item: Default::default(),
 4589                                        scroll_handle: UniformListScrollHandle::default(),
 4590                                        deployed_from_indicator,
 4591                                    }));
 4592                                if spawn_straight_away {
 4593                                    if let Some(task) = editor.confirm_code_action(
 4594                                        &ConfirmCodeAction { item_ix: Some(0) },
 4595                                        cx,
 4596                                    ) {
 4597                                        cx.notify();
 4598                                        return task;
 4599                                    }
 4600                                }
 4601                                cx.notify();
 4602                                Task::ready(Ok(()))
 4603                            })
 4604                            .ok()
 4605                        {
 4606                            task.await
 4607                        } else {
 4608                            Ok(())
 4609                        }
 4610                    }))
 4611                } else {
 4612                    Some(Task::ready(Ok(())))
 4613                }
 4614            })?;
 4615            if let Some(task) = spawned_test_task {
 4616                task.await?;
 4617            }
 4618
 4619            Ok::<_, anyhow::Error>(())
 4620        })
 4621        .detach_and_log_err(cx);
 4622    }
 4623
 4624    pub fn confirm_code_action(
 4625        &mut self,
 4626        action: &ConfirmCodeAction,
 4627        cx: &mut ViewContext<Self>,
 4628    ) -> Option<Task<Result<()>>> {
 4629        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4630            menu
 4631        } else {
 4632            return None;
 4633        };
 4634        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4635        let action = actions_menu.actions.get(action_ix)?;
 4636        let title = action.label();
 4637        let buffer = actions_menu.buffer;
 4638        let workspace = self.workspace()?;
 4639
 4640        match action {
 4641            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4642                workspace.update(cx, |workspace, cx| {
 4643                    workspace::tasks::schedule_resolved_task(
 4644                        workspace,
 4645                        task_source_kind,
 4646                        resolved_task,
 4647                        false,
 4648                        cx,
 4649                    );
 4650
 4651                    Some(Task::ready(Ok(())))
 4652                })
 4653            }
 4654            CodeActionsItem::CodeAction(action) => {
 4655                let apply_code_actions = workspace
 4656                    .read(cx)
 4657                    .project()
 4658                    .clone()
 4659                    .update(cx, |project, cx| {
 4660                        project.apply_code_action(buffer, action, true, cx)
 4661                    });
 4662                let workspace = workspace.downgrade();
 4663                Some(cx.spawn(|editor, cx| async move {
 4664                    let project_transaction = apply_code_actions.await?;
 4665                    Self::open_project_transaction(
 4666                        &editor,
 4667                        workspace,
 4668                        project_transaction,
 4669                        title,
 4670                        cx,
 4671                    )
 4672                    .await
 4673                }))
 4674            }
 4675        }
 4676    }
 4677
 4678    pub async fn open_project_transaction(
 4679        this: &WeakView<Editor>,
 4680        workspace: WeakView<Workspace>,
 4681        transaction: ProjectTransaction,
 4682        title: String,
 4683        mut cx: AsyncWindowContext,
 4684    ) -> Result<()> {
 4685        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 4686
 4687        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4688        cx.update(|cx| {
 4689            entries.sort_unstable_by_key(|(buffer, _)| {
 4690                buffer.read(cx).file().map(|f| f.path().clone())
 4691            });
 4692        })?;
 4693
 4694        // If the project transaction's edits are all contained within this editor, then
 4695        // avoid opening a new editor to display them.
 4696
 4697        if let Some((buffer, transaction)) = entries.first() {
 4698            if entries.len() == 1 {
 4699                let excerpt = this.update(&mut cx, |editor, cx| {
 4700                    editor
 4701                        .buffer()
 4702                        .read(cx)
 4703                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4704                })?;
 4705                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4706                    if excerpted_buffer == *buffer {
 4707                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4708                            let excerpt_range = excerpt_range.to_offset(buffer);
 4709                            buffer
 4710                                .edited_ranges_for_transaction::<usize>(transaction)
 4711                                .all(|range| {
 4712                                    excerpt_range.start <= range.start
 4713                                        && excerpt_range.end >= range.end
 4714                                })
 4715                        })?;
 4716
 4717                        if all_edits_within_excerpt {
 4718                            return Ok(());
 4719                        }
 4720                    }
 4721                }
 4722            }
 4723        } else {
 4724            return Ok(());
 4725        }
 4726
 4727        let mut ranges_to_highlight = Vec::new();
 4728        let excerpt_buffer = cx.new_model(|cx| {
 4729            let mut multibuffer =
 4730                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 4731            for (buffer_handle, transaction) in &entries {
 4732                let buffer = buffer_handle.read(cx);
 4733                ranges_to_highlight.extend(
 4734                    multibuffer.push_excerpts_with_context_lines(
 4735                        buffer_handle.clone(),
 4736                        buffer
 4737                            .edited_ranges_for_transaction::<usize>(transaction)
 4738                            .collect(),
 4739                        DEFAULT_MULTIBUFFER_CONTEXT,
 4740                        cx,
 4741                    ),
 4742                );
 4743            }
 4744            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4745            multibuffer
 4746        })?;
 4747
 4748        workspace.update(&mut cx, |workspace, cx| {
 4749            let project = workspace.project().clone();
 4750            let editor =
 4751                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4752            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4753            editor.update(cx, |editor, cx| {
 4754                editor.highlight_background::<Self>(
 4755                    &ranges_to_highlight,
 4756                    |theme| theme.editor_highlighted_line_background,
 4757                    cx,
 4758                );
 4759            });
 4760        })?;
 4761
 4762        Ok(())
 4763    }
 4764
 4765    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4766        let project = self.project.clone()?;
 4767        let buffer = self.buffer.read(cx);
 4768        let newest_selection = self.selections.newest_anchor().clone();
 4769        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4770        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4771        if start_buffer != end_buffer {
 4772            return None;
 4773        }
 4774
 4775        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4776            cx.background_executor()
 4777                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4778                .await;
 4779
 4780            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4781                project.code_actions(&start_buffer, start..end, cx)
 4782            }) {
 4783                code_actions.await
 4784            } else {
 4785                Vec::new()
 4786            };
 4787
 4788            this.update(&mut cx, |this, cx| {
 4789                this.available_code_actions = if actions.is_empty() {
 4790                    None
 4791                } else {
 4792                    Some((
 4793                        Location {
 4794                            buffer: start_buffer,
 4795                            range: start..end,
 4796                        },
 4797                        actions.into(),
 4798                    ))
 4799                };
 4800                cx.notify();
 4801            })
 4802            .log_err();
 4803        }));
 4804        None
 4805    }
 4806
 4807    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4808        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4809            self.show_git_blame_inline = false;
 4810
 4811            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4812                cx.background_executor().timer(delay).await;
 4813
 4814                this.update(&mut cx, |this, cx| {
 4815                    this.show_git_blame_inline = true;
 4816                    cx.notify();
 4817                })
 4818                .log_err();
 4819            }));
 4820        }
 4821    }
 4822
 4823    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4824        if self.pending_rename.is_some() {
 4825            return None;
 4826        }
 4827
 4828        let project = self.project.clone()?;
 4829        let buffer = self.buffer.read(cx);
 4830        let newest_selection = self.selections.newest_anchor().clone();
 4831        let cursor_position = newest_selection.head();
 4832        let (cursor_buffer, cursor_buffer_position) =
 4833            buffer.text_anchor_for_position(cursor_position, cx)?;
 4834        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4835        if cursor_buffer != tail_buffer {
 4836            return None;
 4837        }
 4838
 4839        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4840            cx.background_executor()
 4841                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4842                .await;
 4843
 4844            let highlights = if let Some(highlights) = project
 4845                .update(&mut cx, |project, cx| {
 4846                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4847                })
 4848                .log_err()
 4849            {
 4850                highlights.await.log_err()
 4851            } else {
 4852                None
 4853            };
 4854
 4855            if let Some(highlights) = highlights {
 4856                this.update(&mut cx, |this, cx| {
 4857                    if this.pending_rename.is_some() {
 4858                        return;
 4859                    }
 4860
 4861                    let buffer_id = cursor_position.buffer_id;
 4862                    let buffer = this.buffer.read(cx);
 4863                    if !buffer
 4864                        .text_anchor_for_position(cursor_position, cx)
 4865                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4866                    {
 4867                        return;
 4868                    }
 4869
 4870                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4871                    let mut write_ranges = Vec::new();
 4872                    let mut read_ranges = Vec::new();
 4873                    for highlight in highlights {
 4874                        for (excerpt_id, excerpt_range) in
 4875                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4876                        {
 4877                            let start = highlight
 4878                                .range
 4879                                .start
 4880                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4881                            let end = highlight
 4882                                .range
 4883                                .end
 4884                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4885                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4886                                continue;
 4887                            }
 4888
 4889                            let range = Anchor {
 4890                                buffer_id,
 4891                                excerpt_id,
 4892                                text_anchor: start,
 4893                            }..Anchor {
 4894                                buffer_id,
 4895                                excerpt_id,
 4896                                text_anchor: end,
 4897                            };
 4898                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4899                                write_ranges.push(range);
 4900                            } else {
 4901                                read_ranges.push(range);
 4902                            }
 4903                        }
 4904                    }
 4905
 4906                    this.highlight_background::<DocumentHighlightRead>(
 4907                        &read_ranges,
 4908                        |theme| theme.editor_document_highlight_read_background,
 4909                        cx,
 4910                    );
 4911                    this.highlight_background::<DocumentHighlightWrite>(
 4912                        &write_ranges,
 4913                        |theme| theme.editor_document_highlight_write_background,
 4914                        cx,
 4915                    );
 4916                    cx.notify();
 4917                })
 4918                .log_err();
 4919            }
 4920        }));
 4921        None
 4922    }
 4923
 4924    pub fn refresh_inline_completion(
 4925        &mut self,
 4926        debounce: bool,
 4927        user_requested: bool,
 4928        cx: &mut ViewContext<Self>,
 4929    ) -> Option<()> {
 4930        let provider = self.inline_completion_provider()?;
 4931        let cursor = self.selections.newest_anchor().head();
 4932        let (buffer, cursor_buffer_position) =
 4933            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4934        if !user_requested
 4935            && (!self.show_inline_completions
 4936                || !provider.is_enabled(&buffer, cursor_buffer_position, cx))
 4937        {
 4938            self.discard_inline_completion(false, cx);
 4939            return None;
 4940        }
 4941
 4942        self.update_visible_inline_completion(cx);
 4943        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4944        Some(())
 4945    }
 4946
 4947    fn cycle_inline_completion(
 4948        &mut self,
 4949        direction: Direction,
 4950        cx: &mut ViewContext<Self>,
 4951    ) -> Option<()> {
 4952        let provider = self.inline_completion_provider()?;
 4953        let cursor = self.selections.newest_anchor().head();
 4954        let (buffer, cursor_buffer_position) =
 4955            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4956        if !self.show_inline_completions
 4957            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4958        {
 4959            return None;
 4960        }
 4961
 4962        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4963        self.update_visible_inline_completion(cx);
 4964
 4965        Some(())
 4966    }
 4967
 4968    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4969        if !self.has_active_inline_completion(cx) {
 4970            self.refresh_inline_completion(false, true, cx);
 4971            return;
 4972        }
 4973
 4974        self.update_visible_inline_completion(cx);
 4975    }
 4976
 4977    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4978        self.show_cursor_names(cx);
 4979    }
 4980
 4981    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4982        self.show_cursor_names = true;
 4983        cx.notify();
 4984        cx.spawn(|this, mut cx| async move {
 4985            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4986            this.update(&mut cx, |this, cx| {
 4987                this.show_cursor_names = false;
 4988                cx.notify()
 4989            })
 4990            .ok()
 4991        })
 4992        .detach();
 4993    }
 4994
 4995    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4996        if self.has_active_inline_completion(cx) {
 4997            self.cycle_inline_completion(Direction::Next, cx);
 4998        } else {
 4999            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5000            if is_copilot_disabled {
 5001                cx.propagate();
 5002            }
 5003        }
 5004    }
 5005
 5006    pub fn previous_inline_completion(
 5007        &mut self,
 5008        _: &PreviousInlineCompletion,
 5009        cx: &mut ViewContext<Self>,
 5010    ) {
 5011        if self.has_active_inline_completion(cx) {
 5012            self.cycle_inline_completion(Direction::Prev, cx);
 5013        } else {
 5014            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5015            if is_copilot_disabled {
 5016                cx.propagate();
 5017            }
 5018        }
 5019    }
 5020
 5021    pub fn accept_inline_completion(
 5022        &mut self,
 5023        _: &AcceptInlineCompletion,
 5024        cx: &mut ViewContext<Self>,
 5025    ) {
 5026        let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
 5027            return;
 5028        };
 5029        if let Some(provider) = self.inline_completion_provider() {
 5030            provider.accept(cx);
 5031        }
 5032
 5033        cx.emit(EditorEvent::InputHandled {
 5034            utf16_range_to_replace: None,
 5035            text: completion.text.to_string().into(),
 5036        });
 5037
 5038        if let Some(range) = delete_range {
 5039            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5040        }
 5041        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5042        self.refresh_inline_completion(true, true, cx);
 5043        cx.notify();
 5044    }
 5045
 5046    pub fn accept_partial_inline_completion(
 5047        &mut self,
 5048        _: &AcceptPartialInlineCompletion,
 5049        cx: &mut ViewContext<Self>,
 5050    ) {
 5051        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5052            if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
 5053                let mut partial_completion = completion
 5054                    .text
 5055                    .chars()
 5056                    .by_ref()
 5057                    .take_while(|c| c.is_alphabetic())
 5058                    .collect::<String>();
 5059                if partial_completion.is_empty() {
 5060                    partial_completion = completion
 5061                        .text
 5062                        .chars()
 5063                        .by_ref()
 5064                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5065                        .collect::<String>();
 5066                }
 5067
 5068                cx.emit(EditorEvent::InputHandled {
 5069                    utf16_range_to_replace: None,
 5070                    text: partial_completion.clone().into(),
 5071                });
 5072
 5073                if let Some(range) = delete_range {
 5074                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5075                }
 5076                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5077
 5078                self.refresh_inline_completion(true, true, cx);
 5079                cx.notify();
 5080            }
 5081        }
 5082    }
 5083
 5084    fn discard_inline_completion(
 5085        &mut self,
 5086        should_report_inline_completion_event: bool,
 5087        cx: &mut ViewContext<Self>,
 5088    ) -> bool {
 5089        if let Some(provider) = self.inline_completion_provider() {
 5090            provider.discard(should_report_inline_completion_event, cx);
 5091        }
 5092
 5093        self.take_active_inline_completion(cx).is_some()
 5094    }
 5095
 5096    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5097        if let Some(completion) = self.active_inline_completion.as_ref() {
 5098            let buffer = self.buffer.read(cx).read(cx);
 5099            completion.0.position.is_valid(&buffer)
 5100        } else {
 5101            false
 5102        }
 5103    }
 5104
 5105    fn take_active_inline_completion(
 5106        &mut self,
 5107        cx: &mut ViewContext<Self>,
 5108    ) -> Option<(Inlay, Option<Range<Anchor>>)> {
 5109        let completion = self.active_inline_completion.take()?;
 5110        self.display_map.update(cx, |map, cx| {
 5111            map.splice_inlays(vec![completion.0.id], Default::default(), cx);
 5112        });
 5113        let buffer = self.buffer.read(cx).read(cx);
 5114
 5115        if completion.0.position.is_valid(&buffer) {
 5116            Some(completion)
 5117        } else {
 5118            None
 5119        }
 5120    }
 5121
 5122    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5123        let selection = self.selections.newest_anchor();
 5124        let cursor = selection.head();
 5125
 5126        let excerpt_id = cursor.excerpt_id;
 5127
 5128        if self.context_menu.read().is_none()
 5129            && self.completion_tasks.is_empty()
 5130            && selection.start == selection.end
 5131        {
 5132            if let Some(provider) = self.inline_completion_provider() {
 5133                if let Some((buffer, cursor_buffer_position)) =
 5134                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5135                {
 5136                    if let Some((text, text_anchor_range)) =
 5137                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5138                    {
 5139                        let text = Rope::from(text);
 5140                        let mut to_remove = Vec::new();
 5141                        if let Some(completion) = self.active_inline_completion.take() {
 5142                            to_remove.push(completion.0.id);
 5143                        }
 5144
 5145                        let completion_inlay =
 5146                            Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
 5147
 5148                        let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
 5149                            let snapshot = self.buffer.read(cx).snapshot(cx);
 5150                            Some(
 5151                                snapshot.anchor_in_excerpt(excerpt_id, range.start)?
 5152                                    ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
 5153                            )
 5154                        });
 5155                        self.active_inline_completion =
 5156                            Some((completion_inlay.clone(), multibuffer_anchor_range));
 5157
 5158                        self.display_map.update(cx, move |map, cx| {
 5159                            map.splice_inlays(to_remove, vec![completion_inlay], cx)
 5160                        });
 5161                        cx.notify();
 5162                        return;
 5163                    }
 5164                }
 5165            }
 5166        }
 5167
 5168        self.discard_inline_completion(false, cx);
 5169    }
 5170
 5171    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5172        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5173    }
 5174
 5175    fn render_code_actions_indicator(
 5176        &self,
 5177        _style: &EditorStyle,
 5178        row: DisplayRow,
 5179        is_active: bool,
 5180        cx: &mut ViewContext<Self>,
 5181    ) -> Option<IconButton> {
 5182        if self.available_code_actions.is_some() {
 5183            Some(
 5184                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5185                    .shape(ui::IconButtonShape::Square)
 5186                    .icon_size(IconSize::XSmall)
 5187                    .icon_color(Color::Muted)
 5188                    .selected(is_active)
 5189                    .on_click(cx.listener(move |editor, _e, cx| {
 5190                        editor.focus(cx);
 5191                        editor.toggle_code_actions(
 5192                            &ToggleCodeActions {
 5193                                deployed_from_indicator: Some(row),
 5194                            },
 5195                            cx,
 5196                        );
 5197                    })),
 5198            )
 5199        } else {
 5200            None
 5201        }
 5202    }
 5203
 5204    fn clear_tasks(&mut self) {
 5205        self.tasks.clear()
 5206    }
 5207
 5208    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5209        if let Some(_) = self.tasks.insert(key, value) {
 5210            // This case should hopefully be rare, but just in case...
 5211            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5212        }
 5213    }
 5214
 5215    fn render_run_indicator(
 5216        &self,
 5217        _style: &EditorStyle,
 5218        is_active: bool,
 5219        row: DisplayRow,
 5220        cx: &mut ViewContext<Self>,
 5221    ) -> IconButton {
 5222        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5223            .shape(ui::IconButtonShape::Square)
 5224            .icon_size(IconSize::XSmall)
 5225            .icon_color(Color::Muted)
 5226            .selected(is_active)
 5227            .on_click(cx.listener(move |editor, _e, cx| {
 5228                editor.focus(cx);
 5229                editor.toggle_code_actions(
 5230                    &ToggleCodeActions {
 5231                        deployed_from_indicator: Some(row),
 5232                    },
 5233                    cx,
 5234                );
 5235            }))
 5236    }
 5237
 5238    fn close_hunk_diff_button(
 5239        &self,
 5240        hunk: HoveredHunk,
 5241        row: DisplayRow,
 5242        cx: &mut ViewContext<Self>,
 5243    ) -> IconButton {
 5244        IconButton::new(
 5245            ("close_hunk_diff_indicator", row.0 as usize),
 5246            ui::IconName::Close,
 5247        )
 5248        .shape(ui::IconButtonShape::Square)
 5249        .icon_size(IconSize::XSmall)
 5250        .icon_color(Color::Muted)
 5251        .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
 5252        .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
 5253    }
 5254
 5255    pub fn context_menu_visible(&self) -> bool {
 5256        self.context_menu
 5257            .read()
 5258            .as_ref()
 5259            .map_or(false, |menu| menu.visible())
 5260    }
 5261
 5262    fn render_context_menu(
 5263        &self,
 5264        cursor_position: DisplayPoint,
 5265        style: &EditorStyle,
 5266        max_height: Pixels,
 5267        cx: &mut ViewContext<Editor>,
 5268    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5269        self.context_menu.read().as_ref().map(|menu| {
 5270            menu.render(
 5271                cursor_position,
 5272                style,
 5273                max_height,
 5274                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5275                cx,
 5276            )
 5277        })
 5278    }
 5279
 5280    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5281        cx.notify();
 5282        self.completion_tasks.clear();
 5283        let context_menu = self.context_menu.write().take();
 5284        if context_menu.is_some() {
 5285            self.update_visible_inline_completion(cx);
 5286        }
 5287        context_menu
 5288    }
 5289
 5290    pub fn insert_snippet(
 5291        &mut self,
 5292        insertion_ranges: &[Range<usize>],
 5293        snippet: Snippet,
 5294        cx: &mut ViewContext<Self>,
 5295    ) -> Result<()> {
 5296        struct Tabstop<T> {
 5297            is_end_tabstop: bool,
 5298            ranges: Vec<Range<T>>,
 5299        }
 5300
 5301        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5302            let snippet_text: Arc<str> = snippet.text.clone().into();
 5303            buffer.edit(
 5304                insertion_ranges
 5305                    .iter()
 5306                    .cloned()
 5307                    .map(|range| (range, snippet_text.clone())),
 5308                Some(AutoindentMode::EachLine),
 5309                cx,
 5310            );
 5311
 5312            let snapshot = &*buffer.read(cx);
 5313            let snippet = &snippet;
 5314            snippet
 5315                .tabstops
 5316                .iter()
 5317                .map(|tabstop| {
 5318                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5319                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5320                    });
 5321                    let mut tabstop_ranges = tabstop
 5322                        .iter()
 5323                        .flat_map(|tabstop_range| {
 5324                            let mut delta = 0_isize;
 5325                            insertion_ranges.iter().map(move |insertion_range| {
 5326                                let insertion_start = insertion_range.start as isize + delta;
 5327                                delta +=
 5328                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5329
 5330                                let start = ((insertion_start + tabstop_range.start) as usize)
 5331                                    .min(snapshot.len());
 5332                                let end = ((insertion_start + tabstop_range.end) as usize)
 5333                                    .min(snapshot.len());
 5334                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5335                            })
 5336                        })
 5337                        .collect::<Vec<_>>();
 5338                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5339
 5340                    Tabstop {
 5341                        is_end_tabstop,
 5342                        ranges: tabstop_ranges,
 5343                    }
 5344                })
 5345                .collect::<Vec<_>>()
 5346        });
 5347        if let Some(tabstop) = tabstops.first() {
 5348            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5349                s.select_ranges(tabstop.ranges.iter().cloned());
 5350            });
 5351
 5352            // If we're already at the last tabstop and it's at the end of the snippet,
 5353            // we're done, we don't need to keep the state around.
 5354            if !tabstop.is_end_tabstop {
 5355                let ranges = tabstops
 5356                    .into_iter()
 5357                    .map(|tabstop| tabstop.ranges)
 5358                    .collect::<Vec<_>>();
 5359                self.snippet_stack.push(SnippetState {
 5360                    active_index: 0,
 5361                    ranges,
 5362                });
 5363            }
 5364
 5365            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5366            if self.autoclose_regions.is_empty() {
 5367                let snapshot = self.buffer.read(cx).snapshot(cx);
 5368                for selection in &mut self.selections.all::<Point>(cx) {
 5369                    let selection_head = selection.head();
 5370                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5371                        continue;
 5372                    };
 5373
 5374                    let mut bracket_pair = None;
 5375                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5376                    let prev_chars = snapshot
 5377                        .reversed_chars_at(selection_head)
 5378                        .collect::<String>();
 5379                    for (pair, enabled) in scope.brackets() {
 5380                        if enabled
 5381                            && pair.close
 5382                            && prev_chars.starts_with(pair.start.as_str())
 5383                            && next_chars.starts_with(pair.end.as_str())
 5384                        {
 5385                            bracket_pair = Some(pair.clone());
 5386                            break;
 5387                        }
 5388                    }
 5389                    if let Some(pair) = bracket_pair {
 5390                        let start = snapshot.anchor_after(selection_head);
 5391                        let end = snapshot.anchor_after(selection_head);
 5392                        self.autoclose_regions.push(AutocloseRegion {
 5393                            selection_id: selection.id,
 5394                            range: start..end,
 5395                            pair,
 5396                        });
 5397                    }
 5398                }
 5399            }
 5400        }
 5401        Ok(())
 5402    }
 5403
 5404    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5405        self.move_to_snippet_tabstop(Bias::Right, cx)
 5406    }
 5407
 5408    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5409        self.move_to_snippet_tabstop(Bias::Left, cx)
 5410    }
 5411
 5412    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5413        if let Some(mut snippet) = self.snippet_stack.pop() {
 5414            match bias {
 5415                Bias::Left => {
 5416                    if snippet.active_index > 0 {
 5417                        snippet.active_index -= 1;
 5418                    } else {
 5419                        self.snippet_stack.push(snippet);
 5420                        return false;
 5421                    }
 5422                }
 5423                Bias::Right => {
 5424                    if snippet.active_index + 1 < snippet.ranges.len() {
 5425                        snippet.active_index += 1;
 5426                    } else {
 5427                        self.snippet_stack.push(snippet);
 5428                        return false;
 5429                    }
 5430                }
 5431            }
 5432            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5433                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5434                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5435                });
 5436                // If snippet state is not at the last tabstop, push it back on the stack
 5437                if snippet.active_index + 1 < snippet.ranges.len() {
 5438                    self.snippet_stack.push(snippet);
 5439                }
 5440                return true;
 5441            }
 5442        }
 5443
 5444        false
 5445    }
 5446
 5447    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5448        self.transact(cx, |this, cx| {
 5449            this.select_all(&SelectAll, cx);
 5450            this.insert("", cx);
 5451        });
 5452    }
 5453
 5454    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5455        self.transact(cx, |this, cx| {
 5456            this.select_autoclose_pair(cx);
 5457            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5458            if !this.linked_edit_ranges.is_empty() {
 5459                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5460                let snapshot = this.buffer.read(cx).snapshot(cx);
 5461
 5462                for selection in selections.iter() {
 5463                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5464                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5465                    if selection_start.buffer_id != selection_end.buffer_id {
 5466                        continue;
 5467                    }
 5468                    if let Some(ranges) =
 5469                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5470                    {
 5471                        for (buffer, entries) in ranges {
 5472                            linked_ranges.entry(buffer).or_default().extend(entries);
 5473                        }
 5474                    }
 5475                }
 5476            }
 5477
 5478            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5479            if !this.selections.line_mode {
 5480                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5481                for selection in &mut selections {
 5482                    if selection.is_empty() {
 5483                        let old_head = selection.head();
 5484                        let mut new_head =
 5485                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5486                                .to_point(&display_map);
 5487                        if let Some((buffer, line_buffer_range)) = display_map
 5488                            .buffer_snapshot
 5489                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5490                        {
 5491                            let indent_size =
 5492                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5493                            let indent_len = match indent_size.kind {
 5494                                IndentKind::Space => {
 5495                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5496                                }
 5497                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5498                            };
 5499                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5500                                let indent_len = indent_len.get();
 5501                                new_head = cmp::min(
 5502                                    new_head,
 5503                                    MultiBufferPoint::new(
 5504                                        old_head.row,
 5505                                        ((old_head.column - 1) / indent_len) * indent_len,
 5506                                    ),
 5507                                );
 5508                            }
 5509                        }
 5510
 5511                        selection.set_head(new_head, SelectionGoal::None);
 5512                    }
 5513                }
 5514            }
 5515
 5516            this.signature_help_state.set_backspace_pressed(true);
 5517            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5518            this.insert("", cx);
 5519            let empty_str: Arc<str> = Arc::from("");
 5520            for (buffer, edits) in linked_ranges {
 5521                let snapshot = buffer.read(cx).snapshot();
 5522                use text::ToPoint as TP;
 5523
 5524                let edits = edits
 5525                    .into_iter()
 5526                    .map(|range| {
 5527                        let end_point = TP::to_point(&range.end, &snapshot);
 5528                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5529
 5530                        if end_point == start_point {
 5531                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5532                                .saturating_sub(1);
 5533                            start_point = TP::to_point(&offset, &snapshot);
 5534                        };
 5535
 5536                        (start_point..end_point, empty_str.clone())
 5537                    })
 5538                    .sorted_by_key(|(range, _)| range.start)
 5539                    .collect::<Vec<_>>();
 5540                buffer.update(cx, |this, cx| {
 5541                    this.edit(edits, None, cx);
 5542                })
 5543            }
 5544            this.refresh_inline_completion(true, false, cx);
 5545            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5546        });
 5547    }
 5548
 5549    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5550        self.transact(cx, |this, cx| {
 5551            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5552                let line_mode = s.line_mode;
 5553                s.move_with(|map, selection| {
 5554                    if selection.is_empty() && !line_mode {
 5555                        let cursor = movement::right(map, selection.head());
 5556                        selection.end = cursor;
 5557                        selection.reversed = true;
 5558                        selection.goal = SelectionGoal::None;
 5559                    }
 5560                })
 5561            });
 5562            this.insert("", cx);
 5563            this.refresh_inline_completion(true, false, cx);
 5564        });
 5565    }
 5566
 5567    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5568        if self.move_to_prev_snippet_tabstop(cx) {
 5569            return;
 5570        }
 5571
 5572        self.outdent(&Outdent, cx);
 5573    }
 5574
 5575    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5576        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5577            return;
 5578        }
 5579
 5580        let mut selections = self.selections.all_adjusted(cx);
 5581        let buffer = self.buffer.read(cx);
 5582        let snapshot = buffer.snapshot(cx);
 5583        let rows_iter = selections.iter().map(|s| s.head().row);
 5584        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5585
 5586        let mut edits = Vec::new();
 5587        let mut prev_edited_row = 0;
 5588        let mut row_delta = 0;
 5589        for selection in &mut selections {
 5590            if selection.start.row != prev_edited_row {
 5591                row_delta = 0;
 5592            }
 5593            prev_edited_row = selection.end.row;
 5594
 5595            // If the selection is non-empty, then increase the indentation of the selected lines.
 5596            if !selection.is_empty() {
 5597                row_delta =
 5598                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5599                continue;
 5600            }
 5601
 5602            // If the selection is empty and the cursor is in the leading whitespace before the
 5603            // suggested indentation, then auto-indent the line.
 5604            let cursor = selection.head();
 5605            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5606            if let Some(suggested_indent) =
 5607                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5608            {
 5609                if cursor.column < suggested_indent.len
 5610                    && cursor.column <= current_indent.len
 5611                    && current_indent.len <= suggested_indent.len
 5612                {
 5613                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5614                    selection.end = selection.start;
 5615                    if row_delta == 0 {
 5616                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5617                            cursor.row,
 5618                            current_indent,
 5619                            suggested_indent,
 5620                        ));
 5621                        row_delta = suggested_indent.len - current_indent.len;
 5622                    }
 5623                    continue;
 5624                }
 5625            }
 5626
 5627            // Otherwise, insert a hard or soft tab.
 5628            let settings = buffer.settings_at(cursor, cx);
 5629            let tab_size = if settings.hard_tabs {
 5630                IndentSize::tab()
 5631            } else {
 5632                let tab_size = settings.tab_size.get();
 5633                let char_column = snapshot
 5634                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5635                    .flat_map(str::chars)
 5636                    .count()
 5637                    + row_delta as usize;
 5638                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5639                IndentSize::spaces(chars_to_next_tab_stop)
 5640            };
 5641            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5642            selection.end = selection.start;
 5643            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5644            row_delta += tab_size.len;
 5645        }
 5646
 5647        self.transact(cx, |this, cx| {
 5648            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5649            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5650            this.refresh_inline_completion(true, false, cx);
 5651        });
 5652    }
 5653
 5654    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5655        if self.read_only(cx) {
 5656            return;
 5657        }
 5658        let mut selections = self.selections.all::<Point>(cx);
 5659        let mut prev_edited_row = 0;
 5660        let mut row_delta = 0;
 5661        let mut edits = Vec::new();
 5662        let buffer = self.buffer.read(cx);
 5663        let snapshot = buffer.snapshot(cx);
 5664        for selection in &mut selections {
 5665            if selection.start.row != prev_edited_row {
 5666                row_delta = 0;
 5667            }
 5668            prev_edited_row = selection.end.row;
 5669
 5670            row_delta =
 5671                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5672        }
 5673
 5674        self.transact(cx, |this, cx| {
 5675            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5676            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5677        });
 5678    }
 5679
 5680    fn indent_selection(
 5681        buffer: &MultiBuffer,
 5682        snapshot: &MultiBufferSnapshot,
 5683        selection: &mut Selection<Point>,
 5684        edits: &mut Vec<(Range<Point>, String)>,
 5685        delta_for_start_row: u32,
 5686        cx: &AppContext,
 5687    ) -> u32 {
 5688        let settings = buffer.settings_at(selection.start, cx);
 5689        let tab_size = settings.tab_size.get();
 5690        let indent_kind = if settings.hard_tabs {
 5691            IndentKind::Tab
 5692        } else {
 5693            IndentKind::Space
 5694        };
 5695        let mut start_row = selection.start.row;
 5696        let mut end_row = selection.end.row + 1;
 5697
 5698        // If a selection ends at the beginning of a line, don't indent
 5699        // that last line.
 5700        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5701            end_row -= 1;
 5702        }
 5703
 5704        // Avoid re-indenting a row that has already been indented by a
 5705        // previous selection, but still update this selection's column
 5706        // to reflect that indentation.
 5707        if delta_for_start_row > 0 {
 5708            start_row += 1;
 5709            selection.start.column += delta_for_start_row;
 5710            if selection.end.row == selection.start.row {
 5711                selection.end.column += delta_for_start_row;
 5712            }
 5713        }
 5714
 5715        let mut delta_for_end_row = 0;
 5716        let has_multiple_rows = start_row + 1 != end_row;
 5717        for row in start_row..end_row {
 5718            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5719            let indent_delta = match (current_indent.kind, indent_kind) {
 5720                (IndentKind::Space, IndentKind::Space) => {
 5721                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5722                    IndentSize::spaces(columns_to_next_tab_stop)
 5723                }
 5724                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5725                (_, IndentKind::Tab) => IndentSize::tab(),
 5726            };
 5727
 5728            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5729                0
 5730            } else {
 5731                selection.start.column
 5732            };
 5733            let row_start = Point::new(row, start);
 5734            edits.push((
 5735                row_start..row_start,
 5736                indent_delta.chars().collect::<String>(),
 5737            ));
 5738
 5739            // Update this selection's endpoints to reflect the indentation.
 5740            if row == selection.start.row {
 5741                selection.start.column += indent_delta.len;
 5742            }
 5743            if row == selection.end.row {
 5744                selection.end.column += indent_delta.len;
 5745                delta_for_end_row = indent_delta.len;
 5746            }
 5747        }
 5748
 5749        if selection.start.row == selection.end.row {
 5750            delta_for_start_row + delta_for_end_row
 5751        } else {
 5752            delta_for_end_row
 5753        }
 5754    }
 5755
 5756    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5757        if self.read_only(cx) {
 5758            return;
 5759        }
 5760        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5761        let selections = self.selections.all::<Point>(cx);
 5762        let mut deletion_ranges = Vec::new();
 5763        let mut last_outdent = None;
 5764        {
 5765            let buffer = self.buffer.read(cx);
 5766            let snapshot = buffer.snapshot(cx);
 5767            for selection in &selections {
 5768                let settings = buffer.settings_at(selection.start, cx);
 5769                let tab_size = settings.tab_size.get();
 5770                let mut rows = selection.spanned_rows(false, &display_map);
 5771
 5772                // Avoid re-outdenting a row that has already been outdented by a
 5773                // previous selection.
 5774                if let Some(last_row) = last_outdent {
 5775                    if last_row == rows.start {
 5776                        rows.start = rows.start.next_row();
 5777                    }
 5778                }
 5779                let has_multiple_rows = rows.len() > 1;
 5780                for row in rows.iter_rows() {
 5781                    let indent_size = snapshot.indent_size_for_line(row);
 5782                    if indent_size.len > 0 {
 5783                        let deletion_len = match indent_size.kind {
 5784                            IndentKind::Space => {
 5785                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5786                                if columns_to_prev_tab_stop == 0 {
 5787                                    tab_size
 5788                                } else {
 5789                                    columns_to_prev_tab_stop
 5790                                }
 5791                            }
 5792                            IndentKind::Tab => 1,
 5793                        };
 5794                        let start = if has_multiple_rows
 5795                            || deletion_len > selection.start.column
 5796                            || indent_size.len < selection.start.column
 5797                        {
 5798                            0
 5799                        } else {
 5800                            selection.start.column - deletion_len
 5801                        };
 5802                        deletion_ranges.push(
 5803                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5804                        );
 5805                        last_outdent = Some(row);
 5806                    }
 5807                }
 5808            }
 5809        }
 5810
 5811        self.transact(cx, |this, cx| {
 5812            this.buffer.update(cx, |buffer, cx| {
 5813                let empty_str: Arc<str> = Arc::default();
 5814                buffer.edit(
 5815                    deletion_ranges
 5816                        .into_iter()
 5817                        .map(|range| (range, empty_str.clone())),
 5818                    None,
 5819                    cx,
 5820                );
 5821            });
 5822            let selections = this.selections.all::<usize>(cx);
 5823            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5824        });
 5825    }
 5826
 5827    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5828        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5829        let selections = self.selections.all::<Point>(cx);
 5830
 5831        let mut new_cursors = Vec::new();
 5832        let mut edit_ranges = Vec::new();
 5833        let mut selections = selections.iter().peekable();
 5834        while let Some(selection) = selections.next() {
 5835            let mut rows = selection.spanned_rows(false, &display_map);
 5836            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5837
 5838            // Accumulate contiguous regions of rows that we want to delete.
 5839            while let Some(next_selection) = selections.peek() {
 5840                let next_rows = next_selection.spanned_rows(false, &display_map);
 5841                if next_rows.start <= rows.end {
 5842                    rows.end = next_rows.end;
 5843                    selections.next().unwrap();
 5844                } else {
 5845                    break;
 5846                }
 5847            }
 5848
 5849            let buffer = &display_map.buffer_snapshot;
 5850            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5851            let edit_end;
 5852            let cursor_buffer_row;
 5853            if buffer.max_point().row >= rows.end.0 {
 5854                // If there's a line after the range, delete the \n from the end of the row range
 5855                // and position the cursor on the next line.
 5856                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5857                cursor_buffer_row = rows.end;
 5858            } else {
 5859                // If there isn't a line after the range, delete the \n from the line before the
 5860                // start of the row range and position the cursor there.
 5861                edit_start = edit_start.saturating_sub(1);
 5862                edit_end = buffer.len();
 5863                cursor_buffer_row = rows.start.previous_row();
 5864            }
 5865
 5866            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5867            *cursor.column_mut() =
 5868                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5869
 5870            new_cursors.push((
 5871                selection.id,
 5872                buffer.anchor_after(cursor.to_point(&display_map)),
 5873            ));
 5874            edit_ranges.push(edit_start..edit_end);
 5875        }
 5876
 5877        self.transact(cx, |this, cx| {
 5878            let buffer = this.buffer.update(cx, |buffer, cx| {
 5879                let empty_str: Arc<str> = Arc::default();
 5880                buffer.edit(
 5881                    edit_ranges
 5882                        .into_iter()
 5883                        .map(|range| (range, empty_str.clone())),
 5884                    None,
 5885                    cx,
 5886                );
 5887                buffer.snapshot(cx)
 5888            });
 5889            let new_selections = new_cursors
 5890                .into_iter()
 5891                .map(|(id, cursor)| {
 5892                    let cursor = cursor.to_point(&buffer);
 5893                    Selection {
 5894                        id,
 5895                        start: cursor,
 5896                        end: cursor,
 5897                        reversed: false,
 5898                        goal: SelectionGoal::None,
 5899                    }
 5900                })
 5901                .collect();
 5902
 5903            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5904                s.select(new_selections);
 5905            });
 5906        });
 5907    }
 5908
 5909    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5910        if self.read_only(cx) {
 5911            return;
 5912        }
 5913        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5914        for selection in self.selections.all::<Point>(cx) {
 5915            let start = MultiBufferRow(selection.start.row);
 5916            let end = if selection.start.row == selection.end.row {
 5917                MultiBufferRow(selection.start.row + 1)
 5918            } else {
 5919                MultiBufferRow(selection.end.row)
 5920            };
 5921
 5922            if let Some(last_row_range) = row_ranges.last_mut() {
 5923                if start <= last_row_range.end {
 5924                    last_row_range.end = end;
 5925                    continue;
 5926                }
 5927            }
 5928            row_ranges.push(start..end);
 5929        }
 5930
 5931        let snapshot = self.buffer.read(cx).snapshot(cx);
 5932        let mut cursor_positions = Vec::new();
 5933        for row_range in &row_ranges {
 5934            let anchor = snapshot.anchor_before(Point::new(
 5935                row_range.end.previous_row().0,
 5936                snapshot.line_len(row_range.end.previous_row()),
 5937            ));
 5938            cursor_positions.push(anchor..anchor);
 5939        }
 5940
 5941        self.transact(cx, |this, cx| {
 5942            for row_range in row_ranges.into_iter().rev() {
 5943                for row in row_range.iter_rows().rev() {
 5944                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5945                    let next_line_row = row.next_row();
 5946                    let indent = snapshot.indent_size_for_line(next_line_row);
 5947                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5948
 5949                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5950                        " "
 5951                    } else {
 5952                        ""
 5953                    };
 5954
 5955                    this.buffer.update(cx, |buffer, cx| {
 5956                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5957                    });
 5958                }
 5959            }
 5960
 5961            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5962                s.select_anchor_ranges(cursor_positions)
 5963            });
 5964        });
 5965    }
 5966
 5967    pub fn sort_lines_case_sensitive(
 5968        &mut self,
 5969        _: &SortLinesCaseSensitive,
 5970        cx: &mut ViewContext<Self>,
 5971    ) {
 5972        self.manipulate_lines(cx, |lines| lines.sort())
 5973    }
 5974
 5975    pub fn sort_lines_case_insensitive(
 5976        &mut self,
 5977        _: &SortLinesCaseInsensitive,
 5978        cx: &mut ViewContext<Self>,
 5979    ) {
 5980        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5981    }
 5982
 5983    pub fn unique_lines_case_insensitive(
 5984        &mut self,
 5985        _: &UniqueLinesCaseInsensitive,
 5986        cx: &mut ViewContext<Self>,
 5987    ) {
 5988        self.manipulate_lines(cx, |lines| {
 5989            let mut seen = HashSet::default();
 5990            lines.retain(|line| seen.insert(line.to_lowercase()));
 5991        })
 5992    }
 5993
 5994    pub fn unique_lines_case_sensitive(
 5995        &mut self,
 5996        _: &UniqueLinesCaseSensitive,
 5997        cx: &mut ViewContext<Self>,
 5998    ) {
 5999        self.manipulate_lines(cx, |lines| {
 6000            let mut seen = HashSet::default();
 6001            lines.retain(|line| seen.insert(*line));
 6002        })
 6003    }
 6004
 6005    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6006        let mut revert_changes = HashMap::default();
 6007        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6008        for hunk in hunks_for_rows(
 6009            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6010            &multi_buffer_snapshot,
 6011        ) {
 6012            Self::prepare_revert_change(&mut revert_changes, &self.buffer(), &hunk, cx);
 6013        }
 6014        if !revert_changes.is_empty() {
 6015            self.transact(cx, |editor, cx| {
 6016                editor.revert(revert_changes, cx);
 6017            });
 6018        }
 6019    }
 6020
 6021    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6022        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6023        if !revert_changes.is_empty() {
 6024            self.transact(cx, |editor, cx| {
 6025                editor.revert(revert_changes, cx);
 6026            });
 6027        }
 6028    }
 6029
 6030    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6031        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6032            let project_path = buffer.read(cx).project_path(cx)?;
 6033            let project = self.project.as_ref()?.read(cx);
 6034            let entry = project.entry_for_path(&project_path, cx)?;
 6035            let abs_path = project.absolute_path(&project_path, cx)?;
 6036            let parent = if entry.is_symlink {
 6037                abs_path.canonicalize().ok()?
 6038            } else {
 6039                abs_path
 6040            }
 6041            .parent()?
 6042            .to_path_buf();
 6043            Some(parent)
 6044        }) {
 6045            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6046        }
 6047    }
 6048
 6049    fn gather_revert_changes(
 6050        &mut self,
 6051        selections: &[Selection<Anchor>],
 6052        cx: &mut ViewContext<'_, Editor>,
 6053    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6054        let mut revert_changes = HashMap::default();
 6055        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6056        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6057            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6058        }
 6059        revert_changes
 6060    }
 6061
 6062    pub fn prepare_revert_change(
 6063        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6064        multi_buffer: &Model<MultiBuffer>,
 6065        hunk: &DiffHunk<MultiBufferRow>,
 6066        cx: &AppContext,
 6067    ) -> Option<()> {
 6068        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6069        let buffer = buffer.read(cx);
 6070        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6071        let buffer_snapshot = buffer.snapshot();
 6072        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6073        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6074            probe
 6075                .0
 6076                .start
 6077                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6078                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6079        }) {
 6080            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6081            Some(())
 6082        } else {
 6083            None
 6084        }
 6085    }
 6086
 6087    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6088        self.manipulate_lines(cx, |lines| lines.reverse())
 6089    }
 6090
 6091    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6092        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6093    }
 6094
 6095    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6096    where
 6097        Fn: FnMut(&mut Vec<&str>),
 6098    {
 6099        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6100        let buffer = self.buffer.read(cx).snapshot(cx);
 6101
 6102        let mut edits = Vec::new();
 6103
 6104        let selections = self.selections.all::<Point>(cx);
 6105        let mut selections = selections.iter().peekable();
 6106        let mut contiguous_row_selections = Vec::new();
 6107        let mut new_selections = Vec::new();
 6108        let mut added_lines = 0;
 6109        let mut removed_lines = 0;
 6110
 6111        while let Some(selection) = selections.next() {
 6112            let (start_row, end_row) = consume_contiguous_rows(
 6113                &mut contiguous_row_selections,
 6114                selection,
 6115                &display_map,
 6116                &mut selections,
 6117            );
 6118
 6119            let start_point = Point::new(start_row.0, 0);
 6120            let end_point = Point::new(
 6121                end_row.previous_row().0,
 6122                buffer.line_len(end_row.previous_row()),
 6123            );
 6124            let text = buffer
 6125                .text_for_range(start_point..end_point)
 6126                .collect::<String>();
 6127
 6128            let mut lines = text.split('\n').collect_vec();
 6129
 6130            let lines_before = lines.len();
 6131            callback(&mut lines);
 6132            let lines_after = lines.len();
 6133
 6134            edits.push((start_point..end_point, lines.join("\n")));
 6135
 6136            // Selections must change based on added and removed line count
 6137            let start_row =
 6138                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6139            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6140            new_selections.push(Selection {
 6141                id: selection.id,
 6142                start: start_row,
 6143                end: end_row,
 6144                goal: SelectionGoal::None,
 6145                reversed: selection.reversed,
 6146            });
 6147
 6148            if lines_after > lines_before {
 6149                added_lines += lines_after - lines_before;
 6150            } else if lines_before > lines_after {
 6151                removed_lines += lines_before - lines_after;
 6152            }
 6153        }
 6154
 6155        self.transact(cx, |this, cx| {
 6156            let buffer = this.buffer.update(cx, |buffer, cx| {
 6157                buffer.edit(edits, None, cx);
 6158                buffer.snapshot(cx)
 6159            });
 6160
 6161            // Recalculate offsets on newly edited buffer
 6162            let new_selections = new_selections
 6163                .iter()
 6164                .map(|s| {
 6165                    let start_point = Point::new(s.start.0, 0);
 6166                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6167                    Selection {
 6168                        id: s.id,
 6169                        start: buffer.point_to_offset(start_point),
 6170                        end: buffer.point_to_offset(end_point),
 6171                        goal: s.goal,
 6172                        reversed: s.reversed,
 6173                    }
 6174                })
 6175                .collect();
 6176
 6177            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6178                s.select(new_selections);
 6179            });
 6180
 6181            this.request_autoscroll(Autoscroll::fit(), cx);
 6182        });
 6183    }
 6184
 6185    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6186        self.manipulate_text(cx, |text| text.to_uppercase())
 6187    }
 6188
 6189    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6190        self.manipulate_text(cx, |text| text.to_lowercase())
 6191    }
 6192
 6193    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6194        self.manipulate_text(cx, |text| {
 6195            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6196            // https://github.com/rutrum/convert-case/issues/16
 6197            text.split('\n')
 6198                .map(|line| line.to_case(Case::Title))
 6199                .join("\n")
 6200        })
 6201    }
 6202
 6203    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6204        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6205    }
 6206
 6207    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6208        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6209    }
 6210
 6211    pub fn convert_to_upper_camel_case(
 6212        &mut self,
 6213        _: &ConvertToUpperCamelCase,
 6214        cx: &mut ViewContext<Self>,
 6215    ) {
 6216        self.manipulate_text(cx, |text| {
 6217            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6218            // https://github.com/rutrum/convert-case/issues/16
 6219            text.split('\n')
 6220                .map(|line| line.to_case(Case::UpperCamel))
 6221                .join("\n")
 6222        })
 6223    }
 6224
 6225    pub fn convert_to_lower_camel_case(
 6226        &mut self,
 6227        _: &ConvertToLowerCamelCase,
 6228        cx: &mut ViewContext<Self>,
 6229    ) {
 6230        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6231    }
 6232
 6233    pub fn convert_to_opposite_case(
 6234        &mut self,
 6235        _: &ConvertToOppositeCase,
 6236        cx: &mut ViewContext<Self>,
 6237    ) {
 6238        self.manipulate_text(cx, |text| {
 6239            text.chars()
 6240                .fold(String::with_capacity(text.len()), |mut t, c| {
 6241                    if c.is_uppercase() {
 6242                        t.extend(c.to_lowercase());
 6243                    } else {
 6244                        t.extend(c.to_uppercase());
 6245                    }
 6246                    t
 6247                })
 6248        })
 6249    }
 6250
 6251    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6252    where
 6253        Fn: FnMut(&str) -> String,
 6254    {
 6255        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6256        let buffer = self.buffer.read(cx).snapshot(cx);
 6257
 6258        let mut new_selections = Vec::new();
 6259        let mut edits = Vec::new();
 6260        let mut selection_adjustment = 0i32;
 6261
 6262        for selection in self.selections.all::<usize>(cx) {
 6263            let selection_is_empty = selection.is_empty();
 6264
 6265            let (start, end) = if selection_is_empty {
 6266                let word_range = movement::surrounding_word(
 6267                    &display_map,
 6268                    selection.start.to_display_point(&display_map),
 6269                );
 6270                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6271                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6272                (start, end)
 6273            } else {
 6274                (selection.start, selection.end)
 6275            };
 6276
 6277            let text = buffer.text_for_range(start..end).collect::<String>();
 6278            let old_length = text.len() as i32;
 6279            let text = callback(&text);
 6280
 6281            new_selections.push(Selection {
 6282                start: (start as i32 - selection_adjustment) as usize,
 6283                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6284                goal: SelectionGoal::None,
 6285                ..selection
 6286            });
 6287
 6288            selection_adjustment += old_length - text.len() as i32;
 6289
 6290            edits.push((start..end, text));
 6291        }
 6292
 6293        self.transact(cx, |this, cx| {
 6294            this.buffer.update(cx, |buffer, cx| {
 6295                buffer.edit(edits, None, cx);
 6296            });
 6297
 6298            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6299                s.select(new_selections);
 6300            });
 6301
 6302            this.request_autoscroll(Autoscroll::fit(), cx);
 6303        });
 6304    }
 6305
 6306    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6307        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6308        let buffer = &display_map.buffer_snapshot;
 6309        let selections = self.selections.all::<Point>(cx);
 6310
 6311        let mut edits = Vec::new();
 6312        let mut selections_iter = selections.iter().peekable();
 6313        while let Some(selection) = selections_iter.next() {
 6314            // Avoid duplicating the same lines twice.
 6315            let mut rows = selection.spanned_rows(false, &display_map);
 6316
 6317            while let Some(next_selection) = selections_iter.peek() {
 6318                let next_rows = next_selection.spanned_rows(false, &display_map);
 6319                if next_rows.start < rows.end {
 6320                    rows.end = next_rows.end;
 6321                    selections_iter.next().unwrap();
 6322                } else {
 6323                    break;
 6324                }
 6325            }
 6326
 6327            // Copy the text from the selected row region and splice it either at the start
 6328            // or end of the region.
 6329            let start = Point::new(rows.start.0, 0);
 6330            let end = Point::new(
 6331                rows.end.previous_row().0,
 6332                buffer.line_len(rows.end.previous_row()),
 6333            );
 6334            let text = buffer
 6335                .text_for_range(start..end)
 6336                .chain(Some("\n"))
 6337                .collect::<String>();
 6338            let insert_location = if upwards {
 6339                Point::new(rows.end.0, 0)
 6340            } else {
 6341                start
 6342            };
 6343            edits.push((insert_location..insert_location, text));
 6344        }
 6345
 6346        self.transact(cx, |this, cx| {
 6347            this.buffer.update(cx, |buffer, cx| {
 6348                buffer.edit(edits, None, cx);
 6349            });
 6350
 6351            this.request_autoscroll(Autoscroll::fit(), cx);
 6352        });
 6353    }
 6354
 6355    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6356        self.duplicate_line(true, cx);
 6357    }
 6358
 6359    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6360        self.duplicate_line(false, cx);
 6361    }
 6362
 6363    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6364        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6365        let buffer = self.buffer.read(cx).snapshot(cx);
 6366
 6367        let mut edits = Vec::new();
 6368        let mut unfold_ranges = Vec::new();
 6369        let mut refold_ranges = Vec::new();
 6370
 6371        let selections = self.selections.all::<Point>(cx);
 6372        let mut selections = selections.iter().peekable();
 6373        let mut contiguous_row_selections = Vec::new();
 6374        let mut new_selections = Vec::new();
 6375
 6376        while let Some(selection) = selections.next() {
 6377            // Find all the selections that span a contiguous row range
 6378            let (start_row, end_row) = consume_contiguous_rows(
 6379                &mut contiguous_row_selections,
 6380                selection,
 6381                &display_map,
 6382                &mut selections,
 6383            );
 6384
 6385            // Move the text spanned by the row range to be before the line preceding the row range
 6386            if start_row.0 > 0 {
 6387                let range_to_move = Point::new(
 6388                    start_row.previous_row().0,
 6389                    buffer.line_len(start_row.previous_row()),
 6390                )
 6391                    ..Point::new(
 6392                        end_row.previous_row().0,
 6393                        buffer.line_len(end_row.previous_row()),
 6394                    );
 6395                let insertion_point = display_map
 6396                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6397                    .0;
 6398
 6399                // Don't move lines across excerpts
 6400                if buffer
 6401                    .excerpt_boundaries_in_range((
 6402                        Bound::Excluded(insertion_point),
 6403                        Bound::Included(range_to_move.end),
 6404                    ))
 6405                    .next()
 6406                    .is_none()
 6407                {
 6408                    let text = buffer
 6409                        .text_for_range(range_to_move.clone())
 6410                        .flat_map(|s| s.chars())
 6411                        .skip(1)
 6412                        .chain(['\n'])
 6413                        .collect::<String>();
 6414
 6415                    edits.push((
 6416                        buffer.anchor_after(range_to_move.start)
 6417                            ..buffer.anchor_before(range_to_move.end),
 6418                        String::new(),
 6419                    ));
 6420                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6421                    edits.push((insertion_anchor..insertion_anchor, text));
 6422
 6423                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6424
 6425                    // Move selections up
 6426                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6427                        |mut selection| {
 6428                            selection.start.row -= row_delta;
 6429                            selection.end.row -= row_delta;
 6430                            selection
 6431                        },
 6432                    ));
 6433
 6434                    // Move folds up
 6435                    unfold_ranges.push(range_to_move.clone());
 6436                    for fold in display_map.folds_in_range(
 6437                        buffer.anchor_before(range_to_move.start)
 6438                            ..buffer.anchor_after(range_to_move.end),
 6439                    ) {
 6440                        let mut start = fold.range.start.to_point(&buffer);
 6441                        let mut end = fold.range.end.to_point(&buffer);
 6442                        start.row -= row_delta;
 6443                        end.row -= row_delta;
 6444                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6445                    }
 6446                }
 6447            }
 6448
 6449            // If we didn't move line(s), preserve the existing selections
 6450            new_selections.append(&mut contiguous_row_selections);
 6451        }
 6452
 6453        self.transact(cx, |this, cx| {
 6454            this.unfold_ranges(unfold_ranges, true, true, cx);
 6455            this.buffer.update(cx, |buffer, cx| {
 6456                for (range, text) in edits {
 6457                    buffer.edit([(range, text)], None, cx);
 6458                }
 6459            });
 6460            this.fold_ranges(refold_ranges, true, cx);
 6461            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6462                s.select(new_selections);
 6463            })
 6464        });
 6465    }
 6466
 6467    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6468        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6469        let buffer = self.buffer.read(cx).snapshot(cx);
 6470
 6471        let mut edits = Vec::new();
 6472        let mut unfold_ranges = Vec::new();
 6473        let mut refold_ranges = Vec::new();
 6474
 6475        let selections = self.selections.all::<Point>(cx);
 6476        let mut selections = selections.iter().peekable();
 6477        let mut contiguous_row_selections = Vec::new();
 6478        let mut new_selections = Vec::new();
 6479
 6480        while let Some(selection) = selections.next() {
 6481            // Find all the selections that span a contiguous row range
 6482            let (start_row, end_row) = consume_contiguous_rows(
 6483                &mut contiguous_row_selections,
 6484                selection,
 6485                &display_map,
 6486                &mut selections,
 6487            );
 6488
 6489            // Move the text spanned by the row range to be after the last line of the row range
 6490            if end_row.0 <= buffer.max_point().row {
 6491                let range_to_move =
 6492                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6493                let insertion_point = display_map
 6494                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6495                    .0;
 6496
 6497                // Don't move lines across excerpt boundaries
 6498                if buffer
 6499                    .excerpt_boundaries_in_range((
 6500                        Bound::Excluded(range_to_move.start),
 6501                        Bound::Included(insertion_point),
 6502                    ))
 6503                    .next()
 6504                    .is_none()
 6505                {
 6506                    let mut text = String::from("\n");
 6507                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6508                    text.pop(); // Drop trailing newline
 6509                    edits.push((
 6510                        buffer.anchor_after(range_to_move.start)
 6511                            ..buffer.anchor_before(range_to_move.end),
 6512                        String::new(),
 6513                    ));
 6514                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6515                    edits.push((insertion_anchor..insertion_anchor, text));
 6516
 6517                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6518
 6519                    // Move selections down
 6520                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6521                        |mut selection| {
 6522                            selection.start.row += row_delta;
 6523                            selection.end.row += row_delta;
 6524                            selection
 6525                        },
 6526                    ));
 6527
 6528                    // Move folds down
 6529                    unfold_ranges.push(range_to_move.clone());
 6530                    for fold in display_map.folds_in_range(
 6531                        buffer.anchor_before(range_to_move.start)
 6532                            ..buffer.anchor_after(range_to_move.end),
 6533                    ) {
 6534                        let mut start = fold.range.start.to_point(&buffer);
 6535                        let mut end = fold.range.end.to_point(&buffer);
 6536                        start.row += row_delta;
 6537                        end.row += row_delta;
 6538                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6539                    }
 6540                }
 6541            }
 6542
 6543            // If we didn't move line(s), preserve the existing selections
 6544            new_selections.append(&mut contiguous_row_selections);
 6545        }
 6546
 6547        self.transact(cx, |this, cx| {
 6548            this.unfold_ranges(unfold_ranges, true, true, cx);
 6549            this.buffer.update(cx, |buffer, cx| {
 6550                for (range, text) in edits {
 6551                    buffer.edit([(range, text)], None, cx);
 6552                }
 6553            });
 6554            this.fold_ranges(refold_ranges, true, cx);
 6555            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6556        });
 6557    }
 6558
 6559    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6560        let text_layout_details = &self.text_layout_details(cx);
 6561        self.transact(cx, |this, cx| {
 6562            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6563                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6564                let line_mode = s.line_mode;
 6565                s.move_with(|display_map, selection| {
 6566                    if !selection.is_empty() || line_mode {
 6567                        return;
 6568                    }
 6569
 6570                    let mut head = selection.head();
 6571                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6572                    if head.column() == display_map.line_len(head.row()) {
 6573                        transpose_offset = display_map
 6574                            .buffer_snapshot
 6575                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6576                    }
 6577
 6578                    if transpose_offset == 0 {
 6579                        return;
 6580                    }
 6581
 6582                    *head.column_mut() += 1;
 6583                    head = display_map.clip_point(head, Bias::Right);
 6584                    let goal = SelectionGoal::HorizontalPosition(
 6585                        display_map
 6586                            .x_for_display_point(head, &text_layout_details)
 6587                            .into(),
 6588                    );
 6589                    selection.collapse_to(head, goal);
 6590
 6591                    let transpose_start = display_map
 6592                        .buffer_snapshot
 6593                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6594                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6595                        let transpose_end = display_map
 6596                            .buffer_snapshot
 6597                            .clip_offset(transpose_offset + 1, Bias::Right);
 6598                        if let Some(ch) =
 6599                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6600                        {
 6601                            edits.push((transpose_start..transpose_offset, String::new()));
 6602                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6603                        }
 6604                    }
 6605                });
 6606                edits
 6607            });
 6608            this.buffer
 6609                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6610            let selections = this.selections.all::<usize>(cx);
 6611            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6612                s.select(selections);
 6613            });
 6614        });
 6615    }
 6616
 6617    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6618        let mut text = String::new();
 6619        let buffer = self.buffer.read(cx).snapshot(cx);
 6620        let mut selections = self.selections.all::<Point>(cx);
 6621        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6622        {
 6623            let max_point = buffer.max_point();
 6624            let mut is_first = true;
 6625            for selection in &mut selections {
 6626                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6627                if is_entire_line {
 6628                    selection.start = Point::new(selection.start.row, 0);
 6629                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6630                    selection.goal = SelectionGoal::None;
 6631                }
 6632                if is_first {
 6633                    is_first = false;
 6634                } else {
 6635                    text += "\n";
 6636                }
 6637                let mut len = 0;
 6638                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6639                    text.push_str(chunk);
 6640                    len += chunk.len();
 6641                }
 6642                clipboard_selections.push(ClipboardSelection {
 6643                    len,
 6644                    is_entire_line,
 6645                    first_line_indent: buffer
 6646                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6647                        .len,
 6648                });
 6649            }
 6650        }
 6651
 6652        self.transact(cx, |this, cx| {
 6653            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6654                s.select(selections);
 6655            });
 6656            this.insert("", cx);
 6657            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6658                text,
 6659                clipboard_selections,
 6660            ));
 6661        });
 6662    }
 6663
 6664    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6665        let selections = self.selections.all::<Point>(cx);
 6666        let buffer = self.buffer.read(cx).read(cx);
 6667        let mut text = String::new();
 6668
 6669        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6670        {
 6671            let max_point = buffer.max_point();
 6672            let mut is_first = true;
 6673            for selection in selections.iter() {
 6674                let mut start = selection.start;
 6675                let mut end = selection.end;
 6676                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6677                if is_entire_line {
 6678                    start = Point::new(start.row, 0);
 6679                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6680                }
 6681                if is_first {
 6682                    is_first = false;
 6683                } else {
 6684                    text += "\n";
 6685                }
 6686                let mut len = 0;
 6687                for chunk in buffer.text_for_range(start..end) {
 6688                    text.push_str(chunk);
 6689                    len += chunk.len();
 6690                }
 6691                clipboard_selections.push(ClipboardSelection {
 6692                    len,
 6693                    is_entire_line,
 6694                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6695                });
 6696            }
 6697        }
 6698
 6699        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6700            text,
 6701            clipboard_selections,
 6702        ));
 6703    }
 6704
 6705    pub fn do_paste(
 6706        &mut self,
 6707        text: &String,
 6708        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6709        handle_entire_lines: bool,
 6710        cx: &mut ViewContext<Self>,
 6711    ) {
 6712        if self.read_only(cx) {
 6713            return;
 6714        }
 6715
 6716        let clipboard_text = Cow::Borrowed(text);
 6717
 6718        self.transact(cx, |this, cx| {
 6719            if let Some(mut clipboard_selections) = clipboard_selections {
 6720                let old_selections = this.selections.all::<usize>(cx);
 6721                let all_selections_were_entire_line =
 6722                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6723                let first_selection_indent_column =
 6724                    clipboard_selections.first().map(|s| s.first_line_indent);
 6725                if clipboard_selections.len() != old_selections.len() {
 6726                    clipboard_selections.drain(..);
 6727                }
 6728
 6729                this.buffer.update(cx, |buffer, cx| {
 6730                    let snapshot = buffer.read(cx);
 6731                    let mut start_offset = 0;
 6732                    let mut edits = Vec::new();
 6733                    let mut original_indent_columns = Vec::new();
 6734                    for (ix, selection) in old_selections.iter().enumerate() {
 6735                        let to_insert;
 6736                        let entire_line;
 6737                        let original_indent_column;
 6738                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6739                            let end_offset = start_offset + clipboard_selection.len;
 6740                            to_insert = &clipboard_text[start_offset..end_offset];
 6741                            entire_line = clipboard_selection.is_entire_line;
 6742                            start_offset = end_offset + 1;
 6743                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6744                        } else {
 6745                            to_insert = clipboard_text.as_str();
 6746                            entire_line = all_selections_were_entire_line;
 6747                            original_indent_column = first_selection_indent_column
 6748                        }
 6749
 6750                        // If the corresponding selection was empty when this slice of the
 6751                        // clipboard text was written, then the entire line containing the
 6752                        // selection was copied. If this selection is also currently empty,
 6753                        // then paste the line before the current line of the buffer.
 6754                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6755                            let column = selection.start.to_point(&snapshot).column as usize;
 6756                            let line_start = selection.start - column;
 6757                            line_start..line_start
 6758                        } else {
 6759                            selection.range()
 6760                        };
 6761
 6762                        edits.push((range, to_insert));
 6763                        original_indent_columns.extend(original_indent_column);
 6764                    }
 6765                    drop(snapshot);
 6766
 6767                    buffer.edit(
 6768                        edits,
 6769                        Some(AutoindentMode::Block {
 6770                            original_indent_columns,
 6771                        }),
 6772                        cx,
 6773                    );
 6774                });
 6775
 6776                let selections = this.selections.all::<usize>(cx);
 6777                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6778            } else {
 6779                this.insert(&clipboard_text, cx);
 6780            }
 6781        });
 6782    }
 6783
 6784    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6785        if let Some(item) = cx.read_from_clipboard() {
 6786            let entries = item.entries();
 6787
 6788            match entries.first() {
 6789                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 6790                // of all the pasted entries.
 6791                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 6792                    .do_paste(
 6793                        clipboard_string.text(),
 6794                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 6795                        true,
 6796                        cx,
 6797                    ),
 6798                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 6799            }
 6800        }
 6801    }
 6802
 6803    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6804        if self.read_only(cx) {
 6805            return;
 6806        }
 6807
 6808        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6809            if let Some((selections, _)) =
 6810                self.selection_history.transaction(transaction_id).cloned()
 6811            {
 6812                self.change_selections(None, cx, |s| {
 6813                    s.select_anchors(selections.to_vec());
 6814                });
 6815            }
 6816            self.request_autoscroll(Autoscroll::fit(), cx);
 6817            self.unmark_text(cx);
 6818            self.refresh_inline_completion(true, false, cx);
 6819            cx.emit(EditorEvent::Edited { transaction_id });
 6820            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6821        }
 6822    }
 6823
 6824    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6825        if self.read_only(cx) {
 6826            return;
 6827        }
 6828
 6829        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6830            if let Some((_, Some(selections))) =
 6831                self.selection_history.transaction(transaction_id).cloned()
 6832            {
 6833                self.change_selections(None, cx, |s| {
 6834                    s.select_anchors(selections.to_vec());
 6835                });
 6836            }
 6837            self.request_autoscroll(Autoscroll::fit(), cx);
 6838            self.unmark_text(cx);
 6839            self.refresh_inline_completion(true, false, cx);
 6840            cx.emit(EditorEvent::Edited { transaction_id });
 6841        }
 6842    }
 6843
 6844    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6845        self.buffer
 6846            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6847    }
 6848
 6849    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6850        self.buffer
 6851            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6852    }
 6853
 6854    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6855        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6856            let line_mode = s.line_mode;
 6857            s.move_with(|map, selection| {
 6858                let cursor = if selection.is_empty() && !line_mode {
 6859                    movement::left(map, selection.start)
 6860                } else {
 6861                    selection.start
 6862                };
 6863                selection.collapse_to(cursor, SelectionGoal::None);
 6864            });
 6865        })
 6866    }
 6867
 6868    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6869        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6870            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6871        })
 6872    }
 6873
 6874    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6875        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6876            let line_mode = s.line_mode;
 6877            s.move_with(|map, selection| {
 6878                let cursor = if selection.is_empty() && !line_mode {
 6879                    movement::right(map, selection.end)
 6880                } else {
 6881                    selection.end
 6882                };
 6883                selection.collapse_to(cursor, SelectionGoal::None)
 6884            });
 6885        })
 6886    }
 6887
 6888    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6889        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6890            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6891        })
 6892    }
 6893
 6894    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6895        if self.take_rename(true, cx).is_some() {
 6896            return;
 6897        }
 6898
 6899        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6900            cx.propagate();
 6901            return;
 6902        }
 6903
 6904        let text_layout_details = &self.text_layout_details(cx);
 6905        let selection_count = self.selections.count();
 6906        let first_selection = self.selections.first_anchor();
 6907
 6908        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6909            let line_mode = s.line_mode;
 6910            s.move_with(|map, selection| {
 6911                if !selection.is_empty() && !line_mode {
 6912                    selection.goal = SelectionGoal::None;
 6913                }
 6914                let (cursor, goal) = movement::up(
 6915                    map,
 6916                    selection.start,
 6917                    selection.goal,
 6918                    false,
 6919                    &text_layout_details,
 6920                );
 6921                selection.collapse_to(cursor, goal);
 6922            });
 6923        });
 6924
 6925        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6926        {
 6927            cx.propagate();
 6928        }
 6929    }
 6930
 6931    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6932        if self.take_rename(true, cx).is_some() {
 6933            return;
 6934        }
 6935
 6936        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6937            cx.propagate();
 6938            return;
 6939        }
 6940
 6941        let text_layout_details = &self.text_layout_details(cx);
 6942
 6943        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6944            let line_mode = s.line_mode;
 6945            s.move_with(|map, selection| {
 6946                if !selection.is_empty() && !line_mode {
 6947                    selection.goal = SelectionGoal::None;
 6948                }
 6949                let (cursor, goal) = movement::up_by_rows(
 6950                    map,
 6951                    selection.start,
 6952                    action.lines,
 6953                    selection.goal,
 6954                    false,
 6955                    &text_layout_details,
 6956                );
 6957                selection.collapse_to(cursor, goal);
 6958            });
 6959        })
 6960    }
 6961
 6962    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6963        if self.take_rename(true, cx).is_some() {
 6964            return;
 6965        }
 6966
 6967        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6968            cx.propagate();
 6969            return;
 6970        }
 6971
 6972        let text_layout_details = &self.text_layout_details(cx);
 6973
 6974        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6975            let line_mode = s.line_mode;
 6976            s.move_with(|map, selection| {
 6977                if !selection.is_empty() && !line_mode {
 6978                    selection.goal = SelectionGoal::None;
 6979                }
 6980                let (cursor, goal) = movement::down_by_rows(
 6981                    map,
 6982                    selection.start,
 6983                    action.lines,
 6984                    selection.goal,
 6985                    false,
 6986                    &text_layout_details,
 6987                );
 6988                selection.collapse_to(cursor, goal);
 6989            });
 6990        })
 6991    }
 6992
 6993    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6994        let text_layout_details = &self.text_layout_details(cx);
 6995        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6996            s.move_heads_with(|map, head, goal| {
 6997                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6998            })
 6999        })
 7000    }
 7001
 7002    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7003        let text_layout_details = &self.text_layout_details(cx);
 7004        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7005            s.move_heads_with(|map, head, goal| {
 7006                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 7007            })
 7008        })
 7009    }
 7010
 7011    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7012        let Some(row_count) = self.visible_row_count() else {
 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            s.move_heads_with(|map, head, goal| {
 7020                movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
 7021            })
 7022        })
 7023    }
 7024
 7025    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7026        if self.take_rename(true, cx).is_some() {
 7027            return;
 7028        }
 7029
 7030        if self
 7031            .context_menu
 7032            .write()
 7033            .as_mut()
 7034            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 7035            .unwrap_or(false)
 7036        {
 7037            return;
 7038        }
 7039
 7040        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7041            cx.propagate();
 7042            return;
 7043        }
 7044
 7045        let Some(row_count) = self.visible_row_count() else {
 7046            return;
 7047        };
 7048
 7049        let autoscroll = if action.center_cursor {
 7050            Autoscroll::center()
 7051        } else {
 7052            Autoscroll::fit()
 7053        };
 7054
 7055        let text_layout_details = &self.text_layout_details(cx);
 7056
 7057        self.change_selections(Some(autoscroll), cx, |s| {
 7058            let line_mode = s.line_mode;
 7059            s.move_with(|map, selection| {
 7060                if !selection.is_empty() && !line_mode {
 7061                    selection.goal = SelectionGoal::None;
 7062                }
 7063                let (cursor, goal) = movement::up_by_rows(
 7064                    map,
 7065                    selection.end,
 7066                    row_count,
 7067                    selection.goal,
 7068                    false,
 7069                    &text_layout_details,
 7070                );
 7071                selection.collapse_to(cursor, goal);
 7072            });
 7073        });
 7074    }
 7075
 7076    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7077        let text_layout_details = &self.text_layout_details(cx);
 7078        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7079            s.move_heads_with(|map, head, goal| {
 7080                movement::up(map, head, goal, false, &text_layout_details)
 7081            })
 7082        })
 7083    }
 7084
 7085    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7086        self.take_rename(true, cx);
 7087
 7088        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7089            cx.propagate();
 7090            return;
 7091        }
 7092
 7093        let text_layout_details = &self.text_layout_details(cx);
 7094        let selection_count = self.selections.count();
 7095        let first_selection = self.selections.first_anchor();
 7096
 7097        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7098            let line_mode = s.line_mode;
 7099            s.move_with(|map, selection| {
 7100                if !selection.is_empty() && !line_mode {
 7101                    selection.goal = SelectionGoal::None;
 7102                }
 7103                let (cursor, goal) = movement::down(
 7104                    map,
 7105                    selection.end,
 7106                    selection.goal,
 7107                    false,
 7108                    &text_layout_details,
 7109                );
 7110                selection.collapse_to(cursor, goal);
 7111            });
 7112        });
 7113
 7114        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7115        {
 7116            cx.propagate();
 7117        }
 7118    }
 7119
 7120    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7121        let Some(row_count) = self.visible_row_count() else {
 7122            return;
 7123        };
 7124
 7125        let text_layout_details = &self.text_layout_details(cx);
 7126
 7127        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7128            s.move_heads_with(|map, head, goal| {
 7129                movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
 7130            })
 7131        })
 7132    }
 7133
 7134    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7135        if self.take_rename(true, cx).is_some() {
 7136            return;
 7137        }
 7138
 7139        if self
 7140            .context_menu
 7141            .write()
 7142            .as_mut()
 7143            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 7144            .unwrap_or(false)
 7145        {
 7146            return;
 7147        }
 7148
 7149        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7150            cx.propagate();
 7151            return;
 7152        }
 7153
 7154        let Some(row_count) = self.visible_row_count() else {
 7155            return;
 7156        };
 7157
 7158        let autoscroll = if action.center_cursor {
 7159            Autoscroll::center()
 7160        } else {
 7161            Autoscroll::fit()
 7162        };
 7163
 7164        let text_layout_details = &self.text_layout_details(cx);
 7165        self.change_selections(Some(autoscroll), cx, |s| {
 7166            let line_mode = s.line_mode;
 7167            s.move_with(|map, selection| {
 7168                if !selection.is_empty() && !line_mode {
 7169                    selection.goal = SelectionGoal::None;
 7170                }
 7171                let (cursor, goal) = movement::down_by_rows(
 7172                    map,
 7173                    selection.end,
 7174                    row_count,
 7175                    selection.goal,
 7176                    false,
 7177                    &text_layout_details,
 7178                );
 7179                selection.collapse_to(cursor, goal);
 7180            });
 7181        });
 7182    }
 7183
 7184    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7185        let text_layout_details = &self.text_layout_details(cx);
 7186        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7187            s.move_heads_with(|map, head, goal| {
 7188                movement::down(map, head, goal, false, &text_layout_details)
 7189            })
 7190        });
 7191    }
 7192
 7193    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7194        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7195            context_menu.select_first(self.project.as_ref(), cx);
 7196        }
 7197    }
 7198
 7199    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7200        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7201            context_menu.select_prev(self.project.as_ref(), cx);
 7202        }
 7203    }
 7204
 7205    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7206        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7207            context_menu.select_next(self.project.as_ref(), cx);
 7208        }
 7209    }
 7210
 7211    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7212        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7213            context_menu.select_last(self.project.as_ref(), cx);
 7214        }
 7215    }
 7216
 7217    pub fn move_to_previous_word_start(
 7218        &mut self,
 7219        _: &MoveToPreviousWordStart,
 7220        cx: &mut ViewContext<Self>,
 7221    ) {
 7222        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7223            s.move_cursors_with(|map, head, _| {
 7224                (
 7225                    movement::previous_word_start(map, head),
 7226                    SelectionGoal::None,
 7227                )
 7228            });
 7229        })
 7230    }
 7231
 7232    pub fn move_to_previous_subword_start(
 7233        &mut self,
 7234        _: &MoveToPreviousSubwordStart,
 7235        cx: &mut ViewContext<Self>,
 7236    ) {
 7237        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7238            s.move_cursors_with(|map, head, _| {
 7239                (
 7240                    movement::previous_subword_start(map, head),
 7241                    SelectionGoal::None,
 7242                )
 7243            });
 7244        })
 7245    }
 7246
 7247    pub fn select_to_previous_word_start(
 7248        &mut self,
 7249        _: &SelectToPreviousWordStart,
 7250        cx: &mut ViewContext<Self>,
 7251    ) {
 7252        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7253            s.move_heads_with(|map, head, _| {
 7254                (
 7255                    movement::previous_word_start(map, head),
 7256                    SelectionGoal::None,
 7257                )
 7258            });
 7259        })
 7260    }
 7261
 7262    pub fn select_to_previous_subword_start(
 7263        &mut self,
 7264        _: &SelectToPreviousSubwordStart,
 7265        cx: &mut ViewContext<Self>,
 7266    ) {
 7267        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7268            s.move_heads_with(|map, head, _| {
 7269                (
 7270                    movement::previous_subword_start(map, head),
 7271                    SelectionGoal::None,
 7272                )
 7273            });
 7274        })
 7275    }
 7276
 7277    pub fn delete_to_previous_word_start(
 7278        &mut self,
 7279        _: &DeleteToPreviousWordStart,
 7280        cx: &mut ViewContext<Self>,
 7281    ) {
 7282        self.transact(cx, |this, cx| {
 7283            this.select_autoclose_pair(cx);
 7284            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7285                let line_mode = s.line_mode;
 7286                s.move_with(|map, selection| {
 7287                    if selection.is_empty() && !line_mode {
 7288                        let cursor = movement::previous_word_start(map, selection.head());
 7289                        selection.set_head(cursor, SelectionGoal::None);
 7290                    }
 7291                });
 7292            });
 7293            this.insert("", cx);
 7294        });
 7295    }
 7296
 7297    pub fn delete_to_previous_subword_start(
 7298        &mut self,
 7299        _: &DeleteToPreviousSubwordStart,
 7300        cx: &mut ViewContext<Self>,
 7301    ) {
 7302        self.transact(cx, |this, cx| {
 7303            this.select_autoclose_pair(cx);
 7304            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7305                let line_mode = s.line_mode;
 7306                s.move_with(|map, selection| {
 7307                    if selection.is_empty() && !line_mode {
 7308                        let cursor = movement::previous_subword_start(map, selection.head());
 7309                        selection.set_head(cursor, SelectionGoal::None);
 7310                    }
 7311                });
 7312            });
 7313            this.insert("", cx);
 7314        });
 7315    }
 7316
 7317    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7318        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7319            s.move_cursors_with(|map, head, _| {
 7320                (movement::next_word_end(map, head), SelectionGoal::None)
 7321            });
 7322        })
 7323    }
 7324
 7325    pub fn move_to_next_subword_end(
 7326        &mut self,
 7327        _: &MoveToNextSubwordEnd,
 7328        cx: &mut ViewContext<Self>,
 7329    ) {
 7330        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7331            s.move_cursors_with(|map, head, _| {
 7332                (movement::next_subword_end(map, head), SelectionGoal::None)
 7333            });
 7334        })
 7335    }
 7336
 7337    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7338        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7339            s.move_heads_with(|map, head, _| {
 7340                (movement::next_word_end(map, head), SelectionGoal::None)
 7341            });
 7342        })
 7343    }
 7344
 7345    pub fn select_to_next_subword_end(
 7346        &mut self,
 7347        _: &SelectToNextSubwordEnd,
 7348        cx: &mut ViewContext<Self>,
 7349    ) {
 7350        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7351            s.move_heads_with(|map, head, _| {
 7352                (movement::next_subword_end(map, head), SelectionGoal::None)
 7353            });
 7354        })
 7355    }
 7356
 7357    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 7358        self.transact(cx, |this, cx| {
 7359            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7360                let line_mode = s.line_mode;
 7361                s.move_with(|map, selection| {
 7362                    if selection.is_empty() && !line_mode {
 7363                        let cursor = movement::next_word_end(map, selection.head());
 7364                        selection.set_head(cursor, SelectionGoal::None);
 7365                    }
 7366                });
 7367            });
 7368            this.insert("", cx);
 7369        });
 7370    }
 7371
 7372    pub fn delete_to_next_subword_end(
 7373        &mut self,
 7374        _: &DeleteToNextSubwordEnd,
 7375        cx: &mut ViewContext<Self>,
 7376    ) {
 7377        self.transact(cx, |this, cx| {
 7378            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7379                s.move_with(|map, selection| {
 7380                    if selection.is_empty() {
 7381                        let cursor = movement::next_subword_end(map, selection.head());
 7382                        selection.set_head(cursor, SelectionGoal::None);
 7383                    }
 7384                });
 7385            });
 7386            this.insert("", cx);
 7387        });
 7388    }
 7389
 7390    pub fn move_to_beginning_of_line(
 7391        &mut self,
 7392        action: &MoveToBeginningOfLine,
 7393        cx: &mut ViewContext<Self>,
 7394    ) {
 7395        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7396            s.move_cursors_with(|map, head, _| {
 7397                (
 7398                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7399                    SelectionGoal::None,
 7400                )
 7401            });
 7402        })
 7403    }
 7404
 7405    pub fn select_to_beginning_of_line(
 7406        &mut self,
 7407        action: &SelectToBeginningOfLine,
 7408        cx: &mut ViewContext<Self>,
 7409    ) {
 7410        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7411            s.move_heads_with(|map, head, _| {
 7412                (
 7413                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7414                    SelectionGoal::None,
 7415                )
 7416            });
 7417        });
 7418    }
 7419
 7420    pub fn delete_to_beginning_of_line(
 7421        &mut self,
 7422        _: &DeleteToBeginningOfLine,
 7423        cx: &mut ViewContext<Self>,
 7424    ) {
 7425        self.transact(cx, |this, cx| {
 7426            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7427                s.move_with(|_, selection| {
 7428                    selection.reversed = true;
 7429                });
 7430            });
 7431
 7432            this.select_to_beginning_of_line(
 7433                &SelectToBeginningOfLine {
 7434                    stop_at_soft_wraps: false,
 7435                },
 7436                cx,
 7437            );
 7438            this.backspace(&Backspace, cx);
 7439        });
 7440    }
 7441
 7442    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7443        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7444            s.move_cursors_with(|map, head, _| {
 7445                (
 7446                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7447                    SelectionGoal::None,
 7448                )
 7449            });
 7450        })
 7451    }
 7452
 7453    pub fn select_to_end_of_line(
 7454        &mut self,
 7455        action: &SelectToEndOfLine,
 7456        cx: &mut ViewContext<Self>,
 7457    ) {
 7458        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7459            s.move_heads_with(|map, head, _| {
 7460                (
 7461                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7462                    SelectionGoal::None,
 7463                )
 7464            });
 7465        })
 7466    }
 7467
 7468    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7469        self.transact(cx, |this, cx| {
 7470            this.select_to_end_of_line(
 7471                &SelectToEndOfLine {
 7472                    stop_at_soft_wraps: false,
 7473                },
 7474                cx,
 7475            );
 7476            this.delete(&Delete, cx);
 7477        });
 7478    }
 7479
 7480    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7481        self.transact(cx, |this, cx| {
 7482            this.select_to_end_of_line(
 7483                &SelectToEndOfLine {
 7484                    stop_at_soft_wraps: false,
 7485                },
 7486                cx,
 7487            );
 7488            this.cut(&Cut, cx);
 7489        });
 7490    }
 7491
 7492    pub fn move_to_start_of_paragraph(
 7493        &mut self,
 7494        _: &MoveToStartOfParagraph,
 7495        cx: &mut ViewContext<Self>,
 7496    ) {
 7497        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7498            cx.propagate();
 7499            return;
 7500        }
 7501
 7502        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7503            s.move_with(|map, selection| {
 7504                selection.collapse_to(
 7505                    movement::start_of_paragraph(map, selection.head(), 1),
 7506                    SelectionGoal::None,
 7507                )
 7508            });
 7509        })
 7510    }
 7511
 7512    pub fn move_to_end_of_paragraph(
 7513        &mut self,
 7514        _: &MoveToEndOfParagraph,
 7515        cx: &mut ViewContext<Self>,
 7516    ) {
 7517        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7518            cx.propagate();
 7519            return;
 7520        }
 7521
 7522        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7523            s.move_with(|map, selection| {
 7524                selection.collapse_to(
 7525                    movement::end_of_paragraph(map, selection.head(), 1),
 7526                    SelectionGoal::None,
 7527                )
 7528            });
 7529        })
 7530    }
 7531
 7532    pub fn select_to_start_of_paragraph(
 7533        &mut self,
 7534        _: &SelectToStartOfParagraph,
 7535        cx: &mut ViewContext<Self>,
 7536    ) {
 7537        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7538            cx.propagate();
 7539            return;
 7540        }
 7541
 7542        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7543            s.move_heads_with(|map, head, _| {
 7544                (
 7545                    movement::start_of_paragraph(map, head, 1),
 7546                    SelectionGoal::None,
 7547                )
 7548            });
 7549        })
 7550    }
 7551
 7552    pub fn select_to_end_of_paragraph(
 7553        &mut self,
 7554        _: &SelectToEndOfParagraph,
 7555        cx: &mut ViewContext<Self>,
 7556    ) {
 7557        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7558            cx.propagate();
 7559            return;
 7560        }
 7561
 7562        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7563            s.move_heads_with(|map, head, _| {
 7564                (
 7565                    movement::end_of_paragraph(map, head, 1),
 7566                    SelectionGoal::None,
 7567                )
 7568            });
 7569        })
 7570    }
 7571
 7572    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 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.select_ranges(vec![0..0]);
 7580        });
 7581    }
 7582
 7583    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7584        let mut selection = self.selections.last::<Point>(cx);
 7585        selection.set_head(Point::zero(), SelectionGoal::None);
 7586
 7587        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7588            s.select(vec![selection]);
 7589        });
 7590    }
 7591
 7592    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7593        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7594            cx.propagate();
 7595            return;
 7596        }
 7597
 7598        let cursor = self.buffer.read(cx).read(cx).len();
 7599        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7600            s.select_ranges(vec![cursor..cursor])
 7601        });
 7602    }
 7603
 7604    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7605        self.nav_history = nav_history;
 7606    }
 7607
 7608    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7609        self.nav_history.as_ref()
 7610    }
 7611
 7612    fn push_to_nav_history(
 7613        &mut self,
 7614        cursor_anchor: Anchor,
 7615        new_position: Option<Point>,
 7616        cx: &mut ViewContext<Self>,
 7617    ) {
 7618        if let Some(nav_history) = self.nav_history.as_mut() {
 7619            let buffer = self.buffer.read(cx).read(cx);
 7620            let cursor_position = cursor_anchor.to_point(&buffer);
 7621            let scroll_state = self.scroll_manager.anchor();
 7622            let scroll_top_row = scroll_state.top_row(&buffer);
 7623            drop(buffer);
 7624
 7625            if let Some(new_position) = new_position {
 7626                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7627                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7628                    return;
 7629                }
 7630            }
 7631
 7632            nav_history.push(
 7633                Some(NavigationData {
 7634                    cursor_anchor,
 7635                    cursor_position,
 7636                    scroll_anchor: scroll_state,
 7637                    scroll_top_row,
 7638                }),
 7639                cx,
 7640            );
 7641        }
 7642    }
 7643
 7644    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7645        let buffer = self.buffer.read(cx).snapshot(cx);
 7646        let mut selection = self.selections.first::<usize>(cx);
 7647        selection.set_head(buffer.len(), SelectionGoal::None);
 7648        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7649            s.select(vec![selection]);
 7650        });
 7651    }
 7652
 7653    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7654        let end = self.buffer.read(cx).read(cx).len();
 7655        self.change_selections(None, cx, |s| {
 7656            s.select_ranges(vec![0..end]);
 7657        });
 7658    }
 7659
 7660    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7661        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7662        let mut selections = self.selections.all::<Point>(cx);
 7663        let max_point = display_map.buffer_snapshot.max_point();
 7664        for selection in &mut selections {
 7665            let rows = selection.spanned_rows(true, &display_map);
 7666            selection.start = Point::new(rows.start.0, 0);
 7667            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7668            selection.reversed = false;
 7669        }
 7670        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7671            s.select(selections);
 7672        });
 7673    }
 7674
 7675    pub fn split_selection_into_lines(
 7676        &mut self,
 7677        _: &SplitSelectionIntoLines,
 7678        cx: &mut ViewContext<Self>,
 7679    ) {
 7680        let mut to_unfold = Vec::new();
 7681        let mut new_selection_ranges = Vec::new();
 7682        {
 7683            let selections = self.selections.all::<Point>(cx);
 7684            let buffer = self.buffer.read(cx).read(cx);
 7685            for selection in selections {
 7686                for row in selection.start.row..selection.end.row {
 7687                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7688                    new_selection_ranges.push(cursor..cursor);
 7689                }
 7690                new_selection_ranges.push(selection.end..selection.end);
 7691                to_unfold.push(selection.start..selection.end);
 7692            }
 7693        }
 7694        self.unfold_ranges(to_unfold, true, true, cx);
 7695        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7696            s.select_ranges(new_selection_ranges);
 7697        });
 7698    }
 7699
 7700    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7701        self.add_selection(true, cx);
 7702    }
 7703
 7704    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7705        self.add_selection(false, cx);
 7706    }
 7707
 7708    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7709        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7710        let mut selections = self.selections.all::<Point>(cx);
 7711        let text_layout_details = self.text_layout_details(cx);
 7712        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7713            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7714            let range = oldest_selection.display_range(&display_map).sorted();
 7715
 7716            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7717            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7718            let positions = start_x.min(end_x)..start_x.max(end_x);
 7719
 7720            selections.clear();
 7721            let mut stack = Vec::new();
 7722            for row in range.start.row().0..=range.end.row().0 {
 7723                if let Some(selection) = self.selections.build_columnar_selection(
 7724                    &display_map,
 7725                    DisplayRow(row),
 7726                    &positions,
 7727                    oldest_selection.reversed,
 7728                    &text_layout_details,
 7729                ) {
 7730                    stack.push(selection.id);
 7731                    selections.push(selection);
 7732                }
 7733            }
 7734
 7735            if above {
 7736                stack.reverse();
 7737            }
 7738
 7739            AddSelectionsState { above, stack }
 7740        });
 7741
 7742        let last_added_selection = *state.stack.last().unwrap();
 7743        let mut new_selections = Vec::new();
 7744        if above == state.above {
 7745            let end_row = if above {
 7746                DisplayRow(0)
 7747            } else {
 7748                display_map.max_point().row()
 7749            };
 7750
 7751            'outer: for selection in selections {
 7752                if selection.id == last_added_selection {
 7753                    let range = selection.display_range(&display_map).sorted();
 7754                    debug_assert_eq!(range.start.row(), range.end.row());
 7755                    let mut row = range.start.row();
 7756                    let positions =
 7757                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7758                            px(start)..px(end)
 7759                        } else {
 7760                            let start_x =
 7761                                display_map.x_for_display_point(range.start, &text_layout_details);
 7762                            let end_x =
 7763                                display_map.x_for_display_point(range.end, &text_layout_details);
 7764                            start_x.min(end_x)..start_x.max(end_x)
 7765                        };
 7766
 7767                    while row != end_row {
 7768                        if above {
 7769                            row.0 -= 1;
 7770                        } else {
 7771                            row.0 += 1;
 7772                        }
 7773
 7774                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7775                            &display_map,
 7776                            row,
 7777                            &positions,
 7778                            selection.reversed,
 7779                            &text_layout_details,
 7780                        ) {
 7781                            state.stack.push(new_selection.id);
 7782                            if above {
 7783                                new_selections.push(new_selection);
 7784                                new_selections.push(selection);
 7785                            } else {
 7786                                new_selections.push(selection);
 7787                                new_selections.push(new_selection);
 7788                            }
 7789
 7790                            continue 'outer;
 7791                        }
 7792                    }
 7793                }
 7794
 7795                new_selections.push(selection);
 7796            }
 7797        } else {
 7798            new_selections = selections;
 7799            new_selections.retain(|s| s.id != last_added_selection);
 7800            state.stack.pop();
 7801        }
 7802
 7803        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7804            s.select(new_selections);
 7805        });
 7806        if state.stack.len() > 1 {
 7807            self.add_selections_state = Some(state);
 7808        }
 7809    }
 7810
 7811    pub fn select_next_match_internal(
 7812        &mut self,
 7813        display_map: &DisplaySnapshot,
 7814        replace_newest: bool,
 7815        autoscroll: Option<Autoscroll>,
 7816        cx: &mut ViewContext<Self>,
 7817    ) -> Result<()> {
 7818        fn select_next_match_ranges(
 7819            this: &mut Editor,
 7820            range: Range<usize>,
 7821            replace_newest: bool,
 7822            auto_scroll: Option<Autoscroll>,
 7823            cx: &mut ViewContext<Editor>,
 7824        ) {
 7825            this.unfold_ranges([range.clone()], false, true, cx);
 7826            this.change_selections(auto_scroll, cx, |s| {
 7827                if replace_newest {
 7828                    s.delete(s.newest_anchor().id);
 7829                }
 7830                s.insert_range(range.clone());
 7831            });
 7832        }
 7833
 7834        let buffer = &display_map.buffer_snapshot;
 7835        let mut selections = self.selections.all::<usize>(cx);
 7836        if let Some(mut select_next_state) = self.select_next_state.take() {
 7837            let query = &select_next_state.query;
 7838            if !select_next_state.done {
 7839                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7840                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7841                let mut next_selected_range = None;
 7842
 7843                let bytes_after_last_selection =
 7844                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7845                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7846                let query_matches = query
 7847                    .stream_find_iter(bytes_after_last_selection)
 7848                    .map(|result| (last_selection.end, result))
 7849                    .chain(
 7850                        query
 7851                            .stream_find_iter(bytes_before_first_selection)
 7852                            .map(|result| (0, result)),
 7853                    );
 7854
 7855                for (start_offset, query_match) in query_matches {
 7856                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7857                    let offset_range =
 7858                        start_offset + query_match.start()..start_offset + query_match.end();
 7859                    let display_range = offset_range.start.to_display_point(&display_map)
 7860                        ..offset_range.end.to_display_point(&display_map);
 7861
 7862                    if !select_next_state.wordwise
 7863                        || (!movement::is_inside_word(&display_map, display_range.start)
 7864                            && !movement::is_inside_word(&display_map, display_range.end))
 7865                    {
 7866                        // TODO: This is n^2, because we might check all the selections
 7867                        if !selections
 7868                            .iter()
 7869                            .any(|selection| selection.range().overlaps(&offset_range))
 7870                        {
 7871                            next_selected_range = Some(offset_range);
 7872                            break;
 7873                        }
 7874                    }
 7875                }
 7876
 7877                if let Some(next_selected_range) = next_selected_range {
 7878                    select_next_match_ranges(
 7879                        self,
 7880                        next_selected_range,
 7881                        replace_newest,
 7882                        autoscroll,
 7883                        cx,
 7884                    );
 7885                } else {
 7886                    select_next_state.done = true;
 7887                }
 7888            }
 7889
 7890            self.select_next_state = Some(select_next_state);
 7891        } else {
 7892            let mut only_carets = true;
 7893            let mut same_text_selected = true;
 7894            let mut selected_text = None;
 7895
 7896            let mut selections_iter = selections.iter().peekable();
 7897            while let Some(selection) = selections_iter.next() {
 7898                if selection.start != selection.end {
 7899                    only_carets = false;
 7900                }
 7901
 7902                if same_text_selected {
 7903                    if selected_text.is_none() {
 7904                        selected_text =
 7905                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7906                    }
 7907
 7908                    if let Some(next_selection) = selections_iter.peek() {
 7909                        if next_selection.range().len() == selection.range().len() {
 7910                            let next_selected_text = buffer
 7911                                .text_for_range(next_selection.range())
 7912                                .collect::<String>();
 7913                            if Some(next_selected_text) != selected_text {
 7914                                same_text_selected = false;
 7915                                selected_text = None;
 7916                            }
 7917                        } else {
 7918                            same_text_selected = false;
 7919                            selected_text = None;
 7920                        }
 7921                    }
 7922                }
 7923            }
 7924
 7925            if only_carets {
 7926                for selection in &mut selections {
 7927                    let word_range = movement::surrounding_word(
 7928                        &display_map,
 7929                        selection.start.to_display_point(&display_map),
 7930                    );
 7931                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7932                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7933                    selection.goal = SelectionGoal::None;
 7934                    selection.reversed = false;
 7935                    select_next_match_ranges(
 7936                        self,
 7937                        selection.start..selection.end,
 7938                        replace_newest,
 7939                        autoscroll,
 7940                        cx,
 7941                    );
 7942                }
 7943
 7944                if selections.len() == 1 {
 7945                    let selection = selections
 7946                        .last()
 7947                        .expect("ensured that there's only one selection");
 7948                    let query = buffer
 7949                        .text_for_range(selection.start..selection.end)
 7950                        .collect::<String>();
 7951                    let is_empty = query.is_empty();
 7952                    let select_state = SelectNextState {
 7953                        query: AhoCorasick::new(&[query])?,
 7954                        wordwise: true,
 7955                        done: is_empty,
 7956                    };
 7957                    self.select_next_state = Some(select_state);
 7958                } else {
 7959                    self.select_next_state = None;
 7960                }
 7961            } else if let Some(selected_text) = selected_text {
 7962                self.select_next_state = Some(SelectNextState {
 7963                    query: AhoCorasick::new(&[selected_text])?,
 7964                    wordwise: false,
 7965                    done: false,
 7966                });
 7967                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7968            }
 7969        }
 7970        Ok(())
 7971    }
 7972
 7973    pub fn select_all_matches(
 7974        &mut self,
 7975        _action: &SelectAllMatches,
 7976        cx: &mut ViewContext<Self>,
 7977    ) -> Result<()> {
 7978        self.push_to_selection_history();
 7979        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7980
 7981        self.select_next_match_internal(&display_map, false, None, cx)?;
 7982        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7983            return Ok(());
 7984        };
 7985        if select_next_state.done {
 7986            return Ok(());
 7987        }
 7988
 7989        let mut new_selections = self.selections.all::<usize>(cx);
 7990
 7991        let buffer = &display_map.buffer_snapshot;
 7992        let query_matches = select_next_state
 7993            .query
 7994            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7995
 7996        for query_match in query_matches {
 7997            let query_match = query_match.unwrap(); // can only fail due to I/O
 7998            let offset_range = query_match.start()..query_match.end();
 7999            let display_range = offset_range.start.to_display_point(&display_map)
 8000                ..offset_range.end.to_display_point(&display_map);
 8001
 8002            if !select_next_state.wordwise
 8003                || (!movement::is_inside_word(&display_map, display_range.start)
 8004                    && !movement::is_inside_word(&display_map, display_range.end))
 8005            {
 8006                self.selections.change_with(cx, |selections| {
 8007                    new_selections.push(Selection {
 8008                        id: selections.new_selection_id(),
 8009                        start: offset_range.start,
 8010                        end: offset_range.end,
 8011                        reversed: false,
 8012                        goal: SelectionGoal::None,
 8013                    });
 8014                });
 8015            }
 8016        }
 8017
 8018        new_selections.sort_by_key(|selection| selection.start);
 8019        let mut ix = 0;
 8020        while ix + 1 < new_selections.len() {
 8021            let current_selection = &new_selections[ix];
 8022            let next_selection = &new_selections[ix + 1];
 8023            if current_selection.range().overlaps(&next_selection.range()) {
 8024                if current_selection.id < next_selection.id {
 8025                    new_selections.remove(ix + 1);
 8026                } else {
 8027                    new_selections.remove(ix);
 8028                }
 8029            } else {
 8030                ix += 1;
 8031            }
 8032        }
 8033
 8034        select_next_state.done = true;
 8035        self.unfold_ranges(
 8036            new_selections.iter().map(|selection| selection.range()),
 8037            false,
 8038            false,
 8039            cx,
 8040        );
 8041        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8042            selections.select(new_selections)
 8043        });
 8044
 8045        Ok(())
 8046    }
 8047
 8048    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8049        self.push_to_selection_history();
 8050        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8051        self.select_next_match_internal(
 8052            &display_map,
 8053            action.replace_newest,
 8054            Some(Autoscroll::newest()),
 8055            cx,
 8056        )?;
 8057        Ok(())
 8058    }
 8059
 8060    pub fn select_previous(
 8061        &mut self,
 8062        action: &SelectPrevious,
 8063        cx: &mut ViewContext<Self>,
 8064    ) -> Result<()> {
 8065        self.push_to_selection_history();
 8066        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8067        let buffer = &display_map.buffer_snapshot;
 8068        let mut selections = self.selections.all::<usize>(cx);
 8069        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8070            let query = &select_prev_state.query;
 8071            if !select_prev_state.done {
 8072                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8073                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8074                let mut next_selected_range = None;
 8075                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8076                let bytes_before_last_selection =
 8077                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8078                let bytes_after_first_selection =
 8079                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8080                let query_matches = query
 8081                    .stream_find_iter(bytes_before_last_selection)
 8082                    .map(|result| (last_selection.start, result))
 8083                    .chain(
 8084                        query
 8085                            .stream_find_iter(bytes_after_first_selection)
 8086                            .map(|result| (buffer.len(), result)),
 8087                    );
 8088                for (end_offset, query_match) in query_matches {
 8089                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8090                    let offset_range =
 8091                        end_offset - query_match.end()..end_offset - query_match.start();
 8092                    let display_range = offset_range.start.to_display_point(&display_map)
 8093                        ..offset_range.end.to_display_point(&display_map);
 8094
 8095                    if !select_prev_state.wordwise
 8096                        || (!movement::is_inside_word(&display_map, display_range.start)
 8097                            && !movement::is_inside_word(&display_map, display_range.end))
 8098                    {
 8099                        next_selected_range = Some(offset_range);
 8100                        break;
 8101                    }
 8102                }
 8103
 8104                if let Some(next_selected_range) = next_selected_range {
 8105                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8106                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8107                        if action.replace_newest {
 8108                            s.delete(s.newest_anchor().id);
 8109                        }
 8110                        s.insert_range(next_selected_range);
 8111                    });
 8112                } else {
 8113                    select_prev_state.done = true;
 8114                }
 8115            }
 8116
 8117            self.select_prev_state = Some(select_prev_state);
 8118        } else {
 8119            let mut only_carets = true;
 8120            let mut same_text_selected = true;
 8121            let mut selected_text = None;
 8122
 8123            let mut selections_iter = selections.iter().peekable();
 8124            while let Some(selection) = selections_iter.next() {
 8125                if selection.start != selection.end {
 8126                    only_carets = false;
 8127                }
 8128
 8129                if same_text_selected {
 8130                    if selected_text.is_none() {
 8131                        selected_text =
 8132                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8133                    }
 8134
 8135                    if let Some(next_selection) = selections_iter.peek() {
 8136                        if next_selection.range().len() == selection.range().len() {
 8137                            let next_selected_text = buffer
 8138                                .text_for_range(next_selection.range())
 8139                                .collect::<String>();
 8140                            if Some(next_selected_text) != selected_text {
 8141                                same_text_selected = false;
 8142                                selected_text = None;
 8143                            }
 8144                        } else {
 8145                            same_text_selected = false;
 8146                            selected_text = None;
 8147                        }
 8148                    }
 8149                }
 8150            }
 8151
 8152            if only_carets {
 8153                for selection in &mut selections {
 8154                    let word_range = movement::surrounding_word(
 8155                        &display_map,
 8156                        selection.start.to_display_point(&display_map),
 8157                    );
 8158                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8159                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8160                    selection.goal = SelectionGoal::None;
 8161                    selection.reversed = false;
 8162                }
 8163                if selections.len() == 1 {
 8164                    let selection = selections
 8165                        .last()
 8166                        .expect("ensured that there's only one selection");
 8167                    let query = buffer
 8168                        .text_for_range(selection.start..selection.end)
 8169                        .collect::<String>();
 8170                    let is_empty = query.is_empty();
 8171                    let select_state = SelectNextState {
 8172                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8173                        wordwise: true,
 8174                        done: is_empty,
 8175                    };
 8176                    self.select_prev_state = Some(select_state);
 8177                } else {
 8178                    self.select_prev_state = None;
 8179                }
 8180
 8181                self.unfold_ranges(
 8182                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8183                    false,
 8184                    true,
 8185                    cx,
 8186                );
 8187                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8188                    s.select(selections);
 8189                });
 8190            } else if let Some(selected_text) = selected_text {
 8191                self.select_prev_state = Some(SelectNextState {
 8192                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8193                    wordwise: false,
 8194                    done: false,
 8195                });
 8196                self.select_previous(action, cx)?;
 8197            }
 8198        }
 8199        Ok(())
 8200    }
 8201
 8202    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8203        let text_layout_details = &self.text_layout_details(cx);
 8204        self.transact(cx, |this, cx| {
 8205            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8206            let mut edits = Vec::new();
 8207            let mut selection_edit_ranges = Vec::new();
 8208            let mut last_toggled_row = None;
 8209            let snapshot = this.buffer.read(cx).read(cx);
 8210            let empty_str: Arc<str> = Arc::default();
 8211            let mut suffixes_inserted = Vec::new();
 8212
 8213            fn comment_prefix_range(
 8214                snapshot: &MultiBufferSnapshot,
 8215                row: MultiBufferRow,
 8216                comment_prefix: &str,
 8217                comment_prefix_whitespace: &str,
 8218            ) -> Range<Point> {
 8219                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8220
 8221                let mut line_bytes = snapshot
 8222                    .bytes_in_range(start..snapshot.max_point())
 8223                    .flatten()
 8224                    .copied();
 8225
 8226                // If this line currently begins with the line comment prefix, then record
 8227                // the range containing the prefix.
 8228                if line_bytes
 8229                    .by_ref()
 8230                    .take(comment_prefix.len())
 8231                    .eq(comment_prefix.bytes())
 8232                {
 8233                    // Include any whitespace that matches the comment prefix.
 8234                    let matching_whitespace_len = line_bytes
 8235                        .zip(comment_prefix_whitespace.bytes())
 8236                        .take_while(|(a, b)| a == b)
 8237                        .count() as u32;
 8238                    let end = Point::new(
 8239                        start.row,
 8240                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8241                    );
 8242                    start..end
 8243                } else {
 8244                    start..start
 8245                }
 8246            }
 8247
 8248            fn comment_suffix_range(
 8249                snapshot: &MultiBufferSnapshot,
 8250                row: MultiBufferRow,
 8251                comment_suffix: &str,
 8252                comment_suffix_has_leading_space: bool,
 8253            ) -> Range<Point> {
 8254                let end = Point::new(row.0, snapshot.line_len(row));
 8255                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8256
 8257                let mut line_end_bytes = snapshot
 8258                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8259                    .flatten()
 8260                    .copied();
 8261
 8262                let leading_space_len = if suffix_start_column > 0
 8263                    && line_end_bytes.next() == Some(b' ')
 8264                    && comment_suffix_has_leading_space
 8265                {
 8266                    1
 8267                } else {
 8268                    0
 8269                };
 8270
 8271                // If this line currently begins with the line comment prefix, then record
 8272                // the range containing the prefix.
 8273                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8274                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8275                    start..end
 8276                } else {
 8277                    end..end
 8278                }
 8279            }
 8280
 8281            // TODO: Handle selections that cross excerpts
 8282            for selection in &mut selections {
 8283                let start_column = snapshot
 8284                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8285                    .len;
 8286                let language = if let Some(language) =
 8287                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8288                {
 8289                    language
 8290                } else {
 8291                    continue;
 8292                };
 8293
 8294                selection_edit_ranges.clear();
 8295
 8296                // If multiple selections contain a given row, avoid processing that
 8297                // row more than once.
 8298                let mut start_row = MultiBufferRow(selection.start.row);
 8299                if last_toggled_row == Some(start_row) {
 8300                    start_row = start_row.next_row();
 8301                }
 8302                let end_row =
 8303                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8304                        MultiBufferRow(selection.end.row - 1)
 8305                    } else {
 8306                        MultiBufferRow(selection.end.row)
 8307                    };
 8308                last_toggled_row = Some(end_row);
 8309
 8310                if start_row > end_row {
 8311                    continue;
 8312                }
 8313
 8314                // If the language has line comments, toggle those.
 8315                let full_comment_prefixes = language.line_comment_prefixes();
 8316                if !full_comment_prefixes.is_empty() {
 8317                    let first_prefix = full_comment_prefixes
 8318                        .first()
 8319                        .expect("prefixes is non-empty");
 8320                    let prefix_trimmed_lengths = full_comment_prefixes
 8321                        .iter()
 8322                        .map(|p| p.trim_end_matches(' ').len())
 8323                        .collect::<SmallVec<[usize; 4]>>();
 8324
 8325                    let mut all_selection_lines_are_comments = true;
 8326
 8327                    for row in start_row.0..=end_row.0 {
 8328                        let row = MultiBufferRow(row);
 8329                        if start_row < end_row && snapshot.is_line_blank(row) {
 8330                            continue;
 8331                        }
 8332
 8333                        let prefix_range = full_comment_prefixes
 8334                            .iter()
 8335                            .zip(prefix_trimmed_lengths.iter().copied())
 8336                            .map(|(prefix, trimmed_prefix_len)| {
 8337                                comment_prefix_range(
 8338                                    snapshot.deref(),
 8339                                    row,
 8340                                    &prefix[..trimmed_prefix_len],
 8341                                    &prefix[trimmed_prefix_len..],
 8342                                )
 8343                            })
 8344                            .max_by_key(|range| range.end.column - range.start.column)
 8345                            .expect("prefixes is non-empty");
 8346
 8347                        if prefix_range.is_empty() {
 8348                            all_selection_lines_are_comments = false;
 8349                        }
 8350
 8351                        selection_edit_ranges.push(prefix_range);
 8352                    }
 8353
 8354                    if all_selection_lines_are_comments {
 8355                        edits.extend(
 8356                            selection_edit_ranges
 8357                                .iter()
 8358                                .cloned()
 8359                                .map(|range| (range, empty_str.clone())),
 8360                        );
 8361                    } else {
 8362                        let min_column = selection_edit_ranges
 8363                            .iter()
 8364                            .map(|range| range.start.column)
 8365                            .min()
 8366                            .unwrap_or(0);
 8367                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8368                            let position = Point::new(range.start.row, min_column);
 8369                            (position..position, first_prefix.clone())
 8370                        }));
 8371                    }
 8372                } else if let Some((full_comment_prefix, comment_suffix)) =
 8373                    language.block_comment_delimiters()
 8374                {
 8375                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8376                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8377                    let prefix_range = comment_prefix_range(
 8378                        snapshot.deref(),
 8379                        start_row,
 8380                        comment_prefix,
 8381                        comment_prefix_whitespace,
 8382                    );
 8383                    let suffix_range = comment_suffix_range(
 8384                        snapshot.deref(),
 8385                        end_row,
 8386                        comment_suffix.trim_start_matches(' '),
 8387                        comment_suffix.starts_with(' '),
 8388                    );
 8389
 8390                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8391                        edits.push((
 8392                            prefix_range.start..prefix_range.start,
 8393                            full_comment_prefix.clone(),
 8394                        ));
 8395                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8396                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8397                    } else {
 8398                        edits.push((prefix_range, empty_str.clone()));
 8399                        edits.push((suffix_range, empty_str.clone()));
 8400                    }
 8401                } else {
 8402                    continue;
 8403                }
 8404            }
 8405
 8406            drop(snapshot);
 8407            this.buffer.update(cx, |buffer, cx| {
 8408                buffer.edit(edits, None, cx);
 8409            });
 8410
 8411            // Adjust selections so that they end before any comment suffixes that
 8412            // were inserted.
 8413            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8414            let mut selections = this.selections.all::<Point>(cx);
 8415            let snapshot = this.buffer.read(cx).read(cx);
 8416            for selection in &mut selections {
 8417                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8418                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8419                        Ordering::Less => {
 8420                            suffixes_inserted.next();
 8421                            continue;
 8422                        }
 8423                        Ordering::Greater => break,
 8424                        Ordering::Equal => {
 8425                            if selection.end.column == snapshot.line_len(row) {
 8426                                if selection.is_empty() {
 8427                                    selection.start.column -= suffix_len as u32;
 8428                                }
 8429                                selection.end.column -= suffix_len as u32;
 8430                            }
 8431                            break;
 8432                        }
 8433                    }
 8434                }
 8435            }
 8436
 8437            drop(snapshot);
 8438            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8439
 8440            let selections = this.selections.all::<Point>(cx);
 8441            let selections_on_single_row = selections.windows(2).all(|selections| {
 8442                selections[0].start.row == selections[1].start.row
 8443                    && selections[0].end.row == selections[1].end.row
 8444                    && selections[0].start.row == selections[0].end.row
 8445            });
 8446            let selections_selecting = selections
 8447                .iter()
 8448                .any(|selection| selection.start != selection.end);
 8449            let advance_downwards = action.advance_downwards
 8450                && selections_on_single_row
 8451                && !selections_selecting
 8452                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8453
 8454            if advance_downwards {
 8455                let snapshot = this.buffer.read(cx).snapshot(cx);
 8456
 8457                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8458                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8459                        let mut point = display_point.to_point(display_snapshot);
 8460                        point.row += 1;
 8461                        point = snapshot.clip_point(point, Bias::Left);
 8462                        let display_point = point.to_display_point(display_snapshot);
 8463                        let goal = SelectionGoal::HorizontalPosition(
 8464                            display_snapshot
 8465                                .x_for_display_point(display_point, &text_layout_details)
 8466                                .into(),
 8467                        );
 8468                        (display_point, goal)
 8469                    })
 8470                });
 8471            }
 8472        });
 8473    }
 8474
 8475    pub fn select_enclosing_symbol(
 8476        &mut self,
 8477        _: &SelectEnclosingSymbol,
 8478        cx: &mut ViewContext<Self>,
 8479    ) {
 8480        let buffer = self.buffer.read(cx).snapshot(cx);
 8481        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8482
 8483        fn update_selection(
 8484            selection: &Selection<usize>,
 8485            buffer_snap: &MultiBufferSnapshot,
 8486        ) -> Option<Selection<usize>> {
 8487            let cursor = selection.head();
 8488            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8489            for symbol in symbols.iter().rev() {
 8490                let start = symbol.range.start.to_offset(&buffer_snap);
 8491                let end = symbol.range.end.to_offset(&buffer_snap);
 8492                let new_range = start..end;
 8493                if start < selection.start || end > selection.end {
 8494                    return Some(Selection {
 8495                        id: selection.id,
 8496                        start: new_range.start,
 8497                        end: new_range.end,
 8498                        goal: SelectionGoal::None,
 8499                        reversed: selection.reversed,
 8500                    });
 8501                }
 8502            }
 8503            None
 8504        }
 8505
 8506        let mut selected_larger_symbol = false;
 8507        let new_selections = old_selections
 8508            .iter()
 8509            .map(|selection| match update_selection(selection, &buffer) {
 8510                Some(new_selection) => {
 8511                    if new_selection.range() != selection.range() {
 8512                        selected_larger_symbol = true;
 8513                    }
 8514                    new_selection
 8515                }
 8516                None => selection.clone(),
 8517            })
 8518            .collect::<Vec<_>>();
 8519
 8520        if selected_larger_symbol {
 8521            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8522                s.select(new_selections);
 8523            });
 8524        }
 8525    }
 8526
 8527    pub fn select_larger_syntax_node(
 8528        &mut self,
 8529        _: &SelectLargerSyntaxNode,
 8530        cx: &mut ViewContext<Self>,
 8531    ) {
 8532        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8533        let buffer = self.buffer.read(cx).snapshot(cx);
 8534        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8535
 8536        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8537        let mut selected_larger_node = false;
 8538        let new_selections = old_selections
 8539            .iter()
 8540            .map(|selection| {
 8541                let old_range = selection.start..selection.end;
 8542                let mut new_range = old_range.clone();
 8543                while let Some(containing_range) =
 8544                    buffer.range_for_syntax_ancestor(new_range.clone())
 8545                {
 8546                    new_range = containing_range;
 8547                    if !display_map.intersects_fold(new_range.start)
 8548                        && !display_map.intersects_fold(new_range.end)
 8549                    {
 8550                        break;
 8551                    }
 8552                }
 8553
 8554                selected_larger_node |= new_range != old_range;
 8555                Selection {
 8556                    id: selection.id,
 8557                    start: new_range.start,
 8558                    end: new_range.end,
 8559                    goal: SelectionGoal::None,
 8560                    reversed: selection.reversed,
 8561                }
 8562            })
 8563            .collect::<Vec<_>>();
 8564
 8565        if selected_larger_node {
 8566            stack.push(old_selections);
 8567            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8568                s.select(new_selections);
 8569            });
 8570        }
 8571        self.select_larger_syntax_node_stack = stack;
 8572    }
 8573
 8574    pub fn select_smaller_syntax_node(
 8575        &mut self,
 8576        _: &SelectSmallerSyntaxNode,
 8577        cx: &mut ViewContext<Self>,
 8578    ) {
 8579        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8580        if let Some(selections) = stack.pop() {
 8581            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8582                s.select(selections.to_vec());
 8583            });
 8584        }
 8585        self.select_larger_syntax_node_stack = stack;
 8586    }
 8587
 8588    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8589        if !EditorSettings::get_global(cx).gutter.runnables {
 8590            self.clear_tasks();
 8591            return Task::ready(());
 8592        }
 8593        let project = self.project.clone();
 8594        cx.spawn(|this, mut cx| async move {
 8595            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8596                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8597            }) else {
 8598                return;
 8599            };
 8600
 8601            let Some(project) = project else {
 8602                return;
 8603            };
 8604
 8605            let hide_runnables = project
 8606                .update(&mut cx, |project, cx| {
 8607                    // Do not display any test indicators in non-dev server remote projects.
 8608                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8609                })
 8610                .unwrap_or(true);
 8611            if hide_runnables {
 8612                return;
 8613            }
 8614            let new_rows =
 8615                cx.background_executor()
 8616                    .spawn({
 8617                        let snapshot = display_snapshot.clone();
 8618                        async move {
 8619                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8620                        }
 8621                    })
 8622                    .await;
 8623            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8624
 8625            this.update(&mut cx, |this, _| {
 8626                this.clear_tasks();
 8627                for (key, value) in rows {
 8628                    this.insert_tasks(key, value);
 8629                }
 8630            })
 8631            .ok();
 8632        })
 8633    }
 8634    fn fetch_runnable_ranges(
 8635        snapshot: &DisplaySnapshot,
 8636        range: Range<Anchor>,
 8637    ) -> Vec<language::RunnableRange> {
 8638        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8639    }
 8640
 8641    fn runnable_rows(
 8642        project: Model<Project>,
 8643        snapshot: DisplaySnapshot,
 8644        runnable_ranges: Vec<RunnableRange>,
 8645        mut cx: AsyncWindowContext,
 8646    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8647        runnable_ranges
 8648            .into_iter()
 8649            .filter_map(|mut runnable| {
 8650                let tasks = cx
 8651                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8652                    .ok()?;
 8653                if tasks.is_empty() {
 8654                    return None;
 8655                }
 8656
 8657                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8658
 8659                let row = snapshot
 8660                    .buffer_snapshot
 8661                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8662                    .1
 8663                    .start
 8664                    .row;
 8665
 8666                let context_range =
 8667                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8668                Some((
 8669                    (runnable.buffer_id, row),
 8670                    RunnableTasks {
 8671                        templates: tasks,
 8672                        offset: MultiBufferOffset(runnable.run_range.start),
 8673                        context_range,
 8674                        column: point.column,
 8675                        extra_variables: runnable.extra_captures,
 8676                    },
 8677                ))
 8678            })
 8679            .collect()
 8680    }
 8681
 8682    fn templates_with_tags(
 8683        project: &Model<Project>,
 8684        runnable: &mut Runnable,
 8685        cx: &WindowContext<'_>,
 8686    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8687        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8688            let (worktree_id, file) = project
 8689                .buffer_for_id(runnable.buffer, cx)
 8690                .and_then(|buffer| buffer.read(cx).file())
 8691                .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
 8692                .unzip();
 8693
 8694            (project.task_inventory().clone(), worktree_id, file)
 8695        });
 8696
 8697        let inventory = inventory.read(cx);
 8698        let tags = mem::take(&mut runnable.tags);
 8699        let mut tags: Vec<_> = tags
 8700            .into_iter()
 8701            .flat_map(|tag| {
 8702                let tag = tag.0.clone();
 8703                inventory
 8704                    .list_tasks(
 8705                        file.clone(),
 8706                        Some(runnable.language.clone()),
 8707                        worktree_id,
 8708                        cx,
 8709                    )
 8710                    .into_iter()
 8711                    .filter(move |(_, template)| {
 8712                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8713                    })
 8714            })
 8715            .sorted_by_key(|(kind, _)| kind.to_owned())
 8716            .collect();
 8717        if let Some((leading_tag_source, _)) = tags.first() {
 8718            // Strongest source wins; if we have worktree tag binding, prefer that to
 8719            // global and language bindings;
 8720            // if we have a global binding, prefer that to language binding.
 8721            let first_mismatch = tags
 8722                .iter()
 8723                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8724            if let Some(index) = first_mismatch {
 8725                tags.truncate(index);
 8726            }
 8727        }
 8728
 8729        tags
 8730    }
 8731
 8732    pub fn move_to_enclosing_bracket(
 8733        &mut self,
 8734        _: &MoveToEnclosingBracket,
 8735        cx: &mut ViewContext<Self>,
 8736    ) {
 8737        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8738            s.move_offsets_with(|snapshot, selection| {
 8739                let Some(enclosing_bracket_ranges) =
 8740                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8741                else {
 8742                    return;
 8743                };
 8744
 8745                let mut best_length = usize::MAX;
 8746                let mut best_inside = false;
 8747                let mut best_in_bracket_range = false;
 8748                let mut best_destination = None;
 8749                for (open, close) in enclosing_bracket_ranges {
 8750                    let close = close.to_inclusive();
 8751                    let length = close.end() - open.start;
 8752                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8753                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8754                        || close.contains(&selection.head());
 8755
 8756                    // If best is next to a bracket and current isn't, skip
 8757                    if !in_bracket_range && best_in_bracket_range {
 8758                        continue;
 8759                    }
 8760
 8761                    // Prefer smaller lengths unless best is inside and current isn't
 8762                    if length > best_length && (best_inside || !inside) {
 8763                        continue;
 8764                    }
 8765
 8766                    best_length = length;
 8767                    best_inside = inside;
 8768                    best_in_bracket_range = in_bracket_range;
 8769                    best_destination = Some(
 8770                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8771                            if inside {
 8772                                open.end
 8773                            } else {
 8774                                open.start
 8775                            }
 8776                        } else {
 8777                            if inside {
 8778                                *close.start()
 8779                            } else {
 8780                                *close.end()
 8781                            }
 8782                        },
 8783                    );
 8784                }
 8785
 8786                if let Some(destination) = best_destination {
 8787                    selection.collapse_to(destination, SelectionGoal::None);
 8788                }
 8789            })
 8790        });
 8791    }
 8792
 8793    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8794        self.end_selection(cx);
 8795        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8796        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8797            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8798            self.select_next_state = entry.select_next_state;
 8799            self.select_prev_state = entry.select_prev_state;
 8800            self.add_selections_state = entry.add_selections_state;
 8801            self.request_autoscroll(Autoscroll::newest(), cx);
 8802        }
 8803        self.selection_history.mode = SelectionHistoryMode::Normal;
 8804    }
 8805
 8806    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8807        self.end_selection(cx);
 8808        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8809        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8810            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8811            self.select_next_state = entry.select_next_state;
 8812            self.select_prev_state = entry.select_prev_state;
 8813            self.add_selections_state = entry.add_selections_state;
 8814            self.request_autoscroll(Autoscroll::newest(), cx);
 8815        }
 8816        self.selection_history.mode = SelectionHistoryMode::Normal;
 8817    }
 8818
 8819    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8820        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8821    }
 8822
 8823    pub fn expand_excerpts_down(
 8824        &mut self,
 8825        action: &ExpandExcerptsDown,
 8826        cx: &mut ViewContext<Self>,
 8827    ) {
 8828        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8829    }
 8830
 8831    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8832        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8833    }
 8834
 8835    pub fn expand_excerpts_for_direction(
 8836        &mut self,
 8837        lines: u32,
 8838        direction: ExpandExcerptDirection,
 8839        cx: &mut ViewContext<Self>,
 8840    ) {
 8841        let selections = self.selections.disjoint_anchors();
 8842
 8843        let lines = if lines == 0 {
 8844            EditorSettings::get_global(cx).expand_excerpt_lines
 8845        } else {
 8846            lines
 8847        };
 8848
 8849        self.buffer.update(cx, |buffer, cx| {
 8850            buffer.expand_excerpts(
 8851                selections
 8852                    .into_iter()
 8853                    .map(|selection| selection.head().excerpt_id)
 8854                    .dedup(),
 8855                lines,
 8856                direction,
 8857                cx,
 8858            )
 8859        })
 8860    }
 8861
 8862    pub fn expand_excerpt(
 8863        &mut self,
 8864        excerpt: ExcerptId,
 8865        direction: ExpandExcerptDirection,
 8866        cx: &mut ViewContext<Self>,
 8867    ) {
 8868        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8869        self.buffer.update(cx, |buffer, cx| {
 8870            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8871        })
 8872    }
 8873
 8874    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8875        self.go_to_diagnostic_impl(Direction::Next, cx)
 8876    }
 8877
 8878    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8879        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8880    }
 8881
 8882    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8883        let buffer = self.buffer.read(cx).snapshot(cx);
 8884        let selection = self.selections.newest::<usize>(cx);
 8885
 8886        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8887        if direction == Direction::Next {
 8888            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8889                let (group_id, jump_to) = popover.activation_info();
 8890                if self.activate_diagnostics(group_id, cx) {
 8891                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8892                        let mut new_selection = s.newest_anchor().clone();
 8893                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8894                        s.select_anchors(vec![new_selection.clone()]);
 8895                    });
 8896                }
 8897                return;
 8898            }
 8899        }
 8900
 8901        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8902            active_diagnostics
 8903                .primary_range
 8904                .to_offset(&buffer)
 8905                .to_inclusive()
 8906        });
 8907        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8908            if active_primary_range.contains(&selection.head()) {
 8909                *active_primary_range.start()
 8910            } else {
 8911                selection.head()
 8912            }
 8913        } else {
 8914            selection.head()
 8915        };
 8916        let snapshot = self.snapshot(cx);
 8917        loop {
 8918            let diagnostics = if direction == Direction::Prev {
 8919                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8920            } else {
 8921                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8922            }
 8923            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8924            let group = diagnostics
 8925                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8926                // be sorted in a stable way
 8927                // skip until we are at current active diagnostic, if it exists
 8928                .skip_while(|entry| {
 8929                    (match direction {
 8930                        Direction::Prev => entry.range.start >= search_start,
 8931                        Direction::Next => entry.range.start <= search_start,
 8932                    }) && self
 8933                        .active_diagnostics
 8934                        .as_ref()
 8935                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8936                })
 8937                .find_map(|entry| {
 8938                    if entry.diagnostic.is_primary
 8939                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8940                        && !entry.range.is_empty()
 8941                        // if we match with the active diagnostic, skip it
 8942                        && Some(entry.diagnostic.group_id)
 8943                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8944                    {
 8945                        Some((entry.range, entry.diagnostic.group_id))
 8946                    } else {
 8947                        None
 8948                    }
 8949                });
 8950
 8951            if let Some((primary_range, group_id)) = group {
 8952                if self.activate_diagnostics(group_id, cx) {
 8953                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8954                        s.select(vec![Selection {
 8955                            id: selection.id,
 8956                            start: primary_range.start,
 8957                            end: primary_range.start,
 8958                            reversed: false,
 8959                            goal: SelectionGoal::None,
 8960                        }]);
 8961                    });
 8962                }
 8963                break;
 8964            } else {
 8965                // Cycle around to the start of the buffer, potentially moving back to the start of
 8966                // the currently active diagnostic.
 8967                active_primary_range.take();
 8968                if direction == Direction::Prev {
 8969                    if search_start == buffer.len() {
 8970                        break;
 8971                    } else {
 8972                        search_start = buffer.len();
 8973                    }
 8974                } else if search_start == 0 {
 8975                    break;
 8976                } else {
 8977                    search_start = 0;
 8978                }
 8979            }
 8980        }
 8981    }
 8982
 8983    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 8984        let snapshot = self
 8985            .display_map
 8986            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8987        let selection = self.selections.newest::<Point>(cx);
 8988
 8989        if !self.seek_in_direction(
 8990            &snapshot,
 8991            selection.head(),
 8992            false,
 8993            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8994                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 8995            ),
 8996            cx,
 8997        ) {
 8998            let wrapped_point = Point::zero();
 8999            self.seek_in_direction(
 9000                &snapshot,
 9001                wrapped_point,
 9002                true,
 9003                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9004                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9005                ),
 9006                cx,
 9007            );
 9008        }
 9009    }
 9010
 9011    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9012        let snapshot = self
 9013            .display_map
 9014            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9015        let selection = self.selections.newest::<Point>(cx);
 9016
 9017        if !self.seek_in_direction(
 9018            &snapshot,
 9019            selection.head(),
 9020            false,
 9021            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 9022                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 9023            ),
 9024            cx,
 9025        ) {
 9026            let wrapped_point = snapshot.buffer_snapshot.max_point();
 9027            self.seek_in_direction(
 9028                &snapshot,
 9029                wrapped_point,
 9030                true,
 9031                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 9032                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 9033                ),
 9034                cx,
 9035            );
 9036        }
 9037    }
 9038
 9039    fn seek_in_direction(
 9040        &mut self,
 9041        snapshot: &DisplaySnapshot,
 9042        initial_point: Point,
 9043        is_wrapped: bool,
 9044        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 9045        cx: &mut ViewContext<Editor>,
 9046    ) -> bool {
 9047        let display_point = initial_point.to_display_point(snapshot);
 9048        let mut hunks = hunks
 9049            .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
 9050            .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
 9051            .dedup();
 9052
 9053        if let Some(hunk) = hunks.next() {
 9054            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9055                let row = hunk.start_display_row();
 9056                let point = DisplayPoint::new(row, 0);
 9057                s.select_display_ranges([point..point]);
 9058            });
 9059
 9060            true
 9061        } else {
 9062            false
 9063        }
 9064    }
 9065
 9066    pub fn go_to_definition(
 9067        &mut self,
 9068        _: &GoToDefinition,
 9069        cx: &mut ViewContext<Self>,
 9070    ) -> Task<Result<Navigated>> {
 9071        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9072        let references = self.find_all_references(&FindAllReferences, cx);
 9073        cx.background_executor().spawn(async move {
 9074            if definition.await? == Navigated::Yes {
 9075                return Ok(Navigated::Yes);
 9076            }
 9077            if let Some(references) = references {
 9078                if references.await? == Navigated::Yes {
 9079                    return Ok(Navigated::Yes);
 9080                }
 9081            }
 9082
 9083            Ok(Navigated::No)
 9084        })
 9085    }
 9086
 9087    pub fn go_to_declaration(
 9088        &mut self,
 9089        _: &GoToDeclaration,
 9090        cx: &mut ViewContext<Self>,
 9091    ) -> Task<Result<Navigated>> {
 9092        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9093    }
 9094
 9095    pub fn go_to_declaration_split(
 9096        &mut self,
 9097        _: &GoToDeclaration,
 9098        cx: &mut ViewContext<Self>,
 9099    ) -> Task<Result<Navigated>> {
 9100        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9101    }
 9102
 9103    pub fn go_to_implementation(
 9104        &mut self,
 9105        _: &GoToImplementation,
 9106        cx: &mut ViewContext<Self>,
 9107    ) -> Task<Result<Navigated>> {
 9108        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9109    }
 9110
 9111    pub fn go_to_implementation_split(
 9112        &mut self,
 9113        _: &GoToImplementationSplit,
 9114        cx: &mut ViewContext<Self>,
 9115    ) -> Task<Result<Navigated>> {
 9116        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9117    }
 9118
 9119    pub fn go_to_type_definition(
 9120        &mut self,
 9121        _: &GoToTypeDefinition,
 9122        cx: &mut ViewContext<Self>,
 9123    ) -> Task<Result<Navigated>> {
 9124        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9125    }
 9126
 9127    pub fn go_to_definition_split(
 9128        &mut self,
 9129        _: &GoToDefinitionSplit,
 9130        cx: &mut ViewContext<Self>,
 9131    ) -> Task<Result<Navigated>> {
 9132        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9133    }
 9134
 9135    pub fn go_to_type_definition_split(
 9136        &mut self,
 9137        _: &GoToTypeDefinitionSplit,
 9138        cx: &mut ViewContext<Self>,
 9139    ) -> Task<Result<Navigated>> {
 9140        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9141    }
 9142
 9143    fn go_to_definition_of_kind(
 9144        &mut self,
 9145        kind: GotoDefinitionKind,
 9146        split: bool,
 9147        cx: &mut ViewContext<Self>,
 9148    ) -> Task<Result<Navigated>> {
 9149        let Some(workspace) = self.workspace() else {
 9150            return Task::ready(Ok(Navigated::No));
 9151        };
 9152        let buffer = self.buffer.read(cx);
 9153        let head = self.selections.newest::<usize>(cx).head();
 9154        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9155            text_anchor
 9156        } else {
 9157            return Task::ready(Ok(Navigated::No));
 9158        };
 9159
 9160        let project = workspace.read(cx).project().clone();
 9161        let definitions = project.update(cx, |project, cx| match kind {
 9162            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 9163            GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
 9164            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 9165            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 9166        });
 9167
 9168        cx.spawn(|editor, mut cx| async move {
 9169            let definitions = definitions.await?;
 9170            let navigated = editor
 9171                .update(&mut cx, |editor, cx| {
 9172                    editor.navigate_to_hover_links(
 9173                        Some(kind),
 9174                        definitions
 9175                            .into_iter()
 9176                            .filter(|location| {
 9177                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9178                            })
 9179                            .map(HoverLink::Text)
 9180                            .collect::<Vec<_>>(),
 9181                        split,
 9182                        cx,
 9183                    )
 9184                })?
 9185                .await?;
 9186            anyhow::Ok(navigated)
 9187        })
 9188    }
 9189
 9190    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9191        let position = self.selections.newest_anchor().head();
 9192        let Some((buffer, buffer_position)) =
 9193            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9194        else {
 9195            return;
 9196        };
 9197
 9198        cx.spawn(|editor, mut cx| async move {
 9199            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9200                editor.update(&mut cx, |_, cx| {
 9201                    cx.open_url(&url);
 9202                })
 9203            } else {
 9204                Ok(())
 9205            }
 9206        })
 9207        .detach();
 9208    }
 9209
 9210    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9211        let Some(workspace) = self.workspace() else {
 9212            return;
 9213        };
 9214
 9215        let position = self.selections.newest_anchor().head();
 9216
 9217        let Some((buffer, buffer_position)) =
 9218            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9219        else {
 9220            return;
 9221        };
 9222
 9223        let Some(project) = self.project.clone() else {
 9224            return;
 9225        };
 9226
 9227        cx.spawn(|_, mut cx| async move {
 9228            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9229
 9230            if let Some((_, path)) = result {
 9231                workspace
 9232                    .update(&mut cx, |workspace, cx| {
 9233                        workspace.open_resolved_path(path, cx)
 9234                    })?
 9235                    .await?;
 9236            }
 9237            anyhow::Ok(())
 9238        })
 9239        .detach();
 9240    }
 9241
 9242    pub(crate) fn navigate_to_hover_links(
 9243        &mut self,
 9244        kind: Option<GotoDefinitionKind>,
 9245        mut definitions: Vec<HoverLink>,
 9246        split: bool,
 9247        cx: &mut ViewContext<Editor>,
 9248    ) -> Task<Result<Navigated>> {
 9249        // If there is one definition, just open it directly
 9250        if definitions.len() == 1 {
 9251            let definition = definitions.pop().unwrap();
 9252
 9253            enum TargetTaskResult {
 9254                Location(Option<Location>),
 9255                AlreadyNavigated,
 9256            }
 9257
 9258            let target_task = match definition {
 9259                HoverLink::Text(link) => {
 9260                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9261                }
 9262                HoverLink::InlayHint(lsp_location, server_id) => {
 9263                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9264                    cx.background_executor().spawn(async move {
 9265                        let location = computation.await?;
 9266                        Ok(TargetTaskResult::Location(location))
 9267                    })
 9268                }
 9269                HoverLink::Url(url) => {
 9270                    cx.open_url(&url);
 9271                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9272                }
 9273                HoverLink::File(path) => {
 9274                    if let Some(workspace) = self.workspace() {
 9275                        cx.spawn(|_, mut cx| async move {
 9276                            workspace
 9277                                .update(&mut cx, |workspace, cx| {
 9278                                    workspace.open_resolved_path(path, cx)
 9279                                })?
 9280                                .await
 9281                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9282                        })
 9283                    } else {
 9284                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9285                    }
 9286                }
 9287            };
 9288            cx.spawn(|editor, mut cx| async move {
 9289                let target = match target_task.await.context("target resolution task")? {
 9290                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9291                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9292                    TargetTaskResult::Location(Some(target)) => target,
 9293                };
 9294
 9295                editor.update(&mut cx, |editor, cx| {
 9296                    let Some(workspace) = editor.workspace() else {
 9297                        return Navigated::No;
 9298                    };
 9299                    let pane = workspace.read(cx).active_pane().clone();
 9300
 9301                    let range = target.range.to_offset(target.buffer.read(cx));
 9302                    let range = editor.range_for_match(&range);
 9303
 9304                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9305                        let buffer = target.buffer.read(cx);
 9306                        let range = check_multiline_range(buffer, range);
 9307                        editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 9308                            s.select_ranges([range]);
 9309                        });
 9310                    } else {
 9311                        cx.window_context().defer(move |cx| {
 9312                            let target_editor: View<Self> =
 9313                                workspace.update(cx, |workspace, cx| {
 9314                                    let pane = if split {
 9315                                        workspace.adjacent_pane(cx)
 9316                                    } else {
 9317                                        workspace.active_pane().clone()
 9318                                    };
 9319
 9320                                    workspace.open_project_item(
 9321                                        pane,
 9322                                        target.buffer.clone(),
 9323                                        true,
 9324                                        true,
 9325                                        cx,
 9326                                    )
 9327                                });
 9328                            target_editor.update(cx, |target_editor, cx| {
 9329                                // When selecting a definition in a different buffer, disable the nav history
 9330                                // to avoid creating a history entry at the previous cursor location.
 9331                                pane.update(cx, |pane, _| pane.disable_history());
 9332                                let buffer = target.buffer.read(cx);
 9333                                let range = check_multiline_range(buffer, range);
 9334                                target_editor.change_selections(
 9335                                    Some(Autoscroll::focused()),
 9336                                    cx,
 9337                                    |s| {
 9338                                        s.select_ranges([range]);
 9339                                    },
 9340                                );
 9341                                pane.update(cx, |pane, _| pane.enable_history());
 9342                            });
 9343                        });
 9344                    }
 9345                    Navigated::Yes
 9346                })
 9347            })
 9348        } else if !definitions.is_empty() {
 9349            let replica_id = self.replica_id(cx);
 9350            cx.spawn(|editor, mut cx| async move {
 9351                let (title, location_tasks, workspace) = editor
 9352                    .update(&mut cx, |editor, cx| {
 9353                        let tab_kind = match kind {
 9354                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9355                            _ => "Definitions",
 9356                        };
 9357                        let title = definitions
 9358                            .iter()
 9359                            .find_map(|definition| match definition {
 9360                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9361                                    let buffer = origin.buffer.read(cx);
 9362                                    format!(
 9363                                        "{} for {}",
 9364                                        tab_kind,
 9365                                        buffer
 9366                                            .text_for_range(origin.range.clone())
 9367                                            .collect::<String>()
 9368                                    )
 9369                                }),
 9370                                HoverLink::InlayHint(_, _) => None,
 9371                                HoverLink::Url(_) => None,
 9372                                HoverLink::File(_) => None,
 9373                            })
 9374                            .unwrap_or(tab_kind.to_string());
 9375                        let location_tasks = definitions
 9376                            .into_iter()
 9377                            .map(|definition| match definition {
 9378                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9379                                HoverLink::InlayHint(lsp_location, server_id) => {
 9380                                    editor.compute_target_location(lsp_location, server_id, cx)
 9381                                }
 9382                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9383                                HoverLink::File(_) => Task::ready(Ok(None)),
 9384                            })
 9385                            .collect::<Vec<_>>();
 9386                        (title, location_tasks, editor.workspace().clone())
 9387                    })
 9388                    .context("location tasks preparation")?;
 9389
 9390                let locations = futures::future::join_all(location_tasks)
 9391                    .await
 9392                    .into_iter()
 9393                    .filter_map(|location| location.transpose())
 9394                    .collect::<Result<_>>()
 9395                    .context("location tasks")?;
 9396
 9397                let Some(workspace) = workspace else {
 9398                    return Ok(Navigated::No);
 9399                };
 9400                let opened = workspace
 9401                    .update(&mut cx, |workspace, cx| {
 9402                        Self::open_locations_in_multibuffer(
 9403                            workspace, locations, replica_id, title, split, cx,
 9404                        )
 9405                    })
 9406                    .ok();
 9407
 9408                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9409            })
 9410        } else {
 9411            Task::ready(Ok(Navigated::No))
 9412        }
 9413    }
 9414
 9415    fn compute_target_location(
 9416        &self,
 9417        lsp_location: lsp::Location,
 9418        server_id: LanguageServerId,
 9419        cx: &mut ViewContext<Editor>,
 9420    ) -> Task<anyhow::Result<Option<Location>>> {
 9421        let Some(project) = self.project.clone() else {
 9422            return Task::Ready(Some(Ok(None)));
 9423        };
 9424
 9425        cx.spawn(move |editor, mut cx| async move {
 9426            let location_task = editor.update(&mut cx, |editor, cx| {
 9427                project.update(cx, |project, cx| {
 9428                    let language_server_name =
 9429                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9430                            project
 9431                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9432                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9433                        });
 9434                    language_server_name.map(|language_server_name| {
 9435                        project.open_local_buffer_via_lsp(
 9436                            lsp_location.uri.clone(),
 9437                            server_id,
 9438                            language_server_name,
 9439                            cx,
 9440                        )
 9441                    })
 9442                })
 9443            })?;
 9444            let location = match location_task {
 9445                Some(task) => Some({
 9446                    let target_buffer_handle = task.await.context("open local buffer")?;
 9447                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9448                        let target_start = target_buffer
 9449                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9450                        let target_end = target_buffer
 9451                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9452                        target_buffer.anchor_after(target_start)
 9453                            ..target_buffer.anchor_before(target_end)
 9454                    })?;
 9455                    Location {
 9456                        buffer: target_buffer_handle,
 9457                        range,
 9458                    }
 9459                }),
 9460                None => None,
 9461            };
 9462            Ok(location)
 9463        })
 9464    }
 9465
 9466    pub fn find_all_references(
 9467        &mut self,
 9468        _: &FindAllReferences,
 9469        cx: &mut ViewContext<Self>,
 9470    ) -> Option<Task<Result<Navigated>>> {
 9471        let multi_buffer = self.buffer.read(cx);
 9472        let selection = self.selections.newest::<usize>(cx);
 9473        let head = selection.head();
 9474
 9475        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9476        let head_anchor = multi_buffer_snapshot.anchor_at(
 9477            head,
 9478            if head < selection.tail() {
 9479                Bias::Right
 9480            } else {
 9481                Bias::Left
 9482            },
 9483        );
 9484
 9485        match self
 9486            .find_all_references_task_sources
 9487            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9488        {
 9489            Ok(_) => {
 9490                log::info!(
 9491                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9492                );
 9493                return None;
 9494            }
 9495            Err(i) => {
 9496                self.find_all_references_task_sources.insert(i, head_anchor);
 9497            }
 9498        }
 9499
 9500        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9501        let replica_id = self.replica_id(cx);
 9502        let workspace = self.workspace()?;
 9503        let project = workspace.read(cx).project().clone();
 9504        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9505        Some(cx.spawn(|editor, mut cx| async move {
 9506            let _cleanup = defer({
 9507                let mut cx = cx.clone();
 9508                move || {
 9509                    let _ = editor.update(&mut cx, |editor, _| {
 9510                        if let Ok(i) =
 9511                            editor
 9512                                .find_all_references_task_sources
 9513                                .binary_search_by(|anchor| {
 9514                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9515                                })
 9516                        {
 9517                            editor.find_all_references_task_sources.remove(i);
 9518                        }
 9519                    });
 9520                }
 9521            });
 9522
 9523            let locations = references.await?;
 9524            if locations.is_empty() {
 9525                return anyhow::Ok(Navigated::No);
 9526            }
 9527
 9528            workspace.update(&mut cx, |workspace, cx| {
 9529                let title = locations
 9530                    .first()
 9531                    .as_ref()
 9532                    .map(|location| {
 9533                        let buffer = location.buffer.read(cx);
 9534                        format!(
 9535                            "References to `{}`",
 9536                            buffer
 9537                                .text_for_range(location.range.clone())
 9538                                .collect::<String>()
 9539                        )
 9540                    })
 9541                    .unwrap();
 9542                Self::open_locations_in_multibuffer(
 9543                    workspace, locations, replica_id, title, false, cx,
 9544                );
 9545                Navigated::Yes
 9546            })
 9547        }))
 9548    }
 9549
 9550    /// Opens a multibuffer with the given project locations in it
 9551    pub fn open_locations_in_multibuffer(
 9552        workspace: &mut Workspace,
 9553        mut locations: Vec<Location>,
 9554        replica_id: ReplicaId,
 9555        title: String,
 9556        split: bool,
 9557        cx: &mut ViewContext<Workspace>,
 9558    ) {
 9559        // If there are multiple definitions, open them in a multibuffer
 9560        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9561        let mut locations = locations.into_iter().peekable();
 9562        let mut ranges_to_highlight = Vec::new();
 9563        let capability = workspace.project().read(cx).capability();
 9564
 9565        let excerpt_buffer = cx.new_model(|cx| {
 9566            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 9567            while let Some(location) = locations.next() {
 9568                let buffer = location.buffer.read(cx);
 9569                let mut ranges_for_buffer = Vec::new();
 9570                let range = location.range.to_offset(buffer);
 9571                ranges_for_buffer.push(range.clone());
 9572
 9573                while let Some(next_location) = locations.peek() {
 9574                    if next_location.buffer == location.buffer {
 9575                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9576                        locations.next();
 9577                    } else {
 9578                        break;
 9579                    }
 9580                }
 9581
 9582                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9583                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9584                    location.buffer.clone(),
 9585                    ranges_for_buffer,
 9586                    DEFAULT_MULTIBUFFER_CONTEXT,
 9587                    cx,
 9588                ))
 9589            }
 9590
 9591            multibuffer.with_title(title)
 9592        });
 9593
 9594        let editor = cx.new_view(|cx| {
 9595            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9596        });
 9597        editor.update(cx, |editor, cx| {
 9598            if let Some(first_range) = ranges_to_highlight.first() {
 9599                editor.change_selections(None, cx, |selections| {
 9600                    selections.clear_disjoint();
 9601                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9602                });
 9603            }
 9604            editor.highlight_background::<Self>(
 9605                &ranges_to_highlight,
 9606                |theme| theme.editor_highlighted_line_background,
 9607                cx,
 9608            );
 9609        });
 9610
 9611        let item = Box::new(editor);
 9612        let item_id = item.item_id();
 9613
 9614        if split {
 9615            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9616        } else {
 9617            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9618                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9619                    pane.close_current_preview_item(cx)
 9620                } else {
 9621                    None
 9622                }
 9623            });
 9624            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9625        }
 9626        workspace.active_pane().update(cx, |pane, cx| {
 9627            pane.set_preview_item_id(Some(item_id), cx);
 9628        });
 9629    }
 9630
 9631    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9632        use language::ToOffset as _;
 9633
 9634        let project = self.project.clone()?;
 9635        let selection = self.selections.newest_anchor().clone();
 9636        let (cursor_buffer, cursor_buffer_position) = self
 9637            .buffer
 9638            .read(cx)
 9639            .text_anchor_for_position(selection.head(), cx)?;
 9640        let (tail_buffer, cursor_buffer_position_end) = self
 9641            .buffer
 9642            .read(cx)
 9643            .text_anchor_for_position(selection.tail(), cx)?;
 9644        if tail_buffer != cursor_buffer {
 9645            return None;
 9646        }
 9647
 9648        let snapshot = cursor_buffer.read(cx).snapshot();
 9649        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9650        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9651        let prepare_rename = project.update(cx, |project, cx| {
 9652            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 9653        });
 9654        drop(snapshot);
 9655
 9656        Some(cx.spawn(|this, mut cx| async move {
 9657            let rename_range = if let Some(range) = prepare_rename.await? {
 9658                Some(range)
 9659            } else {
 9660                this.update(&mut cx, |this, cx| {
 9661                    let buffer = this.buffer.read(cx).snapshot(cx);
 9662                    let mut buffer_highlights = this
 9663                        .document_highlights_for_position(selection.head(), &buffer)
 9664                        .filter(|highlight| {
 9665                            highlight.start.excerpt_id == selection.head().excerpt_id
 9666                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9667                        });
 9668                    buffer_highlights
 9669                        .next()
 9670                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9671                })?
 9672            };
 9673            if let Some(rename_range) = rename_range {
 9674                this.update(&mut cx, |this, cx| {
 9675                    let snapshot = cursor_buffer.read(cx).snapshot();
 9676                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9677                    let cursor_offset_in_rename_range =
 9678                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9679                    let cursor_offset_in_rename_range_end =
 9680                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9681
 9682                    this.take_rename(false, cx);
 9683                    let buffer = this.buffer.read(cx).read(cx);
 9684                    let cursor_offset = selection.head().to_offset(&buffer);
 9685                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9686                    let rename_end = rename_start + rename_buffer_range.len();
 9687                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9688                    let mut old_highlight_id = None;
 9689                    let old_name: Arc<str> = buffer
 9690                        .chunks(rename_start..rename_end, true)
 9691                        .map(|chunk| {
 9692                            if old_highlight_id.is_none() {
 9693                                old_highlight_id = chunk.syntax_highlight_id;
 9694                            }
 9695                            chunk.text
 9696                        })
 9697                        .collect::<String>()
 9698                        .into();
 9699
 9700                    drop(buffer);
 9701
 9702                    // Position the selection in the rename editor so that it matches the current selection.
 9703                    this.show_local_selections = false;
 9704                    let rename_editor = cx.new_view(|cx| {
 9705                        let mut editor = Editor::single_line(cx);
 9706                        editor.buffer.update(cx, |buffer, cx| {
 9707                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9708                        });
 9709                        let rename_selection_range = match cursor_offset_in_rename_range
 9710                            .cmp(&cursor_offset_in_rename_range_end)
 9711                        {
 9712                            Ordering::Equal => {
 9713                                editor.select_all(&SelectAll, cx);
 9714                                return editor;
 9715                            }
 9716                            Ordering::Less => {
 9717                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9718                            }
 9719                            Ordering::Greater => {
 9720                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9721                            }
 9722                        };
 9723                        if rename_selection_range.end > old_name.len() {
 9724                            editor.select_all(&SelectAll, cx);
 9725                        } else {
 9726                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9727                                s.select_ranges([rename_selection_range]);
 9728                            });
 9729                        }
 9730                        editor
 9731                    });
 9732                    cx.subscribe(&rename_editor, |_, _, e, cx| match e {
 9733                        EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
 9734                        _ => {}
 9735                    })
 9736                    .detach();
 9737
 9738                    let write_highlights =
 9739                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9740                    let read_highlights =
 9741                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9742                    let ranges = write_highlights
 9743                        .iter()
 9744                        .flat_map(|(_, ranges)| ranges.iter())
 9745                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9746                        .cloned()
 9747                        .collect();
 9748
 9749                    this.highlight_text::<Rename>(
 9750                        ranges,
 9751                        HighlightStyle {
 9752                            fade_out: Some(0.6),
 9753                            ..Default::default()
 9754                        },
 9755                        cx,
 9756                    );
 9757                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9758                    cx.focus(&rename_focus_handle);
 9759                    let block_id = this.insert_blocks(
 9760                        [BlockProperties {
 9761                            style: BlockStyle::Flex,
 9762                            position: range.start,
 9763                            height: 1,
 9764                            render: Box::new({
 9765                                let rename_editor = rename_editor.clone();
 9766                                move |cx: &mut BlockContext| {
 9767                                    let mut text_style = cx.editor_style.text.clone();
 9768                                    if let Some(highlight_style) = old_highlight_id
 9769                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9770                                    {
 9771                                        text_style = text_style.highlight(highlight_style);
 9772                                    }
 9773                                    div()
 9774                                        .pl(cx.anchor_x)
 9775                                        .child(EditorElement::new(
 9776                                            &rename_editor,
 9777                                            EditorStyle {
 9778                                                background: cx.theme().system().transparent,
 9779                                                local_player: cx.editor_style.local_player,
 9780                                                text: text_style,
 9781                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9782                                                syntax: cx.editor_style.syntax.clone(),
 9783                                                status: cx.editor_style.status.clone(),
 9784                                                inlay_hints_style: HighlightStyle {
 9785                                                    color: Some(cx.theme().status().hint),
 9786                                                    font_weight: Some(FontWeight::BOLD),
 9787                                                    ..HighlightStyle::default()
 9788                                                },
 9789                                                suggestions_style: HighlightStyle {
 9790                                                    color: Some(cx.theme().status().predictive),
 9791                                                    ..HighlightStyle::default()
 9792                                                },
 9793                                                ..EditorStyle::default()
 9794                                            },
 9795                                        ))
 9796                                        .into_any_element()
 9797                                }
 9798                            }),
 9799                            disposition: BlockDisposition::Below,
 9800                            priority: 0,
 9801                        }],
 9802                        Some(Autoscroll::fit()),
 9803                        cx,
 9804                    )[0];
 9805                    this.pending_rename = Some(RenameState {
 9806                        range,
 9807                        old_name,
 9808                        editor: rename_editor,
 9809                        block_id,
 9810                    });
 9811                })?;
 9812            }
 9813
 9814            Ok(())
 9815        }))
 9816    }
 9817
 9818    pub fn confirm_rename(
 9819        &mut self,
 9820        _: &ConfirmRename,
 9821        cx: &mut ViewContext<Self>,
 9822    ) -> Option<Task<Result<()>>> {
 9823        let rename = self.take_rename(false, cx)?;
 9824        let workspace = self.workspace()?;
 9825        let (start_buffer, start) = self
 9826            .buffer
 9827            .read(cx)
 9828            .text_anchor_for_position(rename.range.start, cx)?;
 9829        let (end_buffer, end) = self
 9830            .buffer
 9831            .read(cx)
 9832            .text_anchor_for_position(rename.range.end, cx)?;
 9833        if start_buffer != end_buffer {
 9834            return None;
 9835        }
 9836
 9837        let buffer = start_buffer;
 9838        let range = start..end;
 9839        let old_name = rename.old_name;
 9840        let new_name = rename.editor.read(cx).text(cx);
 9841
 9842        let rename = workspace
 9843            .read(cx)
 9844            .project()
 9845            .clone()
 9846            .update(cx, |project, cx| {
 9847                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 9848            });
 9849        let workspace = workspace.downgrade();
 9850
 9851        Some(cx.spawn(|editor, mut cx| async move {
 9852            let project_transaction = rename.await?;
 9853            Self::open_project_transaction(
 9854                &editor,
 9855                workspace,
 9856                project_transaction,
 9857                format!("Rename: {}{}", old_name, new_name),
 9858                cx.clone(),
 9859            )
 9860            .await?;
 9861
 9862            editor.update(&mut cx, |editor, cx| {
 9863                editor.refresh_document_highlights(cx);
 9864            })?;
 9865            Ok(())
 9866        }))
 9867    }
 9868
 9869    fn take_rename(
 9870        &mut self,
 9871        moving_cursor: bool,
 9872        cx: &mut ViewContext<Self>,
 9873    ) -> Option<RenameState> {
 9874        let rename = self.pending_rename.take()?;
 9875        if rename.editor.focus_handle(cx).is_focused(cx) {
 9876            cx.focus(&self.focus_handle);
 9877        }
 9878
 9879        self.remove_blocks(
 9880            [rename.block_id].into_iter().collect(),
 9881            Some(Autoscroll::fit()),
 9882            cx,
 9883        );
 9884        self.clear_highlights::<Rename>(cx);
 9885        self.show_local_selections = true;
 9886
 9887        if moving_cursor {
 9888            let rename_editor = rename.editor.read(cx);
 9889            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 9890
 9891            // Update the selection to match the position of the selection inside
 9892            // the rename editor.
 9893            let snapshot = self.buffer.read(cx).read(cx);
 9894            let rename_range = rename.range.to_offset(&snapshot);
 9895            let cursor_in_editor = snapshot
 9896                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9897                .min(rename_range.end);
 9898            drop(snapshot);
 9899
 9900            self.change_selections(None, cx, |s| {
 9901                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9902            });
 9903        } else {
 9904            self.refresh_document_highlights(cx);
 9905        }
 9906
 9907        Some(rename)
 9908    }
 9909
 9910    pub fn pending_rename(&self) -> Option<&RenameState> {
 9911        self.pending_rename.as_ref()
 9912    }
 9913
 9914    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9915        let project = match &self.project {
 9916            Some(project) => project.clone(),
 9917            None => return None,
 9918        };
 9919
 9920        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 9921    }
 9922
 9923    fn perform_format(
 9924        &mut self,
 9925        project: Model<Project>,
 9926        trigger: FormatTrigger,
 9927        cx: &mut ViewContext<Self>,
 9928    ) -> Task<Result<()>> {
 9929        let buffer = self.buffer().clone();
 9930        let mut buffers = buffer.read(cx).all_buffers();
 9931        if trigger == FormatTrigger::Save {
 9932            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 9933        }
 9934
 9935        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 9936        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 9937
 9938        cx.spawn(|_, mut cx| async move {
 9939            let transaction = futures::select_biased! {
 9940                () = timeout => {
 9941                    log::warn!("timed out waiting for formatting");
 9942                    None
 9943                }
 9944                transaction = format.log_err().fuse() => transaction,
 9945            };
 9946
 9947            buffer
 9948                .update(&mut cx, |buffer, cx| {
 9949                    if let Some(transaction) = transaction {
 9950                        if !buffer.is_singleton() {
 9951                            buffer.push_transaction(&transaction.0, cx);
 9952                        }
 9953                    }
 9954
 9955                    cx.notify();
 9956                })
 9957                .ok();
 9958
 9959            Ok(())
 9960        })
 9961    }
 9962
 9963    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 9964        if let Some(project) = self.project.clone() {
 9965            self.buffer.update(cx, |multi_buffer, cx| {
 9966                project.update(cx, |project, cx| {
 9967                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 9968                });
 9969            })
 9970        }
 9971    }
 9972
 9973    fn cancel_language_server_work(
 9974        &mut self,
 9975        _: &CancelLanguageServerWork,
 9976        cx: &mut ViewContext<Self>,
 9977    ) {
 9978        if let Some(project) = self.project.clone() {
 9979            self.buffer.update(cx, |multi_buffer, cx| {
 9980                project.update(cx, |project, cx| {
 9981                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
 9982                });
 9983            })
 9984        }
 9985    }
 9986
 9987    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 9988        cx.show_character_palette();
 9989    }
 9990
 9991    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 9992        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 9993            let buffer = self.buffer.read(cx).snapshot(cx);
 9994            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 9995            let is_valid = buffer
 9996                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 9997                .any(|entry| {
 9998                    entry.diagnostic.is_primary
 9999                        && !entry.range.is_empty()
10000                        && entry.range.start == primary_range_start
10001                        && entry.diagnostic.message == active_diagnostics.primary_message
10002                });
10003
10004            if is_valid != active_diagnostics.is_valid {
10005                active_diagnostics.is_valid = is_valid;
10006                let mut new_styles = HashMap::default();
10007                for (block_id, diagnostic) in &active_diagnostics.blocks {
10008                    new_styles.insert(
10009                        *block_id,
10010                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10011                    );
10012                }
10013                self.display_map.update(cx, |display_map, _cx| {
10014                    display_map.replace_blocks(new_styles)
10015                });
10016            }
10017        }
10018    }
10019
10020    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10021        self.dismiss_diagnostics(cx);
10022        let snapshot = self.snapshot(cx);
10023        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10024            let buffer = self.buffer.read(cx).snapshot(cx);
10025
10026            let mut primary_range = None;
10027            let mut primary_message = None;
10028            let mut group_end = Point::zero();
10029            let diagnostic_group = buffer
10030                .diagnostic_group::<MultiBufferPoint>(group_id)
10031                .filter_map(|entry| {
10032                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10033                        && (entry.range.start.row == entry.range.end.row
10034                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10035                    {
10036                        return None;
10037                    }
10038                    if entry.range.end > group_end {
10039                        group_end = entry.range.end;
10040                    }
10041                    if entry.diagnostic.is_primary {
10042                        primary_range = Some(entry.range.clone());
10043                        primary_message = Some(entry.diagnostic.message.clone());
10044                    }
10045                    Some(entry)
10046                })
10047                .collect::<Vec<_>>();
10048            let primary_range = primary_range?;
10049            let primary_message = primary_message?;
10050            let primary_range =
10051                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10052
10053            let blocks = display_map
10054                .insert_blocks(
10055                    diagnostic_group.iter().map(|entry| {
10056                        let diagnostic = entry.diagnostic.clone();
10057                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10058                        BlockProperties {
10059                            style: BlockStyle::Fixed,
10060                            position: buffer.anchor_after(entry.range.start),
10061                            height: message_height,
10062                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10063                            disposition: BlockDisposition::Below,
10064                            priority: 0,
10065                        }
10066                    }),
10067                    cx,
10068                )
10069                .into_iter()
10070                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10071                .collect();
10072
10073            Some(ActiveDiagnosticGroup {
10074                primary_range,
10075                primary_message,
10076                group_id,
10077                blocks,
10078                is_valid: true,
10079            })
10080        });
10081        self.active_diagnostics.is_some()
10082    }
10083
10084    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10085        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10086            self.display_map.update(cx, |display_map, cx| {
10087                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10088            });
10089            cx.notify();
10090        }
10091    }
10092
10093    pub fn set_selections_from_remote(
10094        &mut self,
10095        selections: Vec<Selection<Anchor>>,
10096        pending_selection: Option<Selection<Anchor>>,
10097        cx: &mut ViewContext<Self>,
10098    ) {
10099        let old_cursor_position = self.selections.newest_anchor().head();
10100        self.selections.change_with(cx, |s| {
10101            s.select_anchors(selections);
10102            if let Some(pending_selection) = pending_selection {
10103                s.set_pending(pending_selection, SelectMode::Character);
10104            } else {
10105                s.clear_pending();
10106            }
10107        });
10108        self.selections_did_change(false, &old_cursor_position, true, cx);
10109    }
10110
10111    fn push_to_selection_history(&mut self) {
10112        self.selection_history.push(SelectionHistoryEntry {
10113            selections: self.selections.disjoint_anchors(),
10114            select_next_state: self.select_next_state.clone(),
10115            select_prev_state: self.select_prev_state.clone(),
10116            add_selections_state: self.add_selections_state.clone(),
10117        });
10118    }
10119
10120    pub fn transact(
10121        &mut self,
10122        cx: &mut ViewContext<Self>,
10123        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10124    ) -> Option<TransactionId> {
10125        self.start_transaction_at(Instant::now(), cx);
10126        update(self, cx);
10127        self.end_transaction_at(Instant::now(), cx)
10128    }
10129
10130    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10131        self.end_selection(cx);
10132        if let Some(tx_id) = self
10133            .buffer
10134            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10135        {
10136            self.selection_history
10137                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10138            cx.emit(EditorEvent::TransactionBegun {
10139                transaction_id: tx_id,
10140            })
10141        }
10142    }
10143
10144    fn end_transaction_at(
10145        &mut self,
10146        now: Instant,
10147        cx: &mut ViewContext<Self>,
10148    ) -> Option<TransactionId> {
10149        if let Some(transaction_id) = self
10150            .buffer
10151            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10152        {
10153            if let Some((_, end_selections)) =
10154                self.selection_history.transaction_mut(transaction_id)
10155            {
10156                *end_selections = Some(self.selections.disjoint_anchors());
10157            } else {
10158                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10159            }
10160
10161            cx.emit(EditorEvent::Edited { transaction_id });
10162            Some(transaction_id)
10163        } else {
10164            None
10165        }
10166    }
10167
10168    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10169        let mut fold_ranges = Vec::new();
10170
10171        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10172
10173        let selections = self.selections.all_adjusted(cx);
10174        for selection in selections {
10175            let range = selection.range().sorted();
10176            let buffer_start_row = range.start.row;
10177
10178            for row in (0..=range.end.row).rev() {
10179                if let Some((foldable_range, fold_text)) =
10180                    display_map.foldable_range(MultiBufferRow(row))
10181                {
10182                    if foldable_range.end.row >= buffer_start_row {
10183                        fold_ranges.push((foldable_range, fold_text));
10184                        if row <= range.start.row {
10185                            break;
10186                        }
10187                    }
10188                }
10189            }
10190        }
10191
10192        self.fold_ranges(fold_ranges, true, cx);
10193    }
10194
10195    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10196        let buffer_row = fold_at.buffer_row;
10197        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10198
10199        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10200            let autoscroll = self
10201                .selections
10202                .all::<Point>(cx)
10203                .iter()
10204                .any(|selection| fold_range.overlaps(&selection.range()));
10205
10206            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10207        }
10208    }
10209
10210    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10211        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10212        let buffer = &display_map.buffer_snapshot;
10213        let selections = self.selections.all::<Point>(cx);
10214        let ranges = selections
10215            .iter()
10216            .map(|s| {
10217                let range = s.display_range(&display_map).sorted();
10218                let mut start = range.start.to_point(&display_map);
10219                let mut end = range.end.to_point(&display_map);
10220                start.column = 0;
10221                end.column = buffer.line_len(MultiBufferRow(end.row));
10222                start..end
10223            })
10224            .collect::<Vec<_>>();
10225
10226        self.unfold_ranges(ranges, true, true, cx);
10227    }
10228
10229    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10230        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10231
10232        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10233            ..Point::new(
10234                unfold_at.buffer_row.0,
10235                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10236            );
10237
10238        let autoscroll = self
10239            .selections
10240            .all::<Point>(cx)
10241            .iter()
10242            .any(|selection| selection.range().overlaps(&intersection_range));
10243
10244        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10245    }
10246
10247    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10248        let selections = self.selections.all::<Point>(cx);
10249        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10250        let line_mode = self.selections.line_mode;
10251        let ranges = selections.into_iter().map(|s| {
10252            if line_mode {
10253                let start = Point::new(s.start.row, 0);
10254                let end = Point::new(
10255                    s.end.row,
10256                    display_map
10257                        .buffer_snapshot
10258                        .line_len(MultiBufferRow(s.end.row)),
10259                );
10260                (start..end, display_map.fold_placeholder.clone())
10261            } else {
10262                (s.start..s.end, display_map.fold_placeholder.clone())
10263            }
10264        });
10265        self.fold_ranges(ranges, true, cx);
10266    }
10267
10268    pub fn fold_ranges<T: ToOffset + Clone>(
10269        &mut self,
10270        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10271        auto_scroll: bool,
10272        cx: &mut ViewContext<Self>,
10273    ) {
10274        let mut fold_ranges = Vec::new();
10275        let mut buffers_affected = HashMap::default();
10276        let multi_buffer = self.buffer().read(cx);
10277        for (fold_range, fold_text) in ranges {
10278            if let Some((_, buffer, _)) =
10279                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10280            {
10281                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10282            };
10283            fold_ranges.push((fold_range, fold_text));
10284        }
10285
10286        let mut ranges = fold_ranges.into_iter().peekable();
10287        if ranges.peek().is_some() {
10288            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10289
10290            if auto_scroll {
10291                self.request_autoscroll(Autoscroll::fit(), cx);
10292            }
10293
10294            for buffer in buffers_affected.into_values() {
10295                self.sync_expanded_diff_hunks(buffer, cx);
10296            }
10297
10298            cx.notify();
10299
10300            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10301                // Clear diagnostics block when folding a range that contains it.
10302                let snapshot = self.snapshot(cx);
10303                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10304                    drop(snapshot);
10305                    self.active_diagnostics = Some(active_diagnostics);
10306                    self.dismiss_diagnostics(cx);
10307                } else {
10308                    self.active_diagnostics = Some(active_diagnostics);
10309                }
10310            }
10311
10312            self.scrollbar_marker_state.dirty = true;
10313        }
10314    }
10315
10316    pub fn unfold_ranges<T: ToOffset + Clone>(
10317        &mut self,
10318        ranges: impl IntoIterator<Item = Range<T>>,
10319        inclusive: bool,
10320        auto_scroll: bool,
10321        cx: &mut ViewContext<Self>,
10322    ) {
10323        let mut unfold_ranges = Vec::new();
10324        let mut buffers_affected = HashMap::default();
10325        let multi_buffer = self.buffer().read(cx);
10326        for range in ranges {
10327            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10328                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10329            };
10330            unfold_ranges.push(range);
10331        }
10332
10333        let mut ranges = unfold_ranges.into_iter().peekable();
10334        if ranges.peek().is_some() {
10335            self.display_map
10336                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10337            if auto_scroll {
10338                self.request_autoscroll(Autoscroll::fit(), cx);
10339            }
10340
10341            for buffer in buffers_affected.into_values() {
10342                self.sync_expanded_diff_hunks(buffer, cx);
10343            }
10344
10345            cx.notify();
10346            self.scrollbar_marker_state.dirty = true;
10347            self.active_indent_guides_state.dirty = true;
10348        }
10349    }
10350
10351    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10352        if hovered != self.gutter_hovered {
10353            self.gutter_hovered = hovered;
10354            cx.notify();
10355        }
10356    }
10357
10358    pub fn insert_blocks(
10359        &mut self,
10360        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10361        autoscroll: Option<Autoscroll>,
10362        cx: &mut ViewContext<Self>,
10363    ) -> Vec<CustomBlockId> {
10364        let blocks = self
10365            .display_map
10366            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10367        if let Some(autoscroll) = autoscroll {
10368            self.request_autoscroll(autoscroll, cx);
10369        }
10370        cx.notify();
10371        blocks
10372    }
10373
10374    pub fn resize_blocks(
10375        &mut self,
10376        heights: HashMap<CustomBlockId, u32>,
10377        autoscroll: Option<Autoscroll>,
10378        cx: &mut ViewContext<Self>,
10379    ) {
10380        self.display_map
10381            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10382        if let Some(autoscroll) = autoscroll {
10383            self.request_autoscroll(autoscroll, cx);
10384        }
10385        cx.notify();
10386    }
10387
10388    pub fn replace_blocks(
10389        &mut self,
10390        renderers: HashMap<CustomBlockId, RenderBlock>,
10391        autoscroll: Option<Autoscroll>,
10392        cx: &mut ViewContext<Self>,
10393    ) {
10394        self.display_map
10395            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10396        if let Some(autoscroll) = autoscroll {
10397            self.request_autoscroll(autoscroll, cx);
10398        }
10399        cx.notify();
10400    }
10401
10402    pub fn remove_blocks(
10403        &mut self,
10404        block_ids: HashSet<CustomBlockId>,
10405        autoscroll: Option<Autoscroll>,
10406        cx: &mut ViewContext<Self>,
10407    ) {
10408        self.display_map.update(cx, |display_map, cx| {
10409            display_map.remove_blocks(block_ids, cx)
10410        });
10411        if let Some(autoscroll) = autoscroll {
10412            self.request_autoscroll(autoscroll, cx);
10413        }
10414        cx.notify();
10415    }
10416
10417    pub fn row_for_block(
10418        &self,
10419        block_id: CustomBlockId,
10420        cx: &mut ViewContext<Self>,
10421    ) -> Option<DisplayRow> {
10422        self.display_map
10423            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10424    }
10425
10426    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10427        self.focused_block = Some(focused_block);
10428    }
10429
10430    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10431        self.focused_block.take()
10432    }
10433
10434    pub fn insert_creases(
10435        &mut self,
10436        creases: impl IntoIterator<Item = Crease>,
10437        cx: &mut ViewContext<Self>,
10438    ) -> Vec<CreaseId> {
10439        self.display_map
10440            .update(cx, |map, cx| map.insert_creases(creases, cx))
10441    }
10442
10443    pub fn remove_creases(
10444        &mut self,
10445        ids: impl IntoIterator<Item = CreaseId>,
10446        cx: &mut ViewContext<Self>,
10447    ) {
10448        self.display_map
10449            .update(cx, |map, cx| map.remove_creases(ids, cx));
10450    }
10451
10452    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10453        self.display_map
10454            .update(cx, |map, cx| map.snapshot(cx))
10455            .longest_row()
10456    }
10457
10458    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10459        self.display_map
10460            .update(cx, |map, cx| map.snapshot(cx))
10461            .max_point()
10462    }
10463
10464    pub fn text(&self, cx: &AppContext) -> String {
10465        self.buffer.read(cx).read(cx).text()
10466    }
10467
10468    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10469        let text = self.text(cx);
10470        let text = text.trim();
10471
10472        if text.is_empty() {
10473            return None;
10474        }
10475
10476        Some(text.to_string())
10477    }
10478
10479    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10480        self.transact(cx, |this, cx| {
10481            this.buffer
10482                .read(cx)
10483                .as_singleton()
10484                .expect("you can only call set_text on editors for singleton buffers")
10485                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10486        });
10487    }
10488
10489    pub fn display_text(&self, cx: &mut AppContext) -> String {
10490        self.display_map
10491            .update(cx, |map, cx| map.snapshot(cx))
10492            .text()
10493    }
10494
10495    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10496        let mut wrap_guides = smallvec::smallvec![];
10497
10498        if self.show_wrap_guides == Some(false) {
10499            return wrap_guides;
10500        }
10501
10502        let settings = self.buffer.read(cx).settings_at(0, cx);
10503        if settings.show_wrap_guides {
10504            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10505                wrap_guides.push((soft_wrap as usize, true));
10506            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10507                wrap_guides.push((soft_wrap as usize, true));
10508            }
10509            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10510        }
10511
10512        wrap_guides
10513    }
10514
10515    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10516        let settings = self.buffer.read(cx).settings_at(0, cx);
10517        let mode = self
10518            .soft_wrap_mode_override
10519            .unwrap_or_else(|| settings.soft_wrap);
10520        match mode {
10521            language_settings::SoftWrap::None => SoftWrap::None,
10522            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10523            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10524            language_settings::SoftWrap::PreferredLineLength => {
10525                SoftWrap::Column(settings.preferred_line_length)
10526            }
10527            language_settings::SoftWrap::Bounded => {
10528                SoftWrap::Bounded(settings.preferred_line_length)
10529            }
10530        }
10531    }
10532
10533    pub fn set_soft_wrap_mode(
10534        &mut self,
10535        mode: language_settings::SoftWrap,
10536        cx: &mut ViewContext<Self>,
10537    ) {
10538        self.soft_wrap_mode_override = Some(mode);
10539        cx.notify();
10540    }
10541
10542    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10543        let rem_size = cx.rem_size();
10544        self.display_map.update(cx, |map, cx| {
10545            map.set_font(
10546                style.text.font(),
10547                style.text.font_size.to_pixels(rem_size),
10548                cx,
10549            )
10550        });
10551        self.style = Some(style);
10552    }
10553
10554    pub fn style(&self) -> Option<&EditorStyle> {
10555        self.style.as_ref()
10556    }
10557
10558    // Called by the element. This method is not designed to be called outside of the editor
10559    // element's layout code because it does not notify when rewrapping is computed synchronously.
10560    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10561        self.display_map
10562            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10563    }
10564
10565    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10566        if self.soft_wrap_mode_override.is_some() {
10567            self.soft_wrap_mode_override.take();
10568        } else {
10569            let soft_wrap = match self.soft_wrap_mode(cx) {
10570                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10571                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10572                    language_settings::SoftWrap::PreferLine
10573                }
10574            };
10575            self.soft_wrap_mode_override = Some(soft_wrap);
10576        }
10577        cx.notify();
10578    }
10579
10580    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10581        let Some(workspace) = self.workspace() else {
10582            return;
10583        };
10584        let fs = workspace.read(cx).app_state().fs.clone();
10585        let current_show = TabBarSettings::get_global(cx).show;
10586        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10587            setting.show = Some(!current_show);
10588        });
10589    }
10590
10591    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10592        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10593            self.buffer
10594                .read(cx)
10595                .settings_at(0, cx)
10596                .indent_guides
10597                .enabled
10598        });
10599        self.show_indent_guides = Some(!currently_enabled);
10600        cx.notify();
10601    }
10602
10603    fn should_show_indent_guides(&self) -> Option<bool> {
10604        self.show_indent_guides
10605    }
10606
10607    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10608        let mut editor_settings = EditorSettings::get_global(cx).clone();
10609        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10610        EditorSettings::override_global(editor_settings, cx);
10611    }
10612
10613    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10614        self.show_gutter = show_gutter;
10615        cx.notify();
10616    }
10617
10618    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10619        self.show_line_numbers = Some(show_line_numbers);
10620        cx.notify();
10621    }
10622
10623    pub fn set_show_git_diff_gutter(
10624        &mut self,
10625        show_git_diff_gutter: bool,
10626        cx: &mut ViewContext<Self>,
10627    ) {
10628        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10629        cx.notify();
10630    }
10631
10632    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10633        self.show_code_actions = Some(show_code_actions);
10634        cx.notify();
10635    }
10636
10637    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10638        self.show_runnables = Some(show_runnables);
10639        cx.notify();
10640    }
10641
10642    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10643        if self.display_map.read(cx).masked != masked {
10644            self.display_map.update(cx, |map, _| map.masked = masked);
10645        }
10646        cx.notify()
10647    }
10648
10649    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10650        self.show_wrap_guides = Some(show_wrap_guides);
10651        cx.notify();
10652    }
10653
10654    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10655        self.show_indent_guides = Some(show_indent_guides);
10656        cx.notify();
10657    }
10658
10659    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10660        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10661            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10662                if let Some(dir) = file.abs_path(cx).parent() {
10663                    return Some(dir.to_owned());
10664                }
10665            }
10666
10667            if let Some(project_path) = buffer.read(cx).project_path(cx) {
10668                return Some(project_path.path.to_path_buf());
10669            }
10670        }
10671
10672        None
10673    }
10674
10675    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10676        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10677            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10678                cx.reveal_path(&file.abs_path(cx));
10679            }
10680        }
10681    }
10682
10683    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10684        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10685            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10686                if let Some(path) = file.abs_path(cx).to_str() {
10687                    cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10688                }
10689            }
10690        }
10691    }
10692
10693    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10694        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10695            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10696                if let Some(path) = file.path().to_str() {
10697                    cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10698                }
10699            }
10700        }
10701    }
10702
10703    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10704        self.show_git_blame_gutter = !self.show_git_blame_gutter;
10705
10706        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10707            self.start_git_blame(true, cx);
10708        }
10709
10710        cx.notify();
10711    }
10712
10713    pub fn toggle_git_blame_inline(
10714        &mut self,
10715        _: &ToggleGitBlameInline,
10716        cx: &mut ViewContext<Self>,
10717    ) {
10718        self.toggle_git_blame_inline_internal(true, cx);
10719        cx.notify();
10720    }
10721
10722    pub fn git_blame_inline_enabled(&self) -> bool {
10723        self.git_blame_inline_enabled
10724    }
10725
10726    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10727        self.show_selection_menu = self
10728            .show_selection_menu
10729            .map(|show_selections_menu| !show_selections_menu)
10730            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10731
10732        cx.notify();
10733    }
10734
10735    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10736        self.show_selection_menu
10737            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10738    }
10739
10740    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10741        if let Some(project) = self.project.as_ref() {
10742            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10743                return;
10744            };
10745
10746            if buffer.read(cx).file().is_none() {
10747                return;
10748            }
10749
10750            let focused = self.focus_handle(cx).contains_focused(cx);
10751
10752            let project = project.clone();
10753            let blame =
10754                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10755            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10756            self.blame = Some(blame);
10757        }
10758    }
10759
10760    fn toggle_git_blame_inline_internal(
10761        &mut self,
10762        user_triggered: bool,
10763        cx: &mut ViewContext<Self>,
10764    ) {
10765        if self.git_blame_inline_enabled {
10766            self.git_blame_inline_enabled = false;
10767            self.show_git_blame_inline = false;
10768            self.show_git_blame_inline_delay_task.take();
10769        } else {
10770            self.git_blame_inline_enabled = true;
10771            self.start_git_blame_inline(user_triggered, cx);
10772        }
10773
10774        cx.notify();
10775    }
10776
10777    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10778        self.start_git_blame(user_triggered, cx);
10779
10780        if ProjectSettings::get_global(cx)
10781            .git
10782            .inline_blame_delay()
10783            .is_some()
10784        {
10785            self.start_inline_blame_timer(cx);
10786        } else {
10787            self.show_git_blame_inline = true
10788        }
10789    }
10790
10791    pub fn blame(&self) -> Option<&Model<GitBlame>> {
10792        self.blame.as_ref()
10793    }
10794
10795    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10796        self.show_git_blame_gutter && self.has_blame_entries(cx)
10797    }
10798
10799    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10800        self.show_git_blame_inline
10801            && self.focus_handle.is_focused(cx)
10802            && !self.newest_selection_head_on_empty_line(cx)
10803            && self.has_blame_entries(cx)
10804    }
10805
10806    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10807        self.blame()
10808            .map_or(false, |blame| blame.read(cx).has_generated_entries())
10809    }
10810
10811    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10812        let cursor_anchor = self.selections.newest_anchor().head();
10813
10814        let snapshot = self.buffer.read(cx).snapshot(cx);
10815        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10816
10817        snapshot.line_len(buffer_row) == 0
10818    }
10819
10820    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10821        let (path, selection, repo) = maybe!({
10822            let project_handle = self.project.as_ref()?.clone();
10823            let project = project_handle.read(cx);
10824
10825            let selection = self.selections.newest::<Point>(cx);
10826            let selection_range = selection.range();
10827
10828            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10829                (buffer, selection_range.start.row..selection_range.end.row)
10830            } else {
10831                let buffer_ranges = self
10832                    .buffer()
10833                    .read(cx)
10834                    .range_to_buffer_ranges(selection_range, cx);
10835
10836                let (buffer, range, _) = if selection.reversed {
10837                    buffer_ranges.first()
10838                } else {
10839                    buffer_ranges.last()
10840                }?;
10841
10842                let snapshot = buffer.read(cx).snapshot();
10843                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10844                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
10845                (buffer.clone(), selection)
10846            };
10847
10848            let path = buffer
10849                .read(cx)
10850                .file()?
10851                .as_local()?
10852                .path()
10853                .to_str()?
10854                .to_string();
10855            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10856            Some((path, selection, repo))
10857        })
10858        .ok_or_else(|| anyhow!("unable to open git repository"))?;
10859
10860        const REMOTE_NAME: &str = "origin";
10861        let origin_url = repo
10862            .remote_url(REMOTE_NAME)
10863            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10864        let sha = repo
10865            .head_sha()
10866            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10867
10868        let (provider, remote) =
10869            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10870                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10871
10872        Ok(provider.build_permalink(
10873            remote,
10874            BuildPermalinkParams {
10875                sha: &sha,
10876                path: &path,
10877                selection: Some(selection),
10878            },
10879        ))
10880    }
10881
10882    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10883        let permalink = self.get_permalink_to_line(cx);
10884
10885        match permalink {
10886            Ok(permalink) => {
10887                cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10888            }
10889            Err(err) => {
10890                let message = format!("Failed to copy permalink: {err}");
10891
10892                Err::<(), anyhow::Error>(err).log_err();
10893
10894                if let Some(workspace) = self.workspace() {
10895                    workspace.update(cx, |workspace, cx| {
10896                        struct CopyPermalinkToLine;
10897
10898                        workspace.show_toast(
10899                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10900                            cx,
10901                        )
10902                    })
10903                }
10904            }
10905        }
10906    }
10907
10908    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10909        let permalink = self.get_permalink_to_line(cx);
10910
10911        match permalink {
10912            Ok(permalink) => {
10913                cx.open_url(permalink.as_ref());
10914            }
10915            Err(err) => {
10916                let message = format!("Failed to open permalink: {err}");
10917
10918                Err::<(), anyhow::Error>(err).log_err();
10919
10920                if let Some(workspace) = self.workspace() {
10921                    workspace.update(cx, |workspace, cx| {
10922                        struct OpenPermalinkToLine;
10923
10924                        workspace.show_toast(
10925                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10926                            cx,
10927                        )
10928                    })
10929                }
10930            }
10931        }
10932    }
10933
10934    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10935    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10936    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10937    pub fn highlight_rows<T: 'static>(
10938        &mut self,
10939        rows: RangeInclusive<Anchor>,
10940        color: Option<Hsla>,
10941        should_autoscroll: bool,
10942        cx: &mut ViewContext<Self>,
10943    ) {
10944        let snapshot = self.buffer().read(cx).snapshot(cx);
10945        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10946        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10947            highlight
10948                .range
10949                .start()
10950                .cmp(&rows.start(), &snapshot)
10951                .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10952        });
10953        match (color, existing_highlight_index) {
10954            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10955                ix,
10956                RowHighlight {
10957                    index: post_inc(&mut self.highlight_order),
10958                    range: rows,
10959                    should_autoscroll,
10960                    color,
10961                },
10962            ),
10963            (None, Ok(i)) => {
10964                row_highlights.remove(i);
10965            }
10966        }
10967    }
10968
10969    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10970    pub fn clear_row_highlights<T: 'static>(&mut self) {
10971        self.highlighted_rows.remove(&TypeId::of::<T>());
10972    }
10973
10974    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10975    pub fn highlighted_rows<T: 'static>(
10976        &self,
10977    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10978        Some(
10979            self.highlighted_rows
10980                .get(&TypeId::of::<T>())?
10981                .iter()
10982                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10983        )
10984    }
10985
10986    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10987    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10988    /// Allows to ignore certain kinds of highlights.
10989    pub fn highlighted_display_rows(
10990        &mut self,
10991        cx: &mut WindowContext,
10992    ) -> BTreeMap<DisplayRow, Hsla> {
10993        let snapshot = self.snapshot(cx);
10994        let mut used_highlight_orders = HashMap::default();
10995        self.highlighted_rows
10996            .iter()
10997            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10998            .fold(
10999                BTreeMap::<DisplayRow, Hsla>::new(),
11000                |mut unique_rows, highlight| {
11001                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
11002                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
11003                    for row in start_row.0..=end_row.0 {
11004                        let used_index =
11005                            used_highlight_orders.entry(row).or_insert(highlight.index);
11006                        if highlight.index >= *used_index {
11007                            *used_index = highlight.index;
11008                            match highlight.color {
11009                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11010                                None => unique_rows.remove(&DisplayRow(row)),
11011                            };
11012                        }
11013                    }
11014                    unique_rows
11015                },
11016            )
11017    }
11018
11019    pub fn highlighted_display_row_for_autoscroll(
11020        &self,
11021        snapshot: &DisplaySnapshot,
11022    ) -> Option<DisplayRow> {
11023        self.highlighted_rows
11024            .values()
11025            .flat_map(|highlighted_rows| highlighted_rows.iter())
11026            .filter_map(|highlight| {
11027                if highlight.color.is_none() || !highlight.should_autoscroll {
11028                    return None;
11029                }
11030                Some(highlight.range.start().to_display_point(&snapshot).row())
11031            })
11032            .min()
11033    }
11034
11035    pub fn set_search_within_ranges(
11036        &mut self,
11037        ranges: &[Range<Anchor>],
11038        cx: &mut ViewContext<Self>,
11039    ) {
11040        self.highlight_background::<SearchWithinRange>(
11041            ranges,
11042            |colors| colors.editor_document_highlight_read_background,
11043            cx,
11044        )
11045    }
11046
11047    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11048        self.breadcrumb_header = Some(new_header);
11049    }
11050
11051    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11052        self.clear_background_highlights::<SearchWithinRange>(cx);
11053    }
11054
11055    pub fn highlight_background<T: 'static>(
11056        &mut self,
11057        ranges: &[Range<Anchor>],
11058        color_fetcher: fn(&ThemeColors) -> Hsla,
11059        cx: &mut ViewContext<Self>,
11060    ) {
11061        self.background_highlights
11062            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11063        self.scrollbar_marker_state.dirty = true;
11064        cx.notify();
11065    }
11066
11067    pub fn clear_background_highlights<T: 'static>(
11068        &mut self,
11069        cx: &mut ViewContext<Self>,
11070    ) -> Option<BackgroundHighlight> {
11071        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11072        if !text_highlights.1.is_empty() {
11073            self.scrollbar_marker_state.dirty = true;
11074            cx.notify();
11075        }
11076        Some(text_highlights)
11077    }
11078
11079    pub fn highlight_gutter<T: 'static>(
11080        &mut self,
11081        ranges: &[Range<Anchor>],
11082        color_fetcher: fn(&AppContext) -> Hsla,
11083        cx: &mut ViewContext<Self>,
11084    ) {
11085        self.gutter_highlights
11086            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11087        cx.notify();
11088    }
11089
11090    pub fn clear_gutter_highlights<T: 'static>(
11091        &mut self,
11092        cx: &mut ViewContext<Self>,
11093    ) -> Option<GutterHighlight> {
11094        cx.notify();
11095        self.gutter_highlights.remove(&TypeId::of::<T>())
11096    }
11097
11098    #[cfg(feature = "test-support")]
11099    pub fn all_text_background_highlights(
11100        &mut self,
11101        cx: &mut ViewContext<Self>,
11102    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11103        let snapshot = self.snapshot(cx);
11104        let buffer = &snapshot.buffer_snapshot;
11105        let start = buffer.anchor_before(0);
11106        let end = buffer.anchor_after(buffer.len());
11107        let theme = cx.theme().colors();
11108        self.background_highlights_in_range(start..end, &snapshot, theme)
11109    }
11110
11111    #[cfg(feature = "test-support")]
11112    pub fn search_background_highlights(
11113        &mut self,
11114        cx: &mut ViewContext<Self>,
11115    ) -> Vec<Range<Point>> {
11116        let snapshot = self.buffer().read(cx).snapshot(cx);
11117
11118        let highlights = self
11119            .background_highlights
11120            .get(&TypeId::of::<items::BufferSearchHighlights>());
11121
11122        if let Some((_color, ranges)) = highlights {
11123            ranges
11124                .iter()
11125                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11126                .collect_vec()
11127        } else {
11128            vec![]
11129        }
11130    }
11131
11132    fn document_highlights_for_position<'a>(
11133        &'a self,
11134        position: Anchor,
11135        buffer: &'a MultiBufferSnapshot,
11136    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11137        let read_highlights = self
11138            .background_highlights
11139            .get(&TypeId::of::<DocumentHighlightRead>())
11140            .map(|h| &h.1);
11141        let write_highlights = self
11142            .background_highlights
11143            .get(&TypeId::of::<DocumentHighlightWrite>())
11144            .map(|h| &h.1);
11145        let left_position = position.bias_left(buffer);
11146        let right_position = position.bias_right(buffer);
11147        read_highlights
11148            .into_iter()
11149            .chain(write_highlights)
11150            .flat_map(move |ranges| {
11151                let start_ix = match ranges.binary_search_by(|probe| {
11152                    let cmp = probe.end.cmp(&left_position, buffer);
11153                    if cmp.is_ge() {
11154                        Ordering::Greater
11155                    } else {
11156                        Ordering::Less
11157                    }
11158                }) {
11159                    Ok(i) | Err(i) => i,
11160                };
11161
11162                ranges[start_ix..]
11163                    .iter()
11164                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11165            })
11166    }
11167
11168    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11169        self.background_highlights
11170            .get(&TypeId::of::<T>())
11171            .map_or(false, |(_, highlights)| !highlights.is_empty())
11172    }
11173
11174    pub fn background_highlights_in_range(
11175        &self,
11176        search_range: Range<Anchor>,
11177        display_snapshot: &DisplaySnapshot,
11178        theme: &ThemeColors,
11179    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11180        let mut results = Vec::new();
11181        for (color_fetcher, ranges) in self.background_highlights.values() {
11182            let color = color_fetcher(theme);
11183            let start_ix = match ranges.binary_search_by(|probe| {
11184                let cmp = probe
11185                    .end
11186                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11187                if cmp.is_gt() {
11188                    Ordering::Greater
11189                } else {
11190                    Ordering::Less
11191                }
11192            }) {
11193                Ok(i) | Err(i) => i,
11194            };
11195            for range in &ranges[start_ix..] {
11196                if range
11197                    .start
11198                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11199                    .is_ge()
11200                {
11201                    break;
11202                }
11203
11204                let start = range.start.to_display_point(&display_snapshot);
11205                let end = range.end.to_display_point(&display_snapshot);
11206                results.push((start..end, color))
11207            }
11208        }
11209        results
11210    }
11211
11212    pub fn background_highlight_row_ranges<T: 'static>(
11213        &self,
11214        search_range: Range<Anchor>,
11215        display_snapshot: &DisplaySnapshot,
11216        count: usize,
11217    ) -> Vec<RangeInclusive<DisplayPoint>> {
11218        let mut results = Vec::new();
11219        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11220            return vec![];
11221        };
11222
11223        let start_ix = match ranges.binary_search_by(|probe| {
11224            let cmp = probe
11225                .end
11226                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11227            if cmp.is_gt() {
11228                Ordering::Greater
11229            } else {
11230                Ordering::Less
11231            }
11232        }) {
11233            Ok(i) | Err(i) => i,
11234        };
11235        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11236            if let (Some(start_display), Some(end_display)) = (start, end) {
11237                results.push(
11238                    start_display.to_display_point(display_snapshot)
11239                        ..=end_display.to_display_point(display_snapshot),
11240                );
11241            }
11242        };
11243        let mut start_row: Option<Point> = None;
11244        let mut end_row: Option<Point> = None;
11245        if ranges.len() > count {
11246            return Vec::new();
11247        }
11248        for range in &ranges[start_ix..] {
11249            if range
11250                .start
11251                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11252                .is_ge()
11253            {
11254                break;
11255            }
11256            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11257            if let Some(current_row) = &end_row {
11258                if end.row == current_row.row {
11259                    continue;
11260                }
11261            }
11262            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11263            if start_row.is_none() {
11264                assert_eq!(end_row, None);
11265                start_row = Some(start);
11266                end_row = Some(end);
11267                continue;
11268            }
11269            if let Some(current_end) = end_row.as_mut() {
11270                if start.row > current_end.row + 1 {
11271                    push_region(start_row, end_row);
11272                    start_row = Some(start);
11273                    end_row = Some(end);
11274                } else {
11275                    // Merge two hunks.
11276                    *current_end = end;
11277                }
11278            } else {
11279                unreachable!();
11280            }
11281        }
11282        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11283        push_region(start_row, end_row);
11284        results
11285    }
11286
11287    pub fn gutter_highlights_in_range(
11288        &self,
11289        search_range: Range<Anchor>,
11290        display_snapshot: &DisplaySnapshot,
11291        cx: &AppContext,
11292    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11293        let mut results = Vec::new();
11294        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11295            let color = color_fetcher(cx);
11296            let start_ix = match ranges.binary_search_by(|probe| {
11297                let cmp = probe
11298                    .end
11299                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11300                if cmp.is_gt() {
11301                    Ordering::Greater
11302                } else {
11303                    Ordering::Less
11304                }
11305            }) {
11306                Ok(i) | Err(i) => i,
11307            };
11308            for range in &ranges[start_ix..] {
11309                if range
11310                    .start
11311                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11312                    .is_ge()
11313                {
11314                    break;
11315                }
11316
11317                let start = range.start.to_display_point(&display_snapshot);
11318                let end = range.end.to_display_point(&display_snapshot);
11319                results.push((start..end, color))
11320            }
11321        }
11322        results
11323    }
11324
11325    /// Get the text ranges corresponding to the redaction query
11326    pub fn redacted_ranges(
11327        &self,
11328        search_range: Range<Anchor>,
11329        display_snapshot: &DisplaySnapshot,
11330        cx: &WindowContext,
11331    ) -> Vec<Range<DisplayPoint>> {
11332        display_snapshot
11333            .buffer_snapshot
11334            .redacted_ranges(search_range, |file| {
11335                if let Some(file) = file {
11336                    file.is_private()
11337                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11338                } else {
11339                    false
11340                }
11341            })
11342            .map(|range| {
11343                range.start.to_display_point(display_snapshot)
11344                    ..range.end.to_display_point(display_snapshot)
11345            })
11346            .collect()
11347    }
11348
11349    pub fn highlight_text<T: 'static>(
11350        &mut self,
11351        ranges: Vec<Range<Anchor>>,
11352        style: HighlightStyle,
11353        cx: &mut ViewContext<Self>,
11354    ) {
11355        self.display_map.update(cx, |map, _| {
11356            map.highlight_text(TypeId::of::<T>(), ranges, style)
11357        });
11358        cx.notify();
11359    }
11360
11361    pub(crate) fn highlight_inlays<T: 'static>(
11362        &mut self,
11363        highlights: Vec<InlayHighlight>,
11364        style: HighlightStyle,
11365        cx: &mut ViewContext<Self>,
11366    ) {
11367        self.display_map.update(cx, |map, _| {
11368            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11369        });
11370        cx.notify();
11371    }
11372
11373    pub fn text_highlights<'a, T: 'static>(
11374        &'a self,
11375        cx: &'a AppContext,
11376    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11377        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11378    }
11379
11380    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11381        let cleared = self
11382            .display_map
11383            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11384        if cleared {
11385            cx.notify();
11386        }
11387    }
11388
11389    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11390        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11391            && self.focus_handle.is_focused(cx)
11392    }
11393
11394    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11395        self.show_cursor_when_unfocused = is_enabled;
11396        cx.notify();
11397    }
11398
11399    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11400        cx.notify();
11401    }
11402
11403    fn on_buffer_event(
11404        &mut self,
11405        multibuffer: Model<MultiBuffer>,
11406        event: &multi_buffer::Event,
11407        cx: &mut ViewContext<Self>,
11408    ) {
11409        match event {
11410            multi_buffer::Event::Edited {
11411                singleton_buffer_edited,
11412            } => {
11413                self.scrollbar_marker_state.dirty = true;
11414                self.active_indent_guides_state.dirty = true;
11415                self.refresh_active_diagnostics(cx);
11416                self.refresh_code_actions(cx);
11417                if self.has_active_inline_completion(cx) {
11418                    self.update_visible_inline_completion(cx);
11419                }
11420                cx.emit(EditorEvent::BufferEdited);
11421                cx.emit(SearchEvent::MatchesInvalidated);
11422                if *singleton_buffer_edited {
11423                    if let Some(project) = &self.project {
11424                        let project = project.read(cx);
11425                        #[allow(clippy::mutable_key_type)]
11426                        let languages_affected = multibuffer
11427                            .read(cx)
11428                            .all_buffers()
11429                            .into_iter()
11430                            .filter_map(|buffer| {
11431                                let buffer = buffer.read(cx);
11432                                let language = buffer.language()?;
11433                                if project.is_local_or_ssh()
11434                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
11435                                {
11436                                    None
11437                                } else {
11438                                    Some(language)
11439                                }
11440                            })
11441                            .cloned()
11442                            .collect::<HashSet<_>>();
11443                        if !languages_affected.is_empty() {
11444                            self.refresh_inlay_hints(
11445                                InlayHintRefreshReason::BufferEdited(languages_affected),
11446                                cx,
11447                            );
11448                        }
11449                    }
11450                }
11451
11452                let Some(project) = &self.project else { return };
11453                let telemetry = project.read(cx).client().telemetry().clone();
11454                refresh_linked_ranges(self, cx);
11455                telemetry.log_edit_event("editor");
11456            }
11457            multi_buffer::Event::ExcerptsAdded {
11458                buffer,
11459                predecessor,
11460                excerpts,
11461            } => {
11462                self.tasks_update_task = Some(self.refresh_runnables(cx));
11463                cx.emit(EditorEvent::ExcerptsAdded {
11464                    buffer: buffer.clone(),
11465                    predecessor: *predecessor,
11466                    excerpts: excerpts.clone(),
11467                });
11468                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11469            }
11470            multi_buffer::Event::ExcerptsRemoved { ids } => {
11471                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11472                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11473            }
11474            multi_buffer::Event::ExcerptsEdited { ids } => {
11475                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11476            }
11477            multi_buffer::Event::ExcerptsExpanded { ids } => {
11478                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11479            }
11480            multi_buffer::Event::Reparsed(buffer_id) => {
11481                self.tasks_update_task = Some(self.refresh_runnables(cx));
11482
11483                cx.emit(EditorEvent::Reparsed(*buffer_id));
11484            }
11485            multi_buffer::Event::LanguageChanged(buffer_id) => {
11486                linked_editing_ranges::refresh_linked_ranges(self, cx);
11487                cx.emit(EditorEvent::Reparsed(*buffer_id));
11488                cx.notify();
11489            }
11490            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11491            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11492            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11493                cx.emit(EditorEvent::TitleChanged)
11494            }
11495            multi_buffer::Event::DiffBaseChanged => {
11496                self.scrollbar_marker_state.dirty = true;
11497                cx.emit(EditorEvent::DiffBaseChanged);
11498                cx.notify();
11499            }
11500            multi_buffer::Event::DiffUpdated { buffer } => {
11501                self.sync_expanded_diff_hunks(buffer.clone(), cx);
11502                cx.notify();
11503            }
11504            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11505            multi_buffer::Event::DiagnosticsUpdated => {
11506                self.refresh_active_diagnostics(cx);
11507                self.scrollbar_marker_state.dirty = true;
11508                cx.notify();
11509            }
11510            _ => {}
11511        };
11512    }
11513
11514    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11515        cx.notify();
11516    }
11517
11518    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11519        self.tasks_update_task = Some(self.refresh_runnables(cx));
11520        self.refresh_inline_completion(true, false, cx);
11521        self.refresh_inlay_hints(
11522            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11523                self.selections.newest_anchor().head(),
11524                &self.buffer.read(cx).snapshot(cx),
11525                cx,
11526            )),
11527            cx,
11528        );
11529        let editor_settings = EditorSettings::get_global(cx);
11530        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11531        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11532
11533        let project_settings = ProjectSettings::get_global(cx);
11534        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11535
11536        if self.mode == EditorMode::Full {
11537            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11538            if self.git_blame_inline_enabled != inline_blame_enabled {
11539                self.toggle_git_blame_inline_internal(false, cx);
11540            }
11541        }
11542
11543        cx.notify();
11544    }
11545
11546    pub fn set_searchable(&mut self, searchable: bool) {
11547        self.searchable = searchable;
11548    }
11549
11550    pub fn searchable(&self) -> bool {
11551        self.searchable
11552    }
11553
11554    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11555        self.open_excerpts_common(true, cx)
11556    }
11557
11558    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11559        self.open_excerpts_common(false, cx)
11560    }
11561
11562    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11563        let buffer = self.buffer.read(cx);
11564        if buffer.is_singleton() {
11565            cx.propagate();
11566            return;
11567        }
11568
11569        let Some(workspace) = self.workspace() else {
11570            cx.propagate();
11571            return;
11572        };
11573
11574        let mut new_selections_by_buffer = HashMap::default();
11575        for selection in self.selections.all::<usize>(cx) {
11576            for (buffer, mut range, _) in
11577                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11578            {
11579                if selection.reversed {
11580                    mem::swap(&mut range.start, &mut range.end);
11581                }
11582                new_selections_by_buffer
11583                    .entry(buffer)
11584                    .or_insert(Vec::new())
11585                    .push(range)
11586            }
11587        }
11588
11589        // We defer the pane interaction because we ourselves are a workspace item
11590        // and activating a new item causes the pane to call a method on us reentrantly,
11591        // which panics if we're on the stack.
11592        cx.window_context().defer(move |cx| {
11593            workspace.update(cx, |workspace, cx| {
11594                let pane = if split {
11595                    workspace.adjacent_pane(cx)
11596                } else {
11597                    workspace.active_pane().clone()
11598                };
11599
11600                for (buffer, ranges) in new_selections_by_buffer {
11601                    let editor =
11602                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11603                    editor.update(cx, |editor, cx| {
11604                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11605                            s.select_ranges(ranges);
11606                        });
11607                    });
11608                }
11609            })
11610        });
11611    }
11612
11613    fn jump(
11614        &mut self,
11615        path: ProjectPath,
11616        position: Point,
11617        anchor: language::Anchor,
11618        offset_from_top: u32,
11619        cx: &mut ViewContext<Self>,
11620    ) {
11621        let workspace = self.workspace();
11622        cx.spawn(|_, mut cx| async move {
11623            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11624            let editor = workspace.update(&mut cx, |workspace, cx| {
11625                // Reset the preview item id before opening the new item
11626                workspace.active_pane().update(cx, |pane, cx| {
11627                    pane.set_preview_item_id(None, cx);
11628                });
11629                workspace.open_path_preview(path, None, true, true, cx)
11630            })?;
11631            let editor = editor
11632                .await?
11633                .downcast::<Editor>()
11634                .ok_or_else(|| anyhow!("opened item was not an editor"))?
11635                .downgrade();
11636            editor.update(&mut cx, |editor, cx| {
11637                let buffer = editor
11638                    .buffer()
11639                    .read(cx)
11640                    .as_singleton()
11641                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11642                let buffer = buffer.read(cx);
11643                let cursor = if buffer.can_resolve(&anchor) {
11644                    language::ToPoint::to_point(&anchor, buffer)
11645                } else {
11646                    buffer.clip_point(position, Bias::Left)
11647                };
11648
11649                let nav_history = editor.nav_history.take();
11650                editor.change_selections(
11651                    Some(Autoscroll::top_relative(offset_from_top as usize)),
11652                    cx,
11653                    |s| {
11654                        s.select_ranges([cursor..cursor]);
11655                    },
11656                );
11657                editor.nav_history = nav_history;
11658
11659                anyhow::Ok(())
11660            })??;
11661
11662            anyhow::Ok(())
11663        })
11664        .detach_and_log_err(cx);
11665    }
11666
11667    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11668        let snapshot = self.buffer.read(cx).read(cx);
11669        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11670        Some(
11671            ranges
11672                .iter()
11673                .map(move |range| {
11674                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11675                })
11676                .collect(),
11677        )
11678    }
11679
11680    fn selection_replacement_ranges(
11681        &self,
11682        range: Range<OffsetUtf16>,
11683        cx: &AppContext,
11684    ) -> Vec<Range<OffsetUtf16>> {
11685        let selections = self.selections.all::<OffsetUtf16>(cx);
11686        let newest_selection = selections
11687            .iter()
11688            .max_by_key(|selection| selection.id)
11689            .unwrap();
11690        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11691        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11692        let snapshot = self.buffer.read(cx).read(cx);
11693        selections
11694            .into_iter()
11695            .map(|mut selection| {
11696                selection.start.0 =
11697                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
11698                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11699                snapshot.clip_offset_utf16(selection.start, Bias::Left)
11700                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11701            })
11702            .collect()
11703    }
11704
11705    fn report_editor_event(
11706        &self,
11707        operation: &'static str,
11708        file_extension: Option<String>,
11709        cx: &AppContext,
11710    ) {
11711        if cfg!(any(test, feature = "test-support")) {
11712            return;
11713        }
11714
11715        let Some(project) = &self.project else { return };
11716
11717        // If None, we are in a file without an extension
11718        let file = self
11719            .buffer
11720            .read(cx)
11721            .as_singleton()
11722            .and_then(|b| b.read(cx).file());
11723        let file_extension = file_extension.or(file
11724            .as_ref()
11725            .and_then(|file| Path::new(file.file_name(cx)).extension())
11726            .and_then(|e| e.to_str())
11727            .map(|a| a.to_string()));
11728
11729        let vim_mode = cx
11730            .global::<SettingsStore>()
11731            .raw_user_settings()
11732            .get("vim_mode")
11733            == Some(&serde_json::Value::Bool(true));
11734
11735        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11736            == language::language_settings::InlineCompletionProvider::Copilot;
11737        let copilot_enabled_for_language = self
11738            .buffer
11739            .read(cx)
11740            .settings_at(0, cx)
11741            .show_inline_completions;
11742
11743        let telemetry = project.read(cx).client().telemetry().clone();
11744        telemetry.report_editor_event(
11745            file_extension,
11746            vim_mode,
11747            operation,
11748            copilot_enabled,
11749            copilot_enabled_for_language,
11750        )
11751    }
11752
11753    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11754    /// with each line being an array of {text, highlight} objects.
11755    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11756        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11757            return;
11758        };
11759
11760        #[derive(Serialize)]
11761        struct Chunk<'a> {
11762            text: String,
11763            highlight: Option<&'a str>,
11764        }
11765
11766        let snapshot = buffer.read(cx).snapshot();
11767        let range = self
11768            .selected_text_range(cx)
11769            .and_then(|selected_range| {
11770                if selected_range.is_empty() {
11771                    None
11772                } else {
11773                    Some(selected_range)
11774                }
11775            })
11776            .unwrap_or_else(|| 0..snapshot.len());
11777
11778        let chunks = snapshot.chunks(range, true);
11779        let mut lines = Vec::new();
11780        let mut line: VecDeque<Chunk> = VecDeque::new();
11781
11782        let Some(style) = self.style.as_ref() else {
11783            return;
11784        };
11785
11786        for chunk in chunks {
11787            let highlight = chunk
11788                .syntax_highlight_id
11789                .and_then(|id| id.name(&style.syntax));
11790            let mut chunk_lines = chunk.text.split('\n').peekable();
11791            while let Some(text) = chunk_lines.next() {
11792                let mut merged_with_last_token = false;
11793                if let Some(last_token) = line.back_mut() {
11794                    if last_token.highlight == highlight {
11795                        last_token.text.push_str(text);
11796                        merged_with_last_token = true;
11797                    }
11798                }
11799
11800                if !merged_with_last_token {
11801                    line.push_back(Chunk {
11802                        text: text.into(),
11803                        highlight,
11804                    });
11805                }
11806
11807                if chunk_lines.peek().is_some() {
11808                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
11809                        line.pop_front();
11810                    }
11811                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
11812                        line.pop_back();
11813                    }
11814
11815                    lines.push(mem::take(&mut line));
11816                }
11817            }
11818        }
11819
11820        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11821            return;
11822        };
11823        cx.write_to_clipboard(ClipboardItem::new_string(lines));
11824    }
11825
11826    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11827        &self.inlay_hint_cache
11828    }
11829
11830    pub fn replay_insert_event(
11831        &mut self,
11832        text: &str,
11833        relative_utf16_range: Option<Range<isize>>,
11834        cx: &mut ViewContext<Self>,
11835    ) {
11836        if !self.input_enabled {
11837            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11838            return;
11839        }
11840        if let Some(relative_utf16_range) = relative_utf16_range {
11841            let selections = self.selections.all::<OffsetUtf16>(cx);
11842            self.change_selections(None, cx, |s| {
11843                let new_ranges = selections.into_iter().map(|range| {
11844                    let start = OffsetUtf16(
11845                        range
11846                            .head()
11847                            .0
11848                            .saturating_add_signed(relative_utf16_range.start),
11849                    );
11850                    let end = OffsetUtf16(
11851                        range
11852                            .head()
11853                            .0
11854                            .saturating_add_signed(relative_utf16_range.end),
11855                    );
11856                    start..end
11857                });
11858                s.select_ranges(new_ranges);
11859            });
11860        }
11861
11862        self.handle_input(text, cx);
11863    }
11864
11865    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11866        let Some(project) = self.project.as_ref() else {
11867            return false;
11868        };
11869        let project = project.read(cx);
11870
11871        let mut supports = false;
11872        self.buffer().read(cx).for_each_buffer(|buffer| {
11873            if !supports {
11874                supports = project
11875                    .language_servers_for_buffer(buffer.read(cx), cx)
11876                    .any(
11877                        |(_, server)| match server.capabilities().inlay_hint_provider {
11878                            Some(lsp::OneOf::Left(enabled)) => enabled,
11879                            Some(lsp::OneOf::Right(_)) => true,
11880                            None => false,
11881                        },
11882                    )
11883            }
11884        });
11885        supports
11886    }
11887
11888    pub fn focus(&self, cx: &mut WindowContext) {
11889        cx.focus(&self.focus_handle)
11890    }
11891
11892    pub fn is_focused(&self, cx: &WindowContext) -> bool {
11893        self.focus_handle.is_focused(cx)
11894    }
11895
11896    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11897        cx.emit(EditorEvent::Focused);
11898
11899        if let Some(descendant) = self
11900            .last_focused_descendant
11901            .take()
11902            .and_then(|descendant| descendant.upgrade())
11903        {
11904            cx.focus(&descendant);
11905        } else {
11906            if let Some(blame) = self.blame.as_ref() {
11907                blame.update(cx, GitBlame::focus)
11908            }
11909
11910            self.blink_manager.update(cx, BlinkManager::enable);
11911            self.show_cursor_names(cx);
11912            self.buffer.update(cx, |buffer, cx| {
11913                buffer.finalize_last_transaction(cx);
11914                if self.leader_peer_id.is_none() {
11915                    buffer.set_active_selections(
11916                        &self.selections.disjoint_anchors(),
11917                        self.selections.line_mode,
11918                        self.cursor_shape,
11919                        cx,
11920                    );
11921                }
11922            });
11923        }
11924    }
11925
11926    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11927        cx.emit(EditorEvent::FocusedIn)
11928    }
11929
11930    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11931        if event.blurred != self.focus_handle {
11932            self.last_focused_descendant = Some(event.blurred);
11933        }
11934    }
11935
11936    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11937        self.blink_manager.update(cx, BlinkManager::disable);
11938        self.buffer
11939            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11940
11941        if let Some(blame) = self.blame.as_ref() {
11942            blame.update(cx, GitBlame::blur)
11943        }
11944        if !self.hover_state.focused(cx) {
11945            hide_hover(self, cx);
11946        }
11947
11948        self.hide_context_menu(cx);
11949        cx.emit(EditorEvent::Blurred);
11950        cx.notify();
11951    }
11952
11953    pub fn register_action<A: Action>(
11954        &mut self,
11955        listener: impl Fn(&A, &mut WindowContext) + 'static,
11956    ) -> Subscription {
11957        let id = self.next_editor_action_id.post_inc();
11958        let listener = Arc::new(listener);
11959        self.editor_actions.borrow_mut().insert(
11960            id,
11961            Box::new(move |cx| {
11962                let cx = cx.window_context();
11963                let listener = listener.clone();
11964                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11965                    let action = action.downcast_ref().unwrap();
11966                    if phase == DispatchPhase::Bubble {
11967                        listener(action, cx)
11968                    }
11969                })
11970            }),
11971        );
11972
11973        let editor_actions = self.editor_actions.clone();
11974        Subscription::new(move || {
11975            editor_actions.borrow_mut().remove(&id);
11976        })
11977    }
11978
11979    pub fn file_header_size(&self) -> u32 {
11980        self.file_header_size
11981    }
11982
11983    pub fn revert(
11984        &mut self,
11985        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
11986        cx: &mut ViewContext<Self>,
11987    ) {
11988        self.buffer().update(cx, |multi_buffer, cx| {
11989            for (buffer_id, changes) in revert_changes {
11990                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
11991                    buffer.update(cx, |buffer, cx| {
11992                        buffer.edit(
11993                            changes.into_iter().map(|(range, text)| {
11994                                (range, text.to_string().map(Arc::<str>::from))
11995                            }),
11996                            None,
11997                            cx,
11998                        );
11999                    });
12000                }
12001            }
12002        });
12003        self.change_selections(None, cx, |selections| selections.refresh());
12004    }
12005
12006    pub fn to_pixel_point(
12007        &mut self,
12008        source: multi_buffer::Anchor,
12009        editor_snapshot: &EditorSnapshot,
12010        cx: &mut ViewContext<Self>,
12011    ) -> Option<gpui::Point<Pixels>> {
12012        let source_point = source.to_display_point(editor_snapshot);
12013        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12014    }
12015
12016    pub fn display_to_pixel_point(
12017        &mut self,
12018        source: DisplayPoint,
12019        editor_snapshot: &EditorSnapshot,
12020        cx: &mut ViewContext<Self>,
12021    ) -> Option<gpui::Point<Pixels>> {
12022        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12023        let text_layout_details = self.text_layout_details(cx);
12024        let scroll_top = text_layout_details
12025            .scroll_anchor
12026            .scroll_position(editor_snapshot)
12027            .y;
12028
12029        if source.row().as_f32() < scroll_top.floor() {
12030            return None;
12031        }
12032        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12033        let source_y = line_height * (source.row().as_f32() - scroll_top);
12034        Some(gpui::Point::new(source_x, source_y))
12035    }
12036
12037    fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12038        let bounds = self.last_bounds?;
12039        Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12040    }
12041
12042    pub fn has_active_completions_menu(&self) -> bool {
12043        self.context_menu.read().as_ref().map_or(false, |menu| {
12044            menu.visible() && matches!(menu, ContextMenu::Completions(_))
12045        })
12046    }
12047
12048    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12049        self.addons
12050            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12051    }
12052
12053    pub fn unregister_addon<T: Addon>(&mut self) {
12054        self.addons.remove(&std::any::TypeId::of::<T>());
12055    }
12056
12057    pub fn addon<T: Addon>(&self) -> Option<&T> {
12058        let type_id = std::any::TypeId::of::<T>();
12059        self.addons
12060            .get(&type_id)
12061            .and_then(|item| item.to_any().downcast_ref::<T>())
12062    }
12063}
12064
12065fn hunks_for_selections(
12066    multi_buffer_snapshot: &MultiBufferSnapshot,
12067    selections: &[Selection<Anchor>],
12068) -> Vec<DiffHunk<MultiBufferRow>> {
12069    let buffer_rows_for_selections = selections.iter().map(|selection| {
12070        let head = selection.head();
12071        let tail = selection.tail();
12072        let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
12073        let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
12074        if start > end {
12075            end..start
12076        } else {
12077            start..end
12078        }
12079    });
12080
12081    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12082}
12083
12084pub fn hunks_for_rows(
12085    rows: impl Iterator<Item = Range<MultiBufferRow>>,
12086    multi_buffer_snapshot: &MultiBufferSnapshot,
12087) -> Vec<DiffHunk<MultiBufferRow>> {
12088    let mut hunks = Vec::new();
12089    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12090        HashMap::default();
12091    for selected_multi_buffer_rows in rows {
12092        let query_rows =
12093            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12094        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12095            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12096            // when the caret is just above or just below the deleted hunk.
12097            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12098            let related_to_selection = if allow_adjacent {
12099                hunk.associated_range.overlaps(&query_rows)
12100                    || hunk.associated_range.start == query_rows.end
12101                    || hunk.associated_range.end == query_rows.start
12102            } else {
12103                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12104                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12105                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12106                    || selected_multi_buffer_rows.end == hunk.associated_range.start
12107            };
12108            if related_to_selection {
12109                if !processed_buffer_rows
12110                    .entry(hunk.buffer_id)
12111                    .or_default()
12112                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12113                {
12114                    continue;
12115                }
12116                hunks.push(hunk);
12117            }
12118        }
12119    }
12120
12121    hunks
12122}
12123
12124pub trait CollaborationHub {
12125    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12126    fn user_participant_indices<'a>(
12127        &self,
12128        cx: &'a AppContext,
12129    ) -> &'a HashMap<u64, ParticipantIndex>;
12130    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12131}
12132
12133impl CollaborationHub for Model<Project> {
12134    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12135        self.read(cx).collaborators()
12136    }
12137
12138    fn user_participant_indices<'a>(
12139        &self,
12140        cx: &'a AppContext,
12141    ) -> &'a HashMap<u64, ParticipantIndex> {
12142        self.read(cx).user_store().read(cx).participant_indices()
12143    }
12144
12145    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12146        let this = self.read(cx);
12147        let user_ids = this.collaborators().values().map(|c| c.user_id);
12148        this.user_store().read_with(cx, |user_store, cx| {
12149            user_store.participant_names(user_ids, cx)
12150        })
12151    }
12152}
12153
12154pub trait CompletionProvider {
12155    fn completions(
12156        &self,
12157        buffer: &Model<Buffer>,
12158        buffer_position: text::Anchor,
12159        trigger: CompletionContext,
12160        cx: &mut ViewContext<Editor>,
12161    ) -> Task<Result<Vec<Completion>>>;
12162
12163    fn resolve_completions(
12164        &self,
12165        buffer: Model<Buffer>,
12166        completion_indices: Vec<usize>,
12167        completions: Arc<RwLock<Box<[Completion]>>>,
12168        cx: &mut ViewContext<Editor>,
12169    ) -> Task<Result<bool>>;
12170
12171    fn apply_additional_edits_for_completion(
12172        &self,
12173        buffer: Model<Buffer>,
12174        completion: Completion,
12175        push_to_history: bool,
12176        cx: &mut ViewContext<Editor>,
12177    ) -> Task<Result<Option<language::Transaction>>>;
12178
12179    fn is_completion_trigger(
12180        &self,
12181        buffer: &Model<Buffer>,
12182        position: language::Anchor,
12183        text: &str,
12184        trigger_in_words: bool,
12185        cx: &mut ViewContext<Editor>,
12186    ) -> bool;
12187
12188    fn sort_completions(&self) -> bool {
12189        true
12190    }
12191}
12192
12193fn snippet_completions(
12194    project: &Project,
12195    buffer: &Model<Buffer>,
12196    buffer_position: text::Anchor,
12197    cx: &mut AppContext,
12198) -> Vec<Completion> {
12199    let language = buffer.read(cx).language_at(buffer_position);
12200    let language_name = language.as_ref().map(|language| language.lsp_id());
12201    let snippet_store = project.snippets().read(cx);
12202    let snippets = snippet_store.snippets_for(language_name, cx);
12203
12204    if snippets.is_empty() {
12205        return vec![];
12206    }
12207    let snapshot = buffer.read(cx).text_snapshot();
12208    let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12209
12210    let mut lines = chunks.lines();
12211    let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12212        return vec![];
12213    };
12214
12215    let scope = language.map(|language| language.default_scope());
12216    let mut last_word = line_at
12217        .chars()
12218        .rev()
12219        .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
12220        .collect::<String>();
12221    last_word = last_word.chars().rev().collect();
12222    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12223    let to_lsp = |point: &text::Anchor| {
12224        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12225        point_to_lsp(end)
12226    };
12227    let lsp_end = to_lsp(&buffer_position);
12228    snippets
12229        .into_iter()
12230        .filter_map(|snippet| {
12231            let matching_prefix = snippet
12232                .prefix
12233                .iter()
12234                .find(|prefix| prefix.starts_with(&last_word))?;
12235            let start = as_offset - last_word.len();
12236            let start = snapshot.anchor_before(start);
12237            let range = start..buffer_position;
12238            let lsp_start = to_lsp(&start);
12239            let lsp_range = lsp::Range {
12240                start: lsp_start,
12241                end: lsp_end,
12242            };
12243            Some(Completion {
12244                old_range: range,
12245                new_text: snippet.body.clone(),
12246                label: CodeLabel {
12247                    text: matching_prefix.clone(),
12248                    runs: vec![],
12249                    filter_range: 0..matching_prefix.len(),
12250                },
12251                server_id: LanguageServerId(usize::MAX),
12252                documentation: snippet
12253                    .description
12254                    .clone()
12255                    .map(|description| Documentation::SingleLine(description)),
12256                lsp_completion: lsp::CompletionItem {
12257                    label: snippet.prefix.first().unwrap().clone(),
12258                    kind: Some(CompletionItemKind::SNIPPET),
12259                    label_details: snippet.description.as_ref().map(|description| {
12260                        lsp::CompletionItemLabelDetails {
12261                            detail: Some(description.clone()),
12262                            description: None,
12263                        }
12264                    }),
12265                    insert_text_format: Some(InsertTextFormat::SNIPPET),
12266                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12267                        lsp::InsertReplaceEdit {
12268                            new_text: snippet.body.clone(),
12269                            insert: lsp_range,
12270                            replace: lsp_range,
12271                        },
12272                    )),
12273                    filter_text: Some(snippet.body.clone()),
12274                    sort_text: Some(char::MAX.to_string()),
12275                    ..Default::default()
12276                },
12277                confirm: None,
12278            })
12279        })
12280        .collect()
12281}
12282
12283impl CompletionProvider for Model<Project> {
12284    fn completions(
12285        &self,
12286        buffer: &Model<Buffer>,
12287        buffer_position: text::Anchor,
12288        options: CompletionContext,
12289        cx: &mut ViewContext<Editor>,
12290    ) -> Task<Result<Vec<Completion>>> {
12291        self.update(cx, |project, cx| {
12292            let snippets = snippet_completions(project, buffer, buffer_position, cx);
12293            let project_completions = project.completions(&buffer, buffer_position, options, cx);
12294            cx.background_executor().spawn(async move {
12295                let mut completions = project_completions.await?;
12296                //let snippets = snippets.into_iter().;
12297                completions.extend(snippets);
12298                Ok(completions)
12299            })
12300        })
12301    }
12302
12303    fn resolve_completions(
12304        &self,
12305        buffer: Model<Buffer>,
12306        completion_indices: Vec<usize>,
12307        completions: Arc<RwLock<Box<[Completion]>>>,
12308        cx: &mut ViewContext<Editor>,
12309    ) -> Task<Result<bool>> {
12310        self.update(cx, |project, cx| {
12311            project.resolve_completions(buffer, completion_indices, completions, cx)
12312        })
12313    }
12314
12315    fn apply_additional_edits_for_completion(
12316        &self,
12317        buffer: Model<Buffer>,
12318        completion: Completion,
12319        push_to_history: bool,
12320        cx: &mut ViewContext<Editor>,
12321    ) -> Task<Result<Option<language::Transaction>>> {
12322        self.update(cx, |project, cx| {
12323            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12324        })
12325    }
12326
12327    fn is_completion_trigger(
12328        &self,
12329        buffer: &Model<Buffer>,
12330        position: language::Anchor,
12331        text: &str,
12332        trigger_in_words: bool,
12333        cx: &mut ViewContext<Editor>,
12334    ) -> bool {
12335        if !EditorSettings::get_global(cx).show_completions_on_input {
12336            return false;
12337        }
12338
12339        let mut chars = text.chars();
12340        let char = if let Some(char) = chars.next() {
12341            char
12342        } else {
12343            return false;
12344        };
12345        if chars.next().is_some() {
12346            return false;
12347        }
12348
12349        let buffer = buffer.read(cx);
12350        let scope = buffer.snapshot().language_scope_at(position);
12351        if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12352            return true;
12353        }
12354
12355        buffer
12356            .completion_triggers()
12357            .iter()
12358            .any(|string| string == text)
12359    }
12360}
12361
12362fn inlay_hint_settings(
12363    location: Anchor,
12364    snapshot: &MultiBufferSnapshot,
12365    cx: &mut ViewContext<'_, Editor>,
12366) -> InlayHintSettings {
12367    let file = snapshot.file_at(location);
12368    let language = snapshot.language_at(location);
12369    let settings = all_language_settings(file, cx);
12370    settings
12371        .language(language.map(|l| l.name()).as_deref())
12372        .inlay_hints
12373}
12374
12375fn consume_contiguous_rows(
12376    contiguous_row_selections: &mut Vec<Selection<Point>>,
12377    selection: &Selection<Point>,
12378    display_map: &DisplaySnapshot,
12379    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12380) -> (MultiBufferRow, MultiBufferRow) {
12381    contiguous_row_selections.push(selection.clone());
12382    let start_row = MultiBufferRow(selection.start.row);
12383    let mut end_row = ending_row(selection, display_map);
12384
12385    while let Some(next_selection) = selections.peek() {
12386        if next_selection.start.row <= end_row.0 {
12387            end_row = ending_row(next_selection, display_map);
12388            contiguous_row_selections.push(selections.next().unwrap().clone());
12389        } else {
12390            break;
12391        }
12392    }
12393    (start_row, end_row)
12394}
12395
12396fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12397    if next_selection.end.column > 0 || next_selection.is_empty() {
12398        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12399    } else {
12400        MultiBufferRow(next_selection.end.row)
12401    }
12402}
12403
12404impl EditorSnapshot {
12405    pub fn remote_selections_in_range<'a>(
12406        &'a self,
12407        range: &'a Range<Anchor>,
12408        collaboration_hub: &dyn CollaborationHub,
12409        cx: &'a AppContext,
12410    ) -> impl 'a + Iterator<Item = RemoteSelection> {
12411        let participant_names = collaboration_hub.user_names(cx);
12412        let participant_indices = collaboration_hub.user_participant_indices(cx);
12413        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12414        let collaborators_by_replica_id = collaborators_by_peer_id
12415            .iter()
12416            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12417            .collect::<HashMap<_, _>>();
12418        self.buffer_snapshot
12419            .selections_in_range(range, false)
12420            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12421                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12422                let participant_index = participant_indices.get(&collaborator.user_id).copied();
12423                let user_name = participant_names.get(&collaborator.user_id).cloned();
12424                Some(RemoteSelection {
12425                    replica_id,
12426                    selection,
12427                    cursor_shape,
12428                    line_mode,
12429                    participant_index,
12430                    peer_id: collaborator.peer_id,
12431                    user_name,
12432                })
12433            })
12434    }
12435
12436    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12437        self.display_snapshot.buffer_snapshot.language_at(position)
12438    }
12439
12440    pub fn is_focused(&self) -> bool {
12441        self.is_focused
12442    }
12443
12444    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12445        self.placeholder_text.as_ref()
12446    }
12447
12448    pub fn scroll_position(&self) -> gpui::Point<f32> {
12449        self.scroll_anchor.scroll_position(&self.display_snapshot)
12450    }
12451
12452    fn gutter_dimensions(
12453        &self,
12454        font_id: FontId,
12455        font_size: Pixels,
12456        em_width: Pixels,
12457        max_line_number_width: Pixels,
12458        cx: &AppContext,
12459    ) -> GutterDimensions {
12460        if !self.show_gutter {
12461            return GutterDimensions::default();
12462        }
12463        let descent = cx.text_system().descent(font_id, font_size);
12464
12465        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12466            matches!(
12467                ProjectSettings::get_global(cx).git.git_gutter,
12468                Some(GitGutterSetting::TrackedFiles)
12469            )
12470        });
12471        let gutter_settings = EditorSettings::get_global(cx).gutter;
12472        let show_line_numbers = self
12473            .show_line_numbers
12474            .unwrap_or(gutter_settings.line_numbers);
12475        let line_gutter_width = if show_line_numbers {
12476            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12477            let min_width_for_number_on_gutter = em_width * 4.0;
12478            max_line_number_width.max(min_width_for_number_on_gutter)
12479        } else {
12480            0.0.into()
12481        };
12482
12483        let show_code_actions = self
12484            .show_code_actions
12485            .unwrap_or(gutter_settings.code_actions);
12486
12487        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12488
12489        let git_blame_entries_width = self
12490            .render_git_blame_gutter
12491            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12492
12493        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12494        left_padding += if show_code_actions || show_runnables {
12495            em_width * 3.0
12496        } else if show_git_gutter && show_line_numbers {
12497            em_width * 2.0
12498        } else if show_git_gutter || show_line_numbers {
12499            em_width
12500        } else {
12501            px(0.)
12502        };
12503
12504        let right_padding = if gutter_settings.folds && show_line_numbers {
12505            em_width * 4.0
12506        } else if gutter_settings.folds {
12507            em_width * 3.0
12508        } else if show_line_numbers {
12509            em_width
12510        } else {
12511            px(0.)
12512        };
12513
12514        GutterDimensions {
12515            left_padding,
12516            right_padding,
12517            width: line_gutter_width + left_padding + right_padding,
12518            margin: -descent,
12519            git_blame_entries_width,
12520        }
12521    }
12522
12523    pub fn render_fold_toggle(
12524        &self,
12525        buffer_row: MultiBufferRow,
12526        row_contains_cursor: bool,
12527        editor: View<Editor>,
12528        cx: &mut WindowContext,
12529    ) -> Option<AnyElement> {
12530        let folded = self.is_line_folded(buffer_row);
12531
12532        if let Some(crease) = self
12533            .crease_snapshot
12534            .query_row(buffer_row, &self.buffer_snapshot)
12535        {
12536            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12537                if folded {
12538                    editor.update(cx, |editor, cx| {
12539                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12540                    });
12541                } else {
12542                    editor.update(cx, |editor, cx| {
12543                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12544                    });
12545                }
12546            });
12547
12548            Some((crease.render_toggle)(
12549                buffer_row,
12550                folded,
12551                toggle_callback,
12552                cx,
12553            ))
12554        } else if folded
12555            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12556        {
12557            Some(
12558                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12559                    .selected(folded)
12560                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12561                        if folded {
12562                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
12563                        } else {
12564                            this.fold_at(&FoldAt { buffer_row }, cx);
12565                        }
12566                    }))
12567                    .into_any_element(),
12568            )
12569        } else {
12570            None
12571        }
12572    }
12573
12574    pub fn render_crease_trailer(
12575        &self,
12576        buffer_row: MultiBufferRow,
12577        cx: &mut WindowContext,
12578    ) -> Option<AnyElement> {
12579        let folded = self.is_line_folded(buffer_row);
12580        let crease = self
12581            .crease_snapshot
12582            .query_row(buffer_row, &self.buffer_snapshot)?;
12583        Some((crease.render_trailer)(buffer_row, folded, cx))
12584    }
12585}
12586
12587impl Deref for EditorSnapshot {
12588    type Target = DisplaySnapshot;
12589
12590    fn deref(&self) -> &Self::Target {
12591        &self.display_snapshot
12592    }
12593}
12594
12595#[derive(Clone, Debug, PartialEq, Eq)]
12596pub enum EditorEvent {
12597    InputIgnored {
12598        text: Arc<str>,
12599    },
12600    InputHandled {
12601        utf16_range_to_replace: Option<Range<isize>>,
12602        text: Arc<str>,
12603    },
12604    ExcerptsAdded {
12605        buffer: Model<Buffer>,
12606        predecessor: ExcerptId,
12607        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12608    },
12609    ExcerptsRemoved {
12610        ids: Vec<ExcerptId>,
12611    },
12612    ExcerptsEdited {
12613        ids: Vec<ExcerptId>,
12614    },
12615    ExcerptsExpanded {
12616        ids: Vec<ExcerptId>,
12617    },
12618    BufferEdited,
12619    Edited {
12620        transaction_id: clock::Lamport,
12621    },
12622    Reparsed(BufferId),
12623    Focused,
12624    FocusedIn,
12625    Blurred,
12626    DirtyChanged,
12627    Saved,
12628    TitleChanged,
12629    DiffBaseChanged,
12630    SelectionsChanged {
12631        local: bool,
12632    },
12633    ScrollPositionChanged {
12634        local: bool,
12635        autoscroll: bool,
12636    },
12637    Closed,
12638    TransactionUndone {
12639        transaction_id: clock::Lamport,
12640    },
12641    TransactionBegun {
12642        transaction_id: clock::Lamport,
12643    },
12644}
12645
12646impl EventEmitter<EditorEvent> for Editor {}
12647
12648impl FocusableView for Editor {
12649    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12650        self.focus_handle.clone()
12651    }
12652}
12653
12654impl Render for Editor {
12655    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12656        let settings = ThemeSettings::get_global(cx);
12657
12658        let text_style = match self.mode {
12659            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12660                color: cx.theme().colors().editor_foreground,
12661                font_family: settings.ui_font.family.clone(),
12662                font_features: settings.ui_font.features.clone(),
12663                font_fallbacks: settings.ui_font.fallbacks.clone(),
12664                font_size: rems(0.875).into(),
12665                font_weight: settings.ui_font.weight,
12666                line_height: relative(settings.buffer_line_height.value()),
12667                ..Default::default()
12668            },
12669            EditorMode::Full => TextStyle {
12670                color: cx.theme().colors().editor_foreground,
12671                font_family: settings.buffer_font.family.clone(),
12672                font_features: settings.buffer_font.features.clone(),
12673                font_fallbacks: settings.buffer_font.fallbacks.clone(),
12674                font_size: settings.buffer_font_size(cx).into(),
12675                font_weight: settings.buffer_font.weight,
12676                line_height: relative(settings.buffer_line_height.value()),
12677                ..Default::default()
12678            },
12679        };
12680
12681        let background = match self.mode {
12682            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12683            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12684            EditorMode::Full => cx.theme().colors().editor_background,
12685        };
12686
12687        EditorElement::new(
12688            cx.view(),
12689            EditorStyle {
12690                background,
12691                local_player: cx.theme().players().local(),
12692                text: text_style,
12693                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12694                syntax: cx.theme().syntax().clone(),
12695                status: cx.theme().status().clone(),
12696                inlay_hints_style: HighlightStyle {
12697                    color: Some(cx.theme().status().hint),
12698                    ..HighlightStyle::default()
12699                },
12700                suggestions_style: HighlightStyle {
12701                    color: Some(cx.theme().status().predictive),
12702                    ..HighlightStyle::default()
12703                },
12704                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
12705            },
12706        )
12707    }
12708}
12709
12710impl ViewInputHandler for Editor {
12711    fn text_for_range(
12712        &mut self,
12713        range_utf16: Range<usize>,
12714        cx: &mut ViewContext<Self>,
12715    ) -> Option<String> {
12716        Some(
12717            self.buffer
12718                .read(cx)
12719                .read(cx)
12720                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12721                .collect(),
12722        )
12723    }
12724
12725    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12726        // Prevent the IME menu from appearing when holding down an alphabetic key
12727        // while input is disabled.
12728        if !self.input_enabled {
12729            return None;
12730        }
12731
12732        let range = self.selections.newest::<OffsetUtf16>(cx).range();
12733        Some(range.start.0..range.end.0)
12734    }
12735
12736    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12737        let snapshot = self.buffer.read(cx).read(cx);
12738        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12739        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12740    }
12741
12742    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12743        self.clear_highlights::<InputComposition>(cx);
12744        self.ime_transaction.take();
12745    }
12746
12747    fn replace_text_in_range(
12748        &mut self,
12749        range_utf16: Option<Range<usize>>,
12750        text: &str,
12751        cx: &mut ViewContext<Self>,
12752    ) {
12753        if !self.input_enabled {
12754            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12755            return;
12756        }
12757
12758        self.transact(cx, |this, cx| {
12759            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12760                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12761                Some(this.selection_replacement_ranges(range_utf16, cx))
12762            } else {
12763                this.marked_text_ranges(cx)
12764            };
12765
12766            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12767                let newest_selection_id = this.selections.newest_anchor().id;
12768                this.selections
12769                    .all::<OffsetUtf16>(cx)
12770                    .iter()
12771                    .zip(ranges_to_replace.iter())
12772                    .find_map(|(selection, range)| {
12773                        if selection.id == newest_selection_id {
12774                            Some(
12775                                (range.start.0 as isize - selection.head().0 as isize)
12776                                    ..(range.end.0 as isize - selection.head().0 as isize),
12777                            )
12778                        } else {
12779                            None
12780                        }
12781                    })
12782            });
12783
12784            cx.emit(EditorEvent::InputHandled {
12785                utf16_range_to_replace: range_to_replace,
12786                text: text.into(),
12787            });
12788
12789            if let Some(new_selected_ranges) = new_selected_ranges {
12790                this.change_selections(None, cx, |selections| {
12791                    selections.select_ranges(new_selected_ranges)
12792                });
12793                this.backspace(&Default::default(), cx);
12794            }
12795
12796            this.handle_input(text, cx);
12797        });
12798
12799        if let Some(transaction) = self.ime_transaction {
12800            self.buffer.update(cx, |buffer, cx| {
12801                buffer.group_until_transaction(transaction, cx);
12802            });
12803        }
12804
12805        self.unmark_text(cx);
12806    }
12807
12808    fn replace_and_mark_text_in_range(
12809        &mut self,
12810        range_utf16: Option<Range<usize>>,
12811        text: &str,
12812        new_selected_range_utf16: Option<Range<usize>>,
12813        cx: &mut ViewContext<Self>,
12814    ) {
12815        if !self.input_enabled {
12816            return;
12817        }
12818
12819        let transaction = self.transact(cx, |this, cx| {
12820            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12821                let snapshot = this.buffer.read(cx).read(cx);
12822                if let Some(relative_range_utf16) = range_utf16.as_ref() {
12823                    for marked_range in &mut marked_ranges {
12824                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12825                        marked_range.start.0 += relative_range_utf16.start;
12826                        marked_range.start =
12827                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12828                        marked_range.end =
12829                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12830                    }
12831                }
12832                Some(marked_ranges)
12833            } else if let Some(range_utf16) = range_utf16 {
12834                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12835                Some(this.selection_replacement_ranges(range_utf16, cx))
12836            } else {
12837                None
12838            };
12839
12840            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12841                let newest_selection_id = this.selections.newest_anchor().id;
12842                this.selections
12843                    .all::<OffsetUtf16>(cx)
12844                    .iter()
12845                    .zip(ranges_to_replace.iter())
12846                    .find_map(|(selection, range)| {
12847                        if selection.id == newest_selection_id {
12848                            Some(
12849                                (range.start.0 as isize - selection.head().0 as isize)
12850                                    ..(range.end.0 as isize - selection.head().0 as isize),
12851                            )
12852                        } else {
12853                            None
12854                        }
12855                    })
12856            });
12857
12858            cx.emit(EditorEvent::InputHandled {
12859                utf16_range_to_replace: range_to_replace,
12860                text: text.into(),
12861            });
12862
12863            if let Some(ranges) = ranges_to_replace {
12864                this.change_selections(None, cx, |s| s.select_ranges(ranges));
12865            }
12866
12867            let marked_ranges = {
12868                let snapshot = this.buffer.read(cx).read(cx);
12869                this.selections
12870                    .disjoint_anchors()
12871                    .iter()
12872                    .map(|selection| {
12873                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12874                    })
12875                    .collect::<Vec<_>>()
12876            };
12877
12878            if text.is_empty() {
12879                this.unmark_text(cx);
12880            } else {
12881                this.highlight_text::<InputComposition>(
12882                    marked_ranges.clone(),
12883                    HighlightStyle {
12884                        underline: Some(UnderlineStyle {
12885                            thickness: px(1.),
12886                            color: None,
12887                            wavy: false,
12888                        }),
12889                        ..Default::default()
12890                    },
12891                    cx,
12892                );
12893            }
12894
12895            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12896            let use_autoclose = this.use_autoclose;
12897            let use_auto_surround = this.use_auto_surround;
12898            this.set_use_autoclose(false);
12899            this.set_use_auto_surround(false);
12900            this.handle_input(text, cx);
12901            this.set_use_autoclose(use_autoclose);
12902            this.set_use_auto_surround(use_auto_surround);
12903
12904            if let Some(new_selected_range) = new_selected_range_utf16 {
12905                let snapshot = this.buffer.read(cx).read(cx);
12906                let new_selected_ranges = marked_ranges
12907                    .into_iter()
12908                    .map(|marked_range| {
12909                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12910                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12911                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12912                        snapshot.clip_offset_utf16(new_start, Bias::Left)
12913                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12914                    })
12915                    .collect::<Vec<_>>();
12916
12917                drop(snapshot);
12918                this.change_selections(None, cx, |selections| {
12919                    selections.select_ranges(new_selected_ranges)
12920                });
12921            }
12922        });
12923
12924        self.ime_transaction = self.ime_transaction.or(transaction);
12925        if let Some(transaction) = self.ime_transaction {
12926            self.buffer.update(cx, |buffer, cx| {
12927                buffer.group_until_transaction(transaction, cx);
12928            });
12929        }
12930
12931        if self.text_highlights::<InputComposition>(cx).is_none() {
12932            self.ime_transaction.take();
12933        }
12934    }
12935
12936    fn bounds_for_range(
12937        &mut self,
12938        range_utf16: Range<usize>,
12939        element_bounds: gpui::Bounds<Pixels>,
12940        cx: &mut ViewContext<Self>,
12941    ) -> Option<gpui::Bounds<Pixels>> {
12942        let text_layout_details = self.text_layout_details(cx);
12943        let style = &text_layout_details.editor_style;
12944        let font_id = cx.text_system().resolve_font(&style.text.font());
12945        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12946        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12947
12948        let em_width = cx
12949            .text_system()
12950            .typographic_bounds(font_id, font_size, 'm')
12951            .unwrap()
12952            .size
12953            .width;
12954
12955        let snapshot = self.snapshot(cx);
12956        let scroll_position = snapshot.scroll_position();
12957        let scroll_left = scroll_position.x * em_width;
12958
12959        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12960        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12961            + self.gutter_dimensions.width;
12962        let y = line_height * (start.row().as_f32() - scroll_position.y);
12963
12964        Some(Bounds {
12965            origin: element_bounds.origin + point(x, y),
12966            size: size(em_width, line_height),
12967        })
12968    }
12969}
12970
12971trait SelectionExt {
12972    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12973    fn spanned_rows(
12974        &self,
12975        include_end_if_at_line_start: bool,
12976        map: &DisplaySnapshot,
12977    ) -> Range<MultiBufferRow>;
12978}
12979
12980impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12981    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12982        let start = self
12983            .start
12984            .to_point(&map.buffer_snapshot)
12985            .to_display_point(map);
12986        let end = self
12987            .end
12988            .to_point(&map.buffer_snapshot)
12989            .to_display_point(map);
12990        if self.reversed {
12991            end..start
12992        } else {
12993            start..end
12994        }
12995    }
12996
12997    fn spanned_rows(
12998        &self,
12999        include_end_if_at_line_start: bool,
13000        map: &DisplaySnapshot,
13001    ) -> Range<MultiBufferRow> {
13002        let start = self.start.to_point(&map.buffer_snapshot);
13003        let mut end = self.end.to_point(&map.buffer_snapshot);
13004        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13005            end.row -= 1;
13006        }
13007
13008        let buffer_start = map.prev_line_boundary(start).0;
13009        let buffer_end = map.next_line_boundary(end).0;
13010        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13011    }
13012}
13013
13014impl<T: InvalidationRegion> InvalidationStack<T> {
13015    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13016    where
13017        S: Clone + ToOffset,
13018    {
13019        while let Some(region) = self.last() {
13020            let all_selections_inside_invalidation_ranges =
13021                if selections.len() == region.ranges().len() {
13022                    selections
13023                        .iter()
13024                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13025                        .all(|(selection, invalidation_range)| {
13026                            let head = selection.head().to_offset(buffer);
13027                            invalidation_range.start <= head && invalidation_range.end >= head
13028                        })
13029                } else {
13030                    false
13031                };
13032
13033            if all_selections_inside_invalidation_ranges {
13034                break;
13035            } else {
13036                self.pop();
13037            }
13038        }
13039    }
13040}
13041
13042impl<T> Default for InvalidationStack<T> {
13043    fn default() -> Self {
13044        Self(Default::default())
13045    }
13046}
13047
13048impl<T> Deref for InvalidationStack<T> {
13049    type Target = Vec<T>;
13050
13051    fn deref(&self) -> &Self::Target {
13052        &self.0
13053    }
13054}
13055
13056impl<T> DerefMut for InvalidationStack<T> {
13057    fn deref_mut(&mut self) -> &mut Self::Target {
13058        &mut self.0
13059    }
13060}
13061
13062impl InvalidationRegion for SnippetState {
13063    fn ranges(&self) -> &[Range<Anchor>] {
13064        &self.ranges[self.active_index]
13065    }
13066}
13067
13068pub fn diagnostic_block_renderer(
13069    diagnostic: Diagnostic,
13070    max_message_rows: Option<u8>,
13071    allow_closing: bool,
13072    _is_valid: bool,
13073) -> RenderBlock {
13074    let (text_without_backticks, code_ranges) =
13075        highlight_diagnostic_message(&diagnostic, max_message_rows);
13076
13077    Box::new(move |cx: &mut BlockContext| {
13078        let group_id: SharedString = cx.block_id.to_string().into();
13079
13080        let mut text_style = cx.text_style().clone();
13081        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13082        let theme_settings = ThemeSettings::get_global(cx);
13083        text_style.font_family = theme_settings.buffer_font.family.clone();
13084        text_style.font_style = theme_settings.buffer_font.style;
13085        text_style.font_features = theme_settings.buffer_font.features.clone();
13086        text_style.font_weight = theme_settings.buffer_font.weight;
13087
13088        let multi_line_diagnostic = diagnostic.message.contains('\n');
13089
13090        let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13091            if multi_line_diagnostic {
13092                v_flex()
13093            } else {
13094                h_flex()
13095            }
13096            .when(allow_closing, |div| {
13097                div.children(diagnostic.is_primary.then(|| {
13098                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13099                        .icon_color(Color::Muted)
13100                        .size(ButtonSize::Compact)
13101                        .style(ButtonStyle::Transparent)
13102                        .visible_on_hover(group_id.clone())
13103                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13104                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13105                }))
13106            })
13107            .child(
13108                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13109                    .icon_color(Color::Muted)
13110                    .size(ButtonSize::Compact)
13111                    .style(ButtonStyle::Transparent)
13112                    .visible_on_hover(group_id.clone())
13113                    .on_click({
13114                        let message = diagnostic.message.clone();
13115                        move |_click, cx| {
13116                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13117                        }
13118                    })
13119                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13120            )
13121        };
13122
13123        let icon_size = buttons(&diagnostic, cx.block_id)
13124            .into_any_element()
13125            .layout_as_root(AvailableSpace::min_size(), cx);
13126
13127        h_flex()
13128            .id(cx.block_id)
13129            .group(group_id.clone())
13130            .relative()
13131            .size_full()
13132            .pl(cx.gutter_dimensions.width)
13133            .w(cx.max_width + cx.gutter_dimensions.width)
13134            .child(
13135                div()
13136                    .flex()
13137                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13138                    .flex_shrink(),
13139            )
13140            .child(buttons(&diagnostic, cx.block_id))
13141            .child(div().flex().flex_shrink_0().child(
13142                StyledText::new(text_without_backticks.clone()).with_highlights(
13143                    &text_style,
13144                    code_ranges.iter().map(|range| {
13145                        (
13146                            range.clone(),
13147                            HighlightStyle {
13148                                font_weight: Some(FontWeight::BOLD),
13149                                ..Default::default()
13150                            },
13151                        )
13152                    }),
13153                ),
13154            ))
13155            .into_any_element()
13156    })
13157}
13158
13159pub fn highlight_diagnostic_message(
13160    diagnostic: &Diagnostic,
13161    mut max_message_rows: Option<u8>,
13162) -> (SharedString, Vec<Range<usize>>) {
13163    let mut text_without_backticks = String::new();
13164    let mut code_ranges = Vec::new();
13165
13166    if let Some(source) = &diagnostic.source {
13167        text_without_backticks.push_str(&source);
13168        code_ranges.push(0..source.len());
13169        text_without_backticks.push_str(": ");
13170    }
13171
13172    let mut prev_offset = 0;
13173    let mut in_code_block = false;
13174    let has_row_limit = max_message_rows.is_some();
13175    let mut newline_indices = diagnostic
13176        .message
13177        .match_indices('\n')
13178        .filter(|_| has_row_limit)
13179        .map(|(ix, _)| ix)
13180        .fuse()
13181        .peekable();
13182
13183    for (quote_ix, _) in diagnostic
13184        .message
13185        .match_indices('`')
13186        .chain([(diagnostic.message.len(), "")])
13187    {
13188        let mut first_newline_ix = None;
13189        let mut last_newline_ix = None;
13190        while let Some(newline_ix) = newline_indices.peek() {
13191            if *newline_ix < quote_ix {
13192                if first_newline_ix.is_none() {
13193                    first_newline_ix = Some(*newline_ix);
13194                }
13195                last_newline_ix = Some(*newline_ix);
13196
13197                if let Some(rows_left) = &mut max_message_rows {
13198                    if *rows_left == 0 {
13199                        break;
13200                    } else {
13201                        *rows_left -= 1;
13202                    }
13203                }
13204                let _ = newline_indices.next();
13205            } else {
13206                break;
13207            }
13208        }
13209        let prev_len = text_without_backticks.len();
13210        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13211        text_without_backticks.push_str(new_text);
13212        if in_code_block {
13213            code_ranges.push(prev_len..text_without_backticks.len());
13214        }
13215        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13216        in_code_block = !in_code_block;
13217        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13218            text_without_backticks.push_str("...");
13219            break;
13220        }
13221    }
13222
13223    (text_without_backticks.into(), code_ranges)
13224}
13225
13226fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13227    match severity {
13228        DiagnosticSeverity::ERROR => colors.error,
13229        DiagnosticSeverity::WARNING => colors.warning,
13230        DiagnosticSeverity::INFORMATION => colors.info,
13231        DiagnosticSeverity::HINT => colors.info,
13232        _ => colors.ignored,
13233    }
13234}
13235
13236pub fn styled_runs_for_code_label<'a>(
13237    label: &'a CodeLabel,
13238    syntax_theme: &'a theme::SyntaxTheme,
13239) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13240    let fade_out = HighlightStyle {
13241        fade_out: Some(0.35),
13242        ..Default::default()
13243    };
13244
13245    let mut prev_end = label.filter_range.end;
13246    label
13247        .runs
13248        .iter()
13249        .enumerate()
13250        .flat_map(move |(ix, (range, highlight_id))| {
13251            let style = if let Some(style) = highlight_id.style(syntax_theme) {
13252                style
13253            } else {
13254                return Default::default();
13255            };
13256            let mut muted_style = style;
13257            muted_style.highlight(fade_out);
13258
13259            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13260            if range.start >= label.filter_range.end {
13261                if range.start > prev_end {
13262                    runs.push((prev_end..range.start, fade_out));
13263                }
13264                runs.push((range.clone(), muted_style));
13265            } else if range.end <= label.filter_range.end {
13266                runs.push((range.clone(), style));
13267            } else {
13268                runs.push((range.start..label.filter_range.end, style));
13269                runs.push((label.filter_range.end..range.end, muted_style));
13270            }
13271            prev_end = cmp::max(prev_end, range.end);
13272
13273            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13274                runs.push((prev_end..label.text.len(), fade_out));
13275            }
13276
13277            runs
13278        })
13279}
13280
13281pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13282    let mut prev_index = 0;
13283    let mut prev_codepoint: Option<char> = None;
13284    text.char_indices()
13285        .chain([(text.len(), '\0')])
13286        .filter_map(move |(index, codepoint)| {
13287            let prev_codepoint = prev_codepoint.replace(codepoint)?;
13288            let is_boundary = index == text.len()
13289                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13290                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13291            if is_boundary {
13292                let chunk = &text[prev_index..index];
13293                prev_index = index;
13294                Some(chunk)
13295            } else {
13296                None
13297            }
13298        })
13299}
13300
13301pub trait RangeToAnchorExt: Sized {
13302    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13303
13304    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13305        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13306        anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13307    }
13308}
13309
13310impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13311    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13312        let start_offset = self.start.to_offset(snapshot);
13313        let end_offset = self.end.to_offset(snapshot);
13314        if start_offset == end_offset {
13315            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13316        } else {
13317            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13318        }
13319    }
13320}
13321
13322pub trait RowExt {
13323    fn as_f32(&self) -> f32;
13324
13325    fn next_row(&self) -> Self;
13326
13327    fn previous_row(&self) -> Self;
13328
13329    fn minus(&self, other: Self) -> u32;
13330}
13331
13332impl RowExt for DisplayRow {
13333    fn as_f32(&self) -> f32 {
13334        self.0 as f32
13335    }
13336
13337    fn next_row(&self) -> Self {
13338        Self(self.0 + 1)
13339    }
13340
13341    fn previous_row(&self) -> Self {
13342        Self(self.0.saturating_sub(1))
13343    }
13344
13345    fn minus(&self, other: Self) -> u32 {
13346        self.0 - other.0
13347    }
13348}
13349
13350impl RowExt for MultiBufferRow {
13351    fn as_f32(&self) -> f32 {
13352        self.0 as f32
13353    }
13354
13355    fn next_row(&self) -> Self {
13356        Self(self.0 + 1)
13357    }
13358
13359    fn previous_row(&self) -> Self {
13360        Self(self.0.saturating_sub(1))
13361    }
13362
13363    fn minus(&self, other: Self) -> u32 {
13364        self.0 - other.0
13365    }
13366}
13367
13368trait RowRangeExt {
13369    type Row;
13370
13371    fn len(&self) -> usize;
13372
13373    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13374}
13375
13376impl RowRangeExt for Range<MultiBufferRow> {
13377    type Row = MultiBufferRow;
13378
13379    fn len(&self) -> usize {
13380        (self.end.0 - self.start.0) as usize
13381    }
13382
13383    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13384        (self.start.0..self.end.0).map(MultiBufferRow)
13385    }
13386}
13387
13388impl RowRangeExt for Range<DisplayRow> {
13389    type Row = DisplayRow;
13390
13391    fn len(&self) -> usize {
13392        (self.end.0 - self.start.0) as usize
13393    }
13394
13395    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13396        (self.start.0..self.end.0).map(DisplayRow)
13397    }
13398}
13399
13400fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13401    if hunk.diff_base_byte_range.is_empty() {
13402        DiffHunkStatus::Added
13403    } else if hunk.associated_range.is_empty() {
13404        DiffHunkStatus::Removed
13405    } else {
13406        DiffHunkStatus::Modified
13407    }
13408}
13409
13410/// If select range has more than one line, we
13411/// just point the cursor to range.start.
13412fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13413    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13414        range
13415    } else {
13416        range.start..range.start
13417    }
13418}